babylon.no-module.max.js 5.8 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527104528104529104530104531104532104533104534104535104536104537104538104539104540104541104542104543104544104545104546104547104548104549104550104551104552104553104554104555104556104557104558104559104560104561104562104563104564104565104566104567104568104569104570104571104572104573104574104575104576104577104578104579104580104581104582104583104584104585104586104587104588104589104590104591104592104593104594104595104596104597104598104599104600104601104602104603104604104605104606104607104608104609104610104611104612104613104614104615104616104617104618104619104620104621104622104623104624104625104626104627104628104629104630104631104632104633104634104635104636104637104638104639104640104641104642104643104644104645104646104647104648104649104650104651104652104653104654104655104656104657104658104659104660104661104662104663104664104665104666104667104668104669104670104671104672104673104674104675104676104677104678104679104680104681104682104683104684104685104686104687104688104689104690104691104692104693104694104695104696104697104698104699104700104701104702104703104704104705104706104707104708104709104710104711104712104713104714104715104716104717104718104719104720104721104722104723104724104725104726104727104728104729104730104731104732104733104734104735104736104737104738104739104740104741104742104743104744104745104746104747104748104749104750104751104752104753104754104755104756104757104758104759104760104761104762104763104764104765104766104767104768104769104770104771104772104773104774104775104776104777104778104779104780104781104782104783104784104785104786104787104788104789104790104791104792104793104794104795104796104797104798104799104800104801104802104803104804104805104806104807104808104809104810104811104812104813104814104815104816104817104818104819104820104821104822104823104824104825104826104827104828104829104830104831104832104833104834104835104836104837104838104839104840104841104842104843104844104845104846104847104848104849104850104851104852104853104854104855104856104857104858104859104860104861104862104863104864104865104866104867104868104869104870104871104872104873104874104875104876104877104878104879104880104881104882104883104884104885104886104887104888104889104890104891104892104893104894104895104896104897104898104899104900104901104902104903104904104905104906104907104908104909104910104911104912104913104914104915104916104917104918104919104920104921104922104923104924104925104926104927104928104929104930104931104932104933104934104935104936104937104938104939104940104941104942104943104944104945104946104947104948104949104950104951104952104953104954104955104956104957104958104959104960104961104962104963104964104965104966104967104968104969104970104971104972104973104974104975104976104977104978104979104980104981104982104983104984104985104986104987104988104989104990104991104992104993104994104995104996104997104998104999105000105001105002105003105004105005105006105007105008105009105010105011105012105013105014105015105016105017105018105019105020105021105022105023105024105025105026105027105028105029105030105031105032105033105034105035105036105037105038105039105040105041105042105043105044105045105046105047105048105049105050105051105052105053105054105055105056105057105058105059105060105061105062105063105064105065105066105067105068105069105070105071105072105073105074105075105076105077105078105079105080105081105082105083105084105085105086105087105088105089105090105091105092105093105094105095105096105097105098105099105100105101105102105103105104105105105106105107105108105109105110105111105112105113105114105115105116105117105118105119105120105121105122105123105124105125105126105127105128105129105130105131105132105133105134105135105136105137105138105139105140105141105142105143105144105145105146105147105148105149105150105151105152105153105154105155105156105157105158105159105160105161105162105163105164105165105166105167105168105169105170105171105172105173105174105175105176105177105178105179105180105181105182105183105184105185105186105187105188105189105190105191105192105193105194105195105196105197105198105199105200105201105202105203105204105205105206105207105208105209105210105211105212105213105214105215105216105217105218105219105220105221105222105223105224105225105226105227105228105229105230105231105232105233105234105235105236105237105238105239105240105241105242105243105244105245105246105247105248105249105250105251105252105253105254105255105256105257105258105259105260105261105262105263105264105265105266105267105268105269105270105271105272105273105274105275105276105277105278105279105280105281105282105283105284105285105286105287105288105289105290105291105292105293105294105295105296105297105298105299105300105301105302105303105304105305105306105307105308105309105310105311105312105313105314105315105316105317105318105319105320105321105322105323105324105325105326105327105328105329105330105331105332105333105334105335105336105337105338105339105340105341105342105343105344105345105346105347105348105349105350105351105352105353105354105355105356105357105358105359105360105361105362105363105364105365105366105367105368105369105370105371105372105373105374105375105376105377105378105379105380105381105382105383105384105385105386105387105388105389105390105391105392105393105394105395105396105397105398105399105400105401105402105403105404105405105406105407105408105409105410105411105412105413105414105415105416105417105418105419105420105421105422105423105424105425105426105427105428105429105430105431105432105433105434105435105436105437105438105439105440105441105442105443105444105445105446105447105448105449105450105451105452105453105454105455105456105457105458105459105460105461105462105463105464105465105466105467105468105469105470105471105472105473105474105475105476105477105478105479105480105481105482105483105484105485105486105487105488105489105490105491105492105493105494105495105496105497105498105499105500105501105502105503105504105505105506105507105508105509105510105511105512105513105514105515105516105517105518105519105520105521105522105523105524105525105526105527105528105529105530105531105532105533105534105535105536105537105538105539105540105541105542105543105544105545105546105547105548105549105550105551105552105553105554105555105556105557105558105559105560105561105562105563105564105565105566105567105568105569105570105571105572105573105574105575105576105577105578105579105580105581105582105583105584105585105586105587105588105589105590105591105592105593105594105595105596105597105598105599105600105601105602105603105604105605105606105607105608105609105610105611105612105613105614105615105616105617105618105619105620105621105622105623105624105625105626105627105628105629105630105631105632105633105634105635105636105637105638105639105640105641105642105643105644105645105646105647105648105649105650105651105652105653105654105655105656105657105658105659105660105661105662105663105664105665105666105667105668105669105670105671105672105673105674105675105676105677105678105679105680105681105682105683105684105685105686105687105688105689105690105691105692105693105694105695105696105697105698105699105700105701105702105703105704105705105706105707105708105709105710105711105712105713105714105715105716105717105718105719105720105721105722105723105724105725105726105727105728105729105730105731105732105733105734105735105736105737105738105739105740105741105742105743105744105745105746105747105748105749105750105751105752105753105754105755105756105757105758105759105760105761105762105763105764105765105766105767105768105769105770105771105772105773105774105775105776105777105778105779105780105781105782105783105784105785105786105787105788105789105790105791105792105793105794105795105796105797105798105799105800105801105802105803105804105805105806105807105808105809105810105811105812105813105814105815105816105817105818105819105820105821105822105823105824105825105826105827105828105829105830105831105832105833105834105835105836105837105838105839105840105841105842105843105844105845105846105847105848105849105850105851105852105853105854105855105856105857105858105859105860105861105862105863105864105865105866105867105868105869105870105871105872105873105874105875105876105877105878105879105880105881105882105883105884105885105886105887105888105889105890105891105892105893105894105895105896105897105898105899105900105901105902105903105904105905105906105907105908105909105910105911105912105913105914105915105916105917105918105919105920105921105922105923105924105925105926105927105928105929105930105931105932105933105934105935105936105937105938105939105940105941105942105943105944105945105946105947105948105949105950105951105952105953105954105955105956105957105958105959105960105961105962105963105964105965105966105967105968105969105970105971105972105973105974105975105976105977105978105979105980105981105982105983105984105985105986105987105988105989105990105991105992105993105994105995105996105997105998105999106000106001106002106003106004106005106006106007106008106009106010106011106012106013106014106015106016106017106018106019106020106021106022106023106024106025106026106027106028106029106030106031106032106033106034106035106036106037106038106039106040106041106042106043106044106045106046106047106048106049106050106051106052106053106054106055106056106057106058106059106060106061106062106063106064106065106066106067106068106069106070106071106072106073106074106075106076106077106078106079106080106081106082106083106084106085106086106087106088106089106090106091106092106093106094106095106096106097106098106099106100106101106102106103106104106105106106106107106108106109106110106111106112106113106114106115106116106117106118106119106120106121106122106123106124106125106126106127106128106129106130106131106132106133106134106135106136106137106138106139106140106141106142106143106144106145106146106147106148106149106150106151106152106153106154106155106156106157106158106159106160106161106162106163106164106165106166106167106168106169106170106171106172106173106174106175106176106177106178106179106180106181106182106183106184106185106186106187106188106189106190106191106192106193106194106195106196106197106198106199106200106201106202106203106204106205106206106207106208106209106210106211106212106213106214106215106216106217106218106219106220106221106222106223106224106225106226106227106228106229106230106231106232106233106234106235106236106237106238106239106240106241106242106243106244106245106246106247106248106249106250106251106252106253106254106255106256106257106258106259106260106261106262106263106264106265106266106267106268106269106270106271106272106273106274106275106276106277106278106279106280106281106282106283106284106285106286106287106288106289106290106291106292106293106294106295106296106297106298106299106300106301106302106303106304106305106306106307106308106309106310106311106312106313106314106315106316106317106318106319106320106321106322106323106324106325106326106327106328106329106330106331106332106333106334106335106336106337106338106339106340106341106342106343106344106345106346106347106348106349106350106351106352106353106354106355106356106357106358106359106360106361106362106363106364106365106366106367106368106369106370106371106372106373106374106375106376106377106378106379106380106381106382106383106384106385106386106387106388106389106390106391106392106393106394106395106396106397106398106399106400106401106402106403106404106405106406106407106408106409106410106411106412106413106414106415106416106417106418106419106420106421106422106423106424106425106426106427106428106429106430106431106432106433106434106435106436106437106438106439106440106441106442106443106444106445106446106447106448106449106450106451106452106453106454106455106456106457106458106459106460106461106462106463106464106465106466106467106468106469106470106471106472106473106474106475106476106477106478106479106480106481106482106483106484106485106486106487106488106489106490106491106492106493106494106495106496106497106498106499106500106501106502106503106504106505106506106507106508106509106510106511106512106513106514106515106516106517106518106519106520106521106522106523106524106525106526106527106528106529106530106531106532106533106534106535106536106537106538106539106540106541106542106543106544106545106546106547106548106549106550106551106552106553106554106555106556106557106558106559106560106561106562106563106564106565106566106567106568106569106570106571106572106573106574106575106576106577106578106579106580106581106582106583106584106585106586106587106588106589106590106591106592106593106594106595106596106597106598106599106600106601106602106603106604106605106606106607106608106609106610106611106612106613106614106615106616106617106618106619106620106621106622106623106624106625106626106627106628106629106630106631106632106633106634106635106636106637106638106639106640106641106642106643106644106645106646106647106648106649106650106651106652106653106654106655106656106657106658106659106660106661106662106663106664106665106666106667106668106669106670106671106672106673106674106675106676106677106678106679106680106681106682106683106684106685106686106687106688106689106690106691106692106693106694106695106696106697106698106699106700106701106702106703106704106705106706106707106708106709106710106711106712106713106714106715106716106717106718106719106720106721106722106723106724106725106726106727106728106729106730106731106732106733106734106735106736106737106738106739106740106741106742106743106744106745106746106747106748106749106750106751106752106753106754106755106756106757106758106759106760106761106762106763106764106765106766106767106768106769106770106771106772106773106774106775106776106777106778106779106780106781106782106783106784106785106786106787106788106789106790106791106792106793106794106795106796106797106798106799106800106801106802106803106804106805106806106807106808106809106810106811106812106813106814106815106816106817106818106819106820106821106822106823106824106825106826106827106828106829106830106831106832106833106834106835106836106837106838106839106840106841106842106843106844106845106846106847106848106849106850106851106852106853106854106855106856106857106858106859106860106861106862106863106864106865106866106867106868106869106870106871106872106873106874106875106876106877106878106879106880106881106882106883106884106885106886106887106888106889106890106891106892106893106894106895106896106897106898106899106900106901106902106903106904106905106906106907106908106909106910106911106912106913106914106915106916106917106918106919106920106921106922106923106924106925106926106927106928106929106930106931106932106933106934106935106936106937106938106939106940106941106942106943106944106945106946106947106948106949106950106951106952106953106954106955106956106957106958106959106960106961106962106963106964106965106966106967106968106969106970106971106972106973106974106975106976106977106978106979106980106981106982106983106984106985106986106987106988106989106990106991106992106993106994106995106996106997106998106999107000107001107002107003107004107005107006107007107008107009107010107011107012107013107014107015107016107017107018107019107020107021107022107023107024107025107026107027107028107029107030107031107032107033107034107035107036107037107038107039107040107041107042107043107044107045107046107047107048107049107050107051107052107053107054107055107056107057107058107059107060107061107062107063107064107065107066107067107068107069107070107071107072107073107074107075107076107077107078107079107080107081107082107083107084107085107086107087107088107089107090107091107092107093107094107095107096107097107098107099107100107101107102107103107104107105107106107107107108107109107110107111107112107113107114107115107116107117107118107119107120107121107122107123107124107125107126107127107128107129107130107131107132107133107134107135107136107137107138107139107140107141107142107143107144107145107146107147107148107149107150107151107152107153107154107155107156107157107158107159107160107161107162107163107164107165107166107167107168107169107170107171107172107173107174107175107176107177107178107179107180107181107182107183107184107185107186107187107188107189107190107191107192107193107194107195107196107197107198107199107200107201107202107203107204107205107206107207107208107209107210107211107212107213107214107215107216107217107218107219107220107221107222107223107224107225107226107227107228107229107230107231107232107233107234107235107236107237107238107239107240107241107242107243107244107245107246107247107248107249107250107251107252107253107254107255107256107257107258107259107260107261107262107263107264107265107266107267107268107269107270107271107272107273107274107275107276107277107278107279107280107281107282107283107284107285107286107287107288107289107290107291107292107293107294107295107296107297107298107299107300107301107302107303107304107305107306107307107308107309107310107311107312107313107314107315107316107317107318107319107320107321107322107323107324107325107326107327107328107329107330107331107332107333107334107335107336107337107338107339107340107341107342107343107344107345107346107347107348107349107350107351107352107353107354107355107356107357107358107359107360107361107362107363107364107365107366107367107368107369107370107371107372107373107374107375107376107377107378107379107380107381107382107383107384107385107386107387107388107389107390107391107392107393107394107395107396107397107398107399107400107401107402107403107404107405107406107407107408107409107410107411107412107413107414107415107416107417107418107419107420107421107422107423107424107425107426107427107428107429107430107431107432107433107434107435107436107437107438107439107440107441107442107443107444107445107446107447107448107449107450107451107452107453107454107455107456107457107458107459107460107461107462107463107464107465107466107467107468107469107470107471107472107473107474107475107476107477107478107479107480107481107482107483107484107485107486107487107488107489107490107491107492107493107494107495107496107497107498107499107500107501107502107503107504107505107506107507107508107509107510107511107512107513107514107515107516107517107518107519107520107521107522107523107524107525107526107527107528107529107530107531107532107533107534107535107536107537107538107539107540107541107542107543107544107545107546107547107548107549107550107551107552107553107554107555107556107557107558107559107560107561107562107563107564107565107566107567107568107569107570107571107572107573107574107575107576107577107578107579107580107581107582107583107584107585107586107587107588107589107590107591107592107593107594107595107596107597107598107599107600107601107602107603107604107605107606107607107608107609107610107611107612107613107614107615107616107617107618107619107620107621107622107623107624107625107626107627107628107629107630107631107632107633107634107635107636107637107638107639107640107641107642107643107644107645107646107647107648107649107650107651107652107653107654107655107656107657107658107659107660107661107662107663107664107665107666107667107668107669107670107671107672107673107674107675107676107677107678107679107680107681107682107683107684107685107686107687107688107689107690107691107692107693107694107695107696107697107698107699107700107701107702107703107704107705107706107707107708107709107710107711107712107713107714107715107716107717107718107719107720107721107722107723107724107725107726107727107728107729107730107731107732107733107734107735107736107737107738107739107740107741107742107743107744107745107746107747107748107749107750107751107752107753107754107755107756107757107758107759107760107761107762107763107764107765107766107767107768107769107770107771107772107773107774107775107776107777107778107779107780107781107782107783107784107785107786107787107788107789107790107791107792107793107794107795107796107797107798107799107800107801107802107803107804107805107806107807107808107809107810107811107812107813107814107815107816107817107818107819107820107821107822107823107824107825107826107827107828107829107830107831107832107833107834107835107836107837107838107839107840107841107842107843107844107845107846107847107848107849107850107851107852107853107854107855107856107857107858107859107860107861107862107863107864107865107866107867107868107869107870107871107872107873107874107875107876107877107878107879107880107881107882107883107884107885107886107887107888107889107890107891107892107893107894107895107896107897107898107899107900107901107902107903107904107905107906107907107908107909107910107911107912107913107914107915107916107917107918107919107920107921107922107923107924107925107926107927107928107929107930107931107932107933107934107935107936107937107938107939107940107941107942107943107944107945107946107947107948107949107950107951107952107953107954107955107956107957107958107959107960107961107962107963107964107965107966107967107968107969107970107971107972107973107974107975107976107977107978107979107980107981107982107983107984107985107986107987107988107989107990107991107992107993107994107995107996107997107998107999108000108001108002108003108004108005108006108007108008108009108010108011108012108013108014108015108016108017108018108019108020108021108022108023108024108025108026108027108028108029108030108031108032108033108034108035108036108037108038108039108040108041108042108043108044108045108046108047108048108049108050108051108052108053108054108055108056108057108058108059108060108061108062108063108064108065108066108067108068108069108070108071108072108073108074108075108076108077108078108079108080108081108082108083108084108085108086108087108088108089108090108091108092108093108094108095108096108097108098108099108100108101108102108103108104108105108106108107108108108109108110108111108112108113108114108115108116108117108118108119108120108121108122108123108124108125108126108127108128108129108130108131108132108133108134108135108136108137108138108139108140108141108142108143108144108145108146108147108148108149108150108151108152108153108154108155108156108157108158108159108160108161108162108163108164108165108166108167108168108169108170108171108172108173108174108175108176108177108178108179108180108181108182108183108184108185108186108187108188108189108190108191108192108193108194108195108196108197108198108199108200108201108202108203108204108205108206108207108208108209108210108211108212108213108214108215108216108217108218108219108220108221108222108223108224108225108226108227108228108229108230108231108232108233108234108235108236108237108238108239108240108241108242108243108244108245108246108247108248108249108250108251108252108253108254108255108256108257108258108259108260108261108262108263108264108265108266108267108268108269108270108271108272108273108274108275108276108277108278108279108280108281108282108283108284108285108286108287108288108289108290108291108292108293108294108295108296108297108298108299108300108301108302108303108304108305108306108307108308108309108310108311108312108313108314108315108316108317108318108319108320108321108322108323108324108325108326108327108328108329108330108331108332108333108334108335108336108337108338108339108340108341108342108343108344108345108346108347108348108349108350108351108352108353108354108355108356108357108358108359108360108361108362108363108364108365108366108367108368108369108370108371108372108373108374108375108376108377108378108379108380108381108382108383108384108385108386108387108388108389108390108391108392108393108394108395108396108397108398108399108400108401108402108403108404108405108406108407108408108409108410108411108412108413108414108415108416108417108418108419108420108421108422108423108424108425108426108427108428108429108430108431108432108433108434108435108436108437108438108439108440108441108442108443108444108445108446108447108448108449108450108451108452108453108454108455108456108457108458108459108460108461108462108463108464108465108466108467108468108469108470108471108472108473108474108475108476108477108478108479108480108481108482108483108484108485108486108487108488108489108490108491108492108493108494108495108496108497108498108499108500108501108502108503108504108505108506108507108508108509108510108511108512108513108514108515108516108517108518108519108520108521108522108523108524108525108526108527108528108529108530108531108532108533108534108535108536108537108538108539108540108541108542108543108544108545108546108547108548108549108550108551108552108553108554108555108556108557108558108559108560108561108562108563108564108565108566108567108568108569108570108571108572108573108574108575108576108577108578108579108580108581108582108583108584108585108586108587108588108589108590108591108592108593108594108595108596108597108598108599108600108601108602108603108604108605108606108607108608108609108610108611108612108613108614108615108616108617108618108619108620108621108622108623108624108625108626108627108628108629108630108631108632108633108634108635108636108637108638108639108640108641108642108643108644108645108646108647108648108649108650108651108652108653108654108655108656108657108658108659108660108661108662108663108664108665108666108667108668108669108670108671108672108673108674108675108676108677108678108679108680108681108682108683108684108685108686108687108688108689108690108691108692108693108694108695108696108697108698108699108700108701108702108703108704108705108706108707108708108709108710108711108712108713108714108715108716108717108718108719108720108721108722108723108724108725108726108727108728108729108730108731108732108733108734108735108736108737108738108739108740108741108742108743108744108745108746108747108748108749108750108751108752108753108754108755108756108757108758108759108760108761108762108763108764108765108766108767108768108769108770108771108772108773108774108775108776108777108778108779108780108781108782108783108784108785108786108787108788108789108790108791108792108793108794108795108796108797108798108799108800108801108802108803108804108805108806108807108808108809108810108811108812108813108814108815108816108817108818108819108820108821108822108823108824108825108826108827108828108829108830108831108832108833108834108835108836108837108838108839108840108841108842108843108844108845108846108847108848108849108850108851108852108853108854108855108856108857108858108859108860108861108862108863108864108865108866108867108868108869108870108871108872108873108874108875108876108877108878108879108880108881108882108883108884108885108886108887108888108889108890108891108892108893108894108895108896108897108898108899108900108901108902108903108904108905108906108907108908108909108910108911108912108913108914108915108916108917108918108919108920108921108922108923108924108925108926108927108928108929108930108931108932108933108934108935108936108937108938108939108940108941108942108943108944108945108946108947108948108949108950108951108952108953108954108955108956108957108958108959108960108961108962108963108964108965108966108967108968108969108970108971108972108973108974108975108976108977108978108979108980108981108982108983108984108985108986108987108988108989108990108991108992108993108994108995108996108997108998108999109000109001109002109003109004109005109006109007109008109009109010109011109012109013109014109015109016109017109018109019109020109021109022109023109024109025109026109027109028109029109030109031109032109033109034109035109036109037109038109039109040109041109042109043109044109045109046109047109048109049109050109051109052109053109054109055109056109057109058109059109060109061109062109063109064109065109066109067109068109069109070109071109072109073109074109075109076109077109078109079109080109081109082109083109084109085109086109087109088109089109090109091109092109093109094109095109096109097109098109099109100109101109102109103109104109105109106109107109108109109109110109111109112109113109114109115109116109117109118109119109120109121109122109123109124109125109126109127109128109129109130109131109132109133109134109135109136109137109138109139109140109141109142109143109144109145109146109147109148109149109150109151109152109153109154109155109156109157109158109159109160109161109162109163109164109165109166109167109168109169109170109171109172109173109174109175109176109177109178109179109180109181109182109183109184109185109186109187109188109189109190109191109192109193109194109195109196109197109198109199109200109201109202109203109204109205109206109207109208109209109210109211109212109213109214109215109216109217109218109219109220109221109222109223109224109225109226109227109228109229109230109231109232109233109234109235109236109237109238109239109240109241109242109243109244109245109246109247109248109249109250109251109252109253109254109255109256109257109258109259109260109261109262109263109264109265109266109267109268109269109270109271109272109273109274109275109276109277109278109279109280109281109282109283109284109285109286109287109288109289109290109291109292109293109294109295109296109297109298109299109300109301109302109303109304109305109306109307109308109309109310109311109312109313109314109315109316109317109318109319109320109321109322109323109324109325109326109327109328109329109330109331109332109333109334109335109336109337109338109339109340109341109342109343109344109345109346109347109348109349109350109351109352109353109354109355109356109357109358109359109360109361109362109363109364109365109366109367109368109369109370109371109372109373109374109375109376109377109378109379109380109381109382109383109384109385109386109387109388109389109390109391109392109393109394109395109396109397109398109399109400109401109402109403109404109405109406109407109408109409109410109411109412109413109414109415109416109417109418109419109420109421109422109423109424109425109426109427109428109429109430109431109432109433109434109435109436109437109438109439109440109441109442109443109444109445109446109447109448109449109450109451109452109453109454109455109456109457109458109459109460109461109462109463109464109465109466109467109468109469109470109471109472109473109474109475109476109477109478109479109480109481109482109483109484109485109486109487109488109489109490109491109492109493109494109495109496109497109498109499109500109501109502109503109504109505109506109507109508109509109510109511109512109513109514109515109516109517109518109519109520109521109522109523109524109525109526109527109528109529109530109531109532109533109534109535109536109537109538109539109540109541109542109543109544109545109546109547109548109549109550109551109552109553109554109555109556109557109558109559109560109561109562109563109564109565109566109567109568109569109570109571109572109573109574109575109576109577109578109579109580109581109582109583109584109585109586109587109588109589109590109591109592109593109594109595109596109597109598109599109600109601109602109603109604109605109606109607109608109609109610109611109612109613109614109615109616109617109618109619109620109621109622109623109624109625109626109627109628109629109630109631109632109633109634109635109636109637109638109639109640109641109642109643109644109645109646109647109648109649109650109651109652109653109654109655109656109657109658109659109660109661109662109663109664109665109666109667109668109669109670109671109672109673109674109675109676109677109678109679109680109681109682109683109684109685109686109687109688109689109690109691109692109693109694109695109696109697109698109699109700109701109702109703109704109705109706109707109708109709109710109711109712109713109714109715109716109717109718109719109720109721109722109723109724109725109726109727109728109729109730109731109732109733109734109735109736109737109738109739109740109741109742109743109744109745109746109747109748109749109750109751109752109753109754109755109756109757109758109759109760109761109762109763109764109765109766109767109768109769109770109771109772109773109774109775109776109777109778109779109780109781109782109783109784109785109786109787109788109789109790109791109792109793109794109795109796109797109798109799109800109801109802109803109804109805109806109807109808109809109810109811109812109813109814109815109816109817109818109819109820109821109822109823109824109825109826109827109828109829109830109831109832109833109834109835109836109837109838109839109840109841109842109843109844109845109846109847109848109849109850109851109852109853109854109855109856109857109858109859109860109861109862109863109864109865109866109867109868109869109870109871109872109873109874109875109876109877109878109879109880109881109882109883109884109885109886109887109888109889109890109891109892109893109894109895109896109897109898109899109900109901109902109903109904109905109906109907109908109909109910109911109912109913109914109915109916109917109918109919109920109921109922109923109924109925109926109927109928109929109930109931109932109933109934109935109936109937109938109939109940109941109942109943109944109945109946109947109948109949109950109951109952109953109954109955109956109957109958109959109960109961109962109963109964109965109966109967109968109969109970109971109972109973109974109975109976109977109978109979109980109981109982109983109984109985109986109987109988109989109990109991109992109993109994109995109996109997109998109999110000110001110002110003110004110005110006110007110008110009110010110011110012110013110014110015110016110017110018110019110020110021110022110023110024110025110026110027110028110029110030110031110032110033110034110035110036110037110038110039110040110041110042110043110044110045110046110047110048110049110050110051110052110053110054110055110056110057110058110059110060110061110062110063110064110065110066110067110068110069110070110071110072110073110074110075110076110077110078110079110080110081110082110083110084110085110086110087110088110089110090110091110092110093110094110095110096110097110098110099110100110101110102110103110104110105110106110107110108110109110110110111110112110113110114110115110116110117110118110119110120110121110122110123110124110125110126110127110128110129110130110131110132110133110134110135110136110137110138110139110140110141110142110143110144110145110146110147110148110149110150110151110152110153110154110155110156110157110158110159110160110161110162110163110164110165110166110167110168110169110170110171110172110173110174110175110176110177110178110179110180110181110182110183110184110185110186110187110188110189110190110191110192110193110194110195110196110197110198110199110200110201110202110203110204110205110206110207110208110209110210110211110212110213110214110215110216110217110218110219110220110221110222110223110224110225110226110227110228110229110230110231110232110233110234110235110236110237110238110239110240110241110242110243110244110245110246110247110248110249110250110251110252110253110254110255110256110257110258110259110260110261110262110263110264110265110266110267110268110269110270110271110272110273110274110275110276110277110278110279110280110281110282110283110284110285110286110287110288110289110290110291110292110293110294110295110296110297110298110299110300110301110302110303110304110305110306110307110308110309110310110311110312110313110314110315110316110317110318110319110320110321110322110323110324110325110326110327110328110329110330110331110332110333110334110335110336110337110338110339110340110341110342110343110344110345110346110347110348110349110350110351110352110353110354110355110356110357110358110359110360110361110362110363110364110365110366110367110368110369110370110371110372110373110374110375110376110377110378110379110380110381110382110383110384110385110386110387110388110389110390110391110392110393110394110395110396110397110398110399110400110401110402110403110404110405110406110407110408110409110410110411110412110413110414110415110416110417110418110419110420110421110422110423110424110425110426110427110428110429110430110431110432110433110434110435110436110437110438110439110440110441110442110443110444110445110446110447110448110449110450110451110452110453110454110455110456110457110458110459110460110461110462110463110464110465110466110467110468110469110470110471110472110473110474110475110476110477110478110479110480110481110482110483110484110485110486110487110488110489110490110491110492110493110494110495110496110497110498110499110500110501110502110503110504110505110506110507110508110509110510110511110512110513110514110515110516110517110518110519110520110521110522110523110524110525110526110527110528110529110530110531110532110533110534110535110536110537110538110539110540110541110542110543110544110545110546110547110548110549110550110551110552110553110554110555110556110557110558110559110560110561110562110563110564110565110566110567110568110569110570110571110572110573110574110575110576110577110578110579110580110581110582110583110584110585110586110587110588110589110590110591110592110593110594110595110596110597110598110599110600110601110602110603110604110605110606110607110608110609110610110611110612110613110614110615110616110617110618110619110620110621110622110623110624110625110626110627110628110629110630110631110632110633110634110635110636110637110638110639110640110641110642110643110644110645110646110647110648110649110650110651110652110653110654110655110656110657110658110659110660110661110662110663110664110665110666110667110668110669110670110671110672110673110674110675110676110677110678110679110680110681110682110683110684110685110686110687110688110689110690110691110692110693110694110695110696110697110698110699110700110701110702110703110704110705110706110707110708110709110710110711110712110713110714110715110716110717110718110719110720110721110722110723110724110725110726110727110728110729110730110731110732110733110734110735110736110737110738110739110740110741110742110743110744110745110746110747110748110749110750110751110752110753110754110755110756110757110758110759110760110761110762110763110764110765110766110767110768110769110770110771110772110773110774110775110776110777110778110779110780110781110782110783110784110785110786110787110788110789110790110791110792110793110794110795110796110797110798110799110800110801110802110803110804110805110806110807110808110809110810110811110812110813110814110815110816110817110818110819110820110821110822110823110824110825110826110827110828110829110830110831110832110833110834110835110836110837110838110839110840110841110842110843110844110845110846110847110848110849110850110851110852110853110854110855110856110857110858110859110860110861110862110863110864110865110866110867110868110869110870110871110872110873110874110875110876110877110878110879110880110881110882110883110884110885110886110887110888110889110890110891110892110893110894110895110896110897110898110899110900110901110902110903110904110905110906110907110908110909110910110911110912110913110914110915110916110917110918110919110920110921110922110923110924110925110926110927110928110929110930110931110932110933110934110935110936110937110938110939110940110941110942110943110944110945110946110947110948110949110950110951110952110953110954110955110956110957110958110959110960110961110962110963110964110965110966110967110968110969110970110971110972110973110974110975110976110977110978110979110980110981110982110983110984110985110986110987110988110989110990110991110992110993110994110995110996110997110998110999111000111001111002111003111004111005111006111007111008111009111010111011111012111013111014111015111016111017111018111019111020111021111022111023111024111025111026111027111028111029111030111031111032111033111034111035111036111037111038111039111040111041111042111043111044111045111046111047111048111049111050111051111052111053111054111055111056111057111058111059111060111061111062111063111064111065111066111067111068111069111070111071111072111073111074111075111076111077111078111079111080111081111082111083111084111085111086111087111088111089111090111091111092111093111094111095111096111097111098111099111100111101111102111103111104111105111106111107111108111109111110111111111112111113111114111115111116111117111118111119111120111121111122111123111124111125111126111127111128111129111130111131111132111133111134111135111136111137111138111139111140111141111142111143111144111145111146111147111148111149111150111151111152111153111154111155111156111157111158111159111160111161111162111163111164111165111166111167111168111169111170111171111172111173111174111175111176111177111178111179111180111181111182111183111184111185111186111187111188111189111190111191111192111193111194111195111196111197111198111199111200111201111202111203111204111205111206111207111208111209111210111211111212111213111214111215111216111217111218111219111220111221111222111223111224111225111226111227111228111229111230111231111232111233111234111235111236111237111238111239111240111241111242111243111244111245111246111247111248111249111250111251111252111253111254111255111256111257111258111259111260111261111262111263111264111265111266111267111268111269111270111271111272111273111274111275111276111277111278111279111280111281111282111283111284111285111286111287111288111289111290111291111292111293111294111295111296111297111298111299111300111301111302111303111304111305111306111307111308111309111310111311111312111313111314111315111316111317111318111319111320111321111322111323111324111325111326111327111328111329111330111331111332111333111334111335111336111337111338111339111340111341111342111343111344111345111346111347111348111349111350111351111352111353111354111355111356111357111358111359111360111361111362111363111364111365111366111367111368111369111370111371111372111373111374111375111376111377111378111379111380111381111382111383111384111385111386111387111388111389111390111391111392111393111394111395111396111397111398111399111400111401111402111403111404111405111406111407111408111409111410111411111412111413111414111415111416111417111418111419111420111421111422111423111424111425111426111427111428111429111430111431111432111433111434111435111436111437111438111439111440111441111442111443111444111445111446111447111448111449111450111451111452111453111454111455111456111457111458111459111460111461111462111463111464111465111466111467111468111469111470111471111472111473111474111475111476111477111478111479111480111481111482111483111484111485111486111487111488111489111490111491111492111493111494111495111496111497111498111499111500111501111502111503111504111505111506111507111508111509111510111511111512111513111514111515111516111517111518111519111520111521111522111523111524111525111526111527111528111529111530111531111532111533111534111535111536111537111538111539111540111541111542111543111544111545111546111547111548111549111550111551111552111553111554111555111556111557111558111559111560111561111562111563111564111565111566111567111568111569111570111571111572111573111574111575111576111577111578111579111580111581111582111583111584111585111586111587111588111589111590111591111592111593111594111595111596111597111598111599111600111601111602111603111604111605111606111607111608111609111610111611111612111613111614111615111616111617111618111619111620111621111622111623111624111625111626111627111628111629111630111631111632111633111634111635111636111637111638111639111640111641111642111643111644111645111646111647111648111649111650111651111652111653111654111655111656111657111658111659111660111661111662111663111664111665111666111667111668111669111670111671111672111673111674111675111676111677111678111679111680111681111682111683111684111685111686111687111688111689111690111691111692111693111694111695111696111697111698111699111700111701111702111703111704111705111706111707111708111709111710111711111712111713111714111715111716111717111718111719111720111721111722111723111724111725111726111727111728111729111730111731111732111733111734111735111736111737111738111739111740111741111742111743111744111745111746111747111748111749111750111751111752111753111754111755111756111757111758111759111760111761111762111763111764111765111766111767111768111769111770111771111772111773111774111775111776111777111778111779111780111781111782111783111784111785111786111787111788111789111790111791111792111793111794111795111796111797111798111799111800111801111802111803111804111805111806111807111808111809111810111811111812111813111814111815111816111817111818111819111820111821111822111823111824111825111826111827111828111829111830111831111832111833111834111835111836111837111838111839111840111841111842111843111844111845111846111847111848111849111850111851111852111853111854111855111856111857111858111859111860111861111862111863111864111865111866111867111868111869111870111871111872111873111874111875111876111877111878111879111880111881111882111883111884111885111886111887111888111889111890111891111892111893111894111895111896111897111898111899111900111901111902111903111904111905111906111907111908111909111910111911111912111913111914111915111916111917111918111919111920111921111922111923111924111925111926111927111928111929111930111931111932111933111934111935111936111937111938111939111940111941111942111943111944111945111946111947111948111949111950111951111952111953111954111955111956111957111958111959111960111961111962111963111964111965111966111967111968111969111970111971111972111973111974111975111976111977111978111979111980111981111982111983111984111985111986111987111988111989111990111991111992111993111994111995111996111997111998111999112000112001112002112003112004112005112006112007112008112009112010112011112012112013112014112015112016112017112018112019112020112021112022112023112024112025112026112027112028112029112030112031112032112033112034112035112036112037112038112039112040112041112042112043112044112045112046112047112048112049112050112051112052112053112054112055112056112057112058112059112060112061112062112063112064112065112066112067112068112069112070112071112072112073112074112075112076112077112078112079112080112081112082112083112084112085112086112087112088112089112090112091112092112093112094112095112096112097112098112099112100112101112102112103112104112105112106112107112108112109112110112111112112112113112114112115112116112117112118112119112120112121112122112123112124112125112126112127112128112129112130112131112132112133112134112135112136112137112138112139112140112141112142112143112144112145112146112147112148112149112150112151112152112153112154112155112156112157112158112159112160112161112162112163112164112165112166112167112168112169112170112171112172112173112174112175112176112177112178112179112180112181112182112183112184112185112186112187112188112189112190112191112192112193112194112195112196112197112198112199112200112201112202112203112204112205112206112207112208112209112210112211112212112213112214112215112216112217112218112219112220112221112222112223112224112225112226112227112228112229112230112231112232112233112234112235112236112237112238112239112240112241112242112243112244112245112246112247112248112249112250112251112252112253112254112255112256112257112258112259112260112261112262112263112264112265112266112267112268112269112270112271112272112273112274112275112276112277112278112279112280112281112282112283112284112285112286112287112288112289112290112291112292112293112294112295112296112297112298112299112300112301112302112303112304112305112306112307112308112309112310112311112312112313112314112315112316112317112318112319112320112321112322112323112324112325112326112327112328112329112330112331112332112333112334112335112336112337112338112339112340112341112342112343112344112345112346112347112348112349112350112351112352112353112354112355112356112357112358112359112360112361112362112363112364112365112366112367112368112369112370112371112372112373112374112375112376112377112378112379112380112381112382112383112384112385112386112387112388112389112390112391112392112393112394112395112396112397112398112399112400112401112402112403112404112405112406112407112408112409112410112411112412112413112414112415112416112417112418112419112420112421112422112423112424112425112426112427112428112429112430112431112432112433112434112435112436112437112438112439112440112441112442112443112444112445112446112447112448112449112450112451112452112453112454112455112456112457112458112459112460112461112462112463112464112465112466112467112468112469112470112471112472112473112474112475112476112477112478112479112480112481112482112483112484112485112486112487112488112489112490112491112492112493112494112495112496112497112498112499112500112501112502112503112504112505112506112507112508112509112510112511112512112513112514112515112516112517112518112519112520112521112522112523112524112525112526112527112528112529112530112531112532112533112534112535112536112537112538112539112540112541112542112543112544112545112546112547112548112549112550112551112552112553112554112555112556112557112558112559112560112561112562112563112564112565112566112567112568112569112570112571112572112573112574112575112576112577112578112579112580112581112582112583112584112585112586112587112588112589112590112591112592112593112594112595112596112597112598112599112600112601112602112603112604112605112606112607112608112609112610112611112612112613112614112615112616112617112618112619112620112621112622112623112624112625112626112627112628112629112630112631112632112633112634112635112636112637112638112639112640112641112642112643112644112645112646112647112648112649112650112651112652112653112654112655112656112657112658112659112660112661112662112663112664112665112666112667112668112669112670112671112672112673112674112675112676112677112678112679112680112681112682112683112684112685112686112687112688112689112690112691112692112693112694112695112696112697112698112699112700112701112702112703112704112705112706112707112708112709112710112711112712112713112714112715112716112717112718112719112720112721112722112723112724112725112726112727112728112729112730112731112732112733112734112735112736112737112738112739112740112741112742112743112744112745112746112747112748112749112750112751112752112753112754112755112756112757112758112759112760112761112762112763112764112765112766112767112768112769112770112771112772112773112774112775112776112777112778112779112780112781112782112783112784112785112786112787112788112789112790112791112792112793112794112795112796112797112798112799112800112801112802112803112804112805112806112807112808112809112810112811112812112813112814112815112816112817112818112819112820112821112822112823112824112825112826112827112828112829112830112831112832112833112834112835112836112837112838112839112840112841112842112843112844112845112846112847112848112849112850112851112852112853112854112855112856112857112858112859112860112861112862112863112864112865112866112867112868112869112870112871112872112873112874112875112876112877112878112879112880112881112882112883112884112885112886112887112888112889112890112891112892112893112894112895112896112897112898112899112900112901112902112903112904112905112906112907112908112909112910112911112912112913112914112915112916112917112918112919112920112921112922112923112924112925112926112927112928112929112930112931112932112933112934112935112936112937112938112939112940112941112942112943112944112945112946112947112948112949112950112951112952112953112954112955112956112957112958112959112960112961112962112963112964112965112966112967112968112969112970112971112972112973112974112975112976112977112978112979112980112981112982112983112984112985112986112987112988112989112990112991112992112993112994112995112996112997112998112999113000113001113002113003113004113005113006113007113008113009113010113011113012113013113014113015113016113017113018113019113020113021113022113023113024113025113026113027113028113029113030113031113032113033113034113035113036113037113038113039113040113041113042113043113044113045113046113047113048113049113050113051113052113053113054113055113056113057113058113059113060113061113062113063113064113065113066113067113068113069113070113071113072113073113074113075113076113077113078113079113080113081113082113083113084113085113086113087113088113089113090113091113092113093113094113095113096113097113098113099113100113101113102113103113104113105113106113107113108113109113110113111113112113113113114113115113116113117113118113119113120113121113122113123113124113125113126113127113128113129113130113131113132113133113134113135113136113137113138113139113140113141113142113143113144113145113146113147113148113149113150113151113152113153113154113155113156113157113158113159113160113161113162113163113164113165113166113167113168113169113170113171113172113173113174113175113176113177113178113179113180113181113182113183113184113185113186113187113188113189113190113191113192113193113194113195113196113197113198113199113200113201113202113203113204113205113206113207113208113209113210113211113212113213113214113215113216113217113218113219113220113221113222113223113224113225113226113227113228113229113230113231113232113233113234113235113236113237113238113239113240113241113242113243113244113245113246113247113248113249113250113251113252113253113254113255113256113257113258113259113260113261113262113263113264113265113266113267113268113269113270113271113272113273113274113275113276113277113278113279113280113281113282113283113284113285113286113287113288113289113290113291113292113293113294113295113296113297113298113299113300113301113302113303113304113305113306113307113308113309113310113311113312113313113314113315113316113317113318113319113320113321113322113323113324113325113326113327113328113329113330113331113332113333113334113335113336113337113338113339113340113341113342113343113344113345113346113347113348113349113350113351113352113353113354113355113356113357113358113359113360113361113362113363113364113365113366113367113368113369113370113371113372113373113374113375113376113377113378113379113380113381113382113383113384113385113386113387113388113389113390113391113392113393113394113395113396113397113398113399113400113401113402113403113404113405113406113407113408113409113410113411113412113413113414113415113416113417113418113419113420113421113422113423113424113425113426113427113428113429113430113431113432113433113434113435113436113437113438113439113440113441113442113443113444113445113446113447113448113449113450113451113452113453113454113455113456113457113458113459113460113461113462113463113464113465113466113467113468113469113470113471113472113473113474113475113476113477113478113479113480113481113482113483113484113485113486113487113488113489113490113491113492113493113494113495113496113497113498113499113500113501113502113503113504113505113506113507113508113509113510113511113512113513113514113515113516113517113518113519113520113521113522113523113524113525113526113527113528113529113530113531113532113533113534113535113536113537113538113539113540113541113542113543113544113545113546113547113548113549113550113551113552113553113554113555113556113557113558113559113560113561113562113563113564113565113566113567113568113569113570113571113572113573113574113575113576113577113578113579113580113581113582113583113584113585113586113587113588113589113590113591113592113593113594113595113596113597113598113599113600113601113602113603113604113605113606113607113608113609113610113611113612113613113614113615113616113617113618113619113620113621113622113623113624113625113626113627113628113629113630113631113632113633113634113635113636113637113638113639113640113641113642113643113644113645113646113647113648113649113650113651113652113653113654113655113656113657113658113659113660113661113662113663113664113665113666113667113668113669113670113671113672113673113674113675113676113677113678113679113680113681113682113683113684113685113686113687113688113689113690113691113692113693113694113695113696113697113698113699113700113701113702113703113704113705113706113707113708113709113710113711113712113713113714113715113716113717113718113719113720113721113722113723113724113725113726113727113728113729113730113731113732113733113734113735113736113737113738113739113740113741113742113743113744113745113746113747113748113749113750113751113752113753113754113755113756113757113758113759113760113761113762113763113764113765113766113767113768113769113770113771113772113773113774113775113776113777113778113779113780113781113782113783113784113785113786113787113788113789113790113791113792113793113794113795113796113797113798113799113800113801113802113803113804113805113806113807113808113809113810113811113812113813113814113815113816113817113818113819113820113821113822113823113824113825113826113827113828113829113830113831113832113833113834113835113836113837113838113839113840113841113842113843113844113845113846113847113848113849113850113851113852113853113854113855113856113857113858113859113860113861113862113863113864113865113866113867113868113869113870113871113872113873113874113875113876113877113878113879113880113881113882113883113884113885113886113887113888113889113890113891113892113893113894113895113896113897113898113899113900113901113902113903113904113905113906113907113908113909113910113911113912113913113914113915113916113917113918113919113920113921113922113923113924113925113926113927113928113929113930113931113932113933113934113935113936113937113938113939113940113941113942113943113944113945113946113947113948113949113950113951113952113953113954113955113956113957113958113959113960113961113962113963113964113965113966113967113968113969113970113971113972113973113974113975113976113977113978113979113980113981113982113983113984113985113986113987113988113989113990113991113992113993113994113995113996113997113998113999114000114001114002114003114004114005114006114007114008114009114010114011114012114013114014114015114016114017114018114019114020114021114022114023114024114025114026114027114028114029114030114031114032114033114034114035114036114037114038114039114040114041114042114043114044114045114046114047114048114049114050114051114052114053114054114055114056114057114058114059114060114061114062114063114064114065114066114067114068114069114070114071114072114073114074114075114076114077114078114079114080114081114082114083114084114085114086114087114088114089114090114091114092114093114094114095114096114097114098114099114100114101114102114103114104114105114106114107114108114109114110114111114112114113114114114115114116114117114118114119114120114121114122114123114124114125114126114127114128114129114130114131114132114133114134114135114136114137114138114139114140114141114142114143114144114145114146114147114148114149114150114151114152114153114154114155114156114157114158114159114160114161114162114163114164114165114166114167114168114169114170114171114172114173114174114175114176114177114178114179114180114181114182114183114184114185114186114187114188114189114190114191114192114193114194114195114196114197114198114199114200114201114202114203114204114205114206114207114208114209114210114211114212114213114214114215114216114217114218114219114220114221114222114223114224114225114226114227114228114229114230114231114232114233114234114235114236114237114238114239114240114241114242114243114244114245114246114247114248114249114250114251114252114253114254114255114256114257114258114259114260114261114262114263114264114265114266114267114268114269114270114271114272114273114274114275114276114277114278114279114280114281114282114283114284114285114286114287114288114289114290114291114292114293114294114295114296114297114298114299114300114301114302114303114304114305114306114307114308114309114310114311114312114313114314114315114316114317114318114319114320114321114322114323114324114325114326114327114328114329114330114331114332114333114334114335114336114337114338114339114340114341114342114343114344114345114346114347114348114349114350114351114352114353114354114355114356114357114358114359114360114361114362114363114364114365114366114367114368114369114370114371114372114373114374114375114376114377114378114379114380114381114382114383114384114385114386114387114388114389114390114391114392114393114394114395114396114397114398114399114400114401114402114403114404114405114406114407114408114409114410114411114412114413114414114415114416114417114418114419114420114421114422114423114424114425114426114427114428114429114430114431114432114433114434114435114436114437114438114439114440114441114442114443114444114445114446114447114448114449114450114451114452114453114454114455114456114457114458114459114460114461114462114463114464114465114466114467114468114469114470114471114472114473114474114475114476114477114478114479114480114481114482114483114484114485114486114487114488114489114490114491114492114493114494114495114496114497114498114499114500114501114502114503114504114505114506114507114508114509114510114511114512114513114514114515114516114517114518114519114520114521114522114523114524114525114526114527114528114529114530114531114532114533114534114535114536114537114538114539114540114541114542114543114544114545114546114547114548114549114550114551114552114553114554114555114556114557114558114559114560114561114562114563114564114565114566114567114568114569114570114571114572114573114574114575114576114577114578114579114580114581114582114583114584114585114586114587114588114589114590114591114592114593114594114595114596114597114598114599114600114601114602114603114604114605114606114607114608114609114610114611114612114613114614114615114616114617114618114619114620114621114622114623114624114625114626114627114628114629114630114631114632114633114634114635114636114637114638114639114640114641114642114643114644114645114646114647114648114649114650114651114652114653114654114655114656114657114658114659114660114661114662114663114664114665114666114667114668114669114670114671114672114673114674114675114676114677114678114679114680114681114682114683114684114685114686114687114688114689114690114691114692114693114694114695114696114697114698114699114700114701114702114703114704114705114706114707114708114709114710114711114712114713114714114715114716114717114718114719114720114721114722114723114724114725114726114727114728114729114730114731114732114733114734114735114736114737114738114739114740114741114742114743114744114745114746114747114748114749114750114751114752114753114754114755114756114757114758114759114760114761114762114763114764114765114766114767114768114769114770114771114772114773114774114775114776114777114778114779114780114781114782114783114784114785114786114787114788114789114790114791114792114793114794114795114796114797114798114799114800114801114802114803114804114805114806114807114808114809114810114811114812114813114814114815114816114817114818114819114820114821114822114823114824114825114826114827114828114829114830114831114832114833114834114835114836114837114838114839114840114841114842114843114844114845114846114847114848114849114850114851114852114853114854114855114856114857114858114859114860114861114862114863114864114865114866114867114868114869114870114871114872114873114874114875114876114877114878114879114880114881114882114883114884114885114886114887114888114889114890114891114892114893114894114895114896114897114898114899114900114901114902114903114904114905114906114907114908114909114910114911114912114913114914114915114916114917114918114919114920114921114922114923114924114925114926114927114928114929114930114931114932114933114934114935114936114937114938114939114940114941114942114943114944114945114946114947114948114949114950114951114952114953114954114955114956114957114958114959114960114961114962114963114964114965114966114967114968114969114970114971114972114973114974114975114976114977114978114979114980114981114982114983114984114985114986114987114988114989114990114991114992114993114994114995114996114997114998114999115000115001115002115003115004115005115006115007115008115009115010115011115012115013115014115015115016115017115018115019115020115021115022115023115024115025115026115027115028115029115030115031115032115033115034115035115036115037115038115039115040115041115042115043115044115045115046115047115048115049115050115051115052115053115054115055115056115057115058115059115060115061115062115063115064115065115066115067115068115069115070115071115072115073115074115075115076115077115078115079115080115081115082115083115084115085115086115087115088115089115090115091115092115093115094115095115096115097115098115099115100115101115102115103115104115105115106115107115108115109115110115111115112115113115114115115115116115117115118115119115120115121115122115123115124115125115126115127115128115129115130115131115132115133115134115135115136115137115138115139115140115141115142115143115144115145115146115147115148115149115150115151115152115153115154115155115156115157115158115159115160115161115162115163115164115165115166115167115168115169115170115171115172115173115174115175115176115177115178115179115180115181115182115183115184115185115186115187115188115189115190115191115192115193115194115195115196115197115198115199115200115201115202115203115204115205115206115207115208115209115210115211115212115213115214115215115216115217115218115219115220115221115222115223115224115225115226115227115228115229115230115231115232115233115234115235115236115237115238115239115240115241115242115243115244115245115246115247115248115249115250115251115252115253115254115255115256115257115258115259115260115261115262115263115264115265115266115267115268115269115270115271115272115273115274115275115276115277115278115279115280115281115282115283115284115285115286115287115288115289115290115291115292115293115294115295115296115297115298115299115300115301115302115303115304115305115306115307115308115309115310115311115312115313115314115315115316115317115318115319115320115321115322115323115324115325115326115327115328115329115330115331115332115333115334115335115336115337115338115339115340115341115342115343115344115345115346115347115348115349115350115351115352115353115354115355115356115357115358115359115360115361115362115363115364115365115366115367115368115369115370115371115372115373115374115375115376115377115378115379115380115381115382115383115384115385115386115387115388115389115390115391115392115393115394115395115396115397115398115399115400115401115402115403115404115405115406115407115408115409115410115411115412115413115414115415115416115417115418115419115420115421115422115423115424115425115426115427115428115429115430115431115432115433115434115435115436115437115438115439115440115441115442115443115444115445115446115447115448115449115450115451115452115453115454115455115456115457115458115459115460115461115462115463115464115465115466115467115468115469115470115471115472115473115474115475115476115477115478115479115480115481115482115483115484115485115486115487115488115489115490115491115492115493115494115495115496115497115498115499115500115501115502115503115504115505115506115507115508115509115510115511115512115513115514115515115516115517115518115519115520115521115522115523115524115525115526115527115528115529115530115531115532115533115534115535115536115537115538115539115540115541115542115543115544115545115546115547115548115549115550115551115552115553115554115555115556115557115558115559115560115561115562115563115564115565115566115567115568115569115570115571115572115573115574115575115576115577115578115579115580115581115582115583115584115585115586115587115588115589115590115591115592115593115594115595115596115597115598115599115600115601115602115603115604115605115606115607115608115609115610115611115612115613115614115615115616115617115618115619115620115621115622115623115624115625115626115627115628115629115630115631115632115633115634115635115636115637115638115639115640115641115642115643115644115645115646115647115648115649115650115651115652115653115654115655115656115657115658115659115660115661115662115663115664115665115666115667115668115669115670115671115672115673115674115675115676115677115678115679115680115681115682115683115684115685115686115687115688115689115690115691115692115693115694115695115696115697115698115699115700115701115702115703115704115705115706115707115708115709115710115711115712115713115714115715115716115717115718115719115720115721115722115723115724115725115726115727115728115729115730115731115732115733115734115735115736115737115738115739115740115741115742115743115744115745115746115747115748115749115750115751115752115753115754115755115756115757115758115759115760115761115762115763115764115765115766115767115768115769115770115771115772115773115774115775115776115777115778115779115780115781115782115783115784115785115786115787115788115789115790115791115792115793115794115795115796115797115798115799115800115801115802115803115804115805115806115807115808115809115810115811115812115813115814115815115816115817115818115819115820115821115822115823115824115825115826115827115828115829115830115831115832115833115834115835115836115837115838115839115840115841115842115843115844115845115846115847115848115849115850115851115852115853115854115855115856115857115858115859115860115861115862115863115864115865115866115867115868115869115870115871115872115873115874115875115876115877115878115879115880115881115882115883115884115885115886115887115888115889115890115891115892115893115894115895115896115897115898115899115900115901115902115903115904115905115906115907115908115909115910115911115912115913115914115915115916115917115918115919115920115921115922115923115924115925115926115927115928115929115930115931115932115933115934115935115936115937115938115939115940115941115942115943115944115945115946115947115948115949115950115951115952115953115954115955115956115957115958115959115960115961115962115963115964115965115966115967115968115969115970115971115972115973115974115975115976115977115978115979115980115981115982115983115984115985115986115987115988115989115990115991115992115993115994115995115996115997115998115999116000116001116002116003116004116005116006116007116008116009116010116011116012116013116014116015116016116017116018116019116020116021116022116023116024116025116026116027116028116029116030116031116032116033116034116035116036116037116038116039116040116041116042116043116044116045116046116047116048116049116050116051116052116053116054116055116056116057116058116059116060116061116062116063116064116065116066116067116068116069116070116071116072116073116074116075116076116077116078116079116080116081116082116083116084116085116086116087116088116089116090116091116092116093116094116095116096116097116098116099116100116101116102116103116104116105116106116107116108116109116110116111116112116113116114116115116116116117116118116119116120116121116122116123116124116125116126116127116128116129116130116131116132116133116134116135116136116137116138116139116140116141116142116143116144116145116146116147116148116149116150116151116152116153116154116155116156116157116158116159116160116161116162116163116164116165116166116167116168116169116170116171116172116173116174116175116176116177116178116179116180116181116182116183116184116185116186116187116188116189116190116191116192116193116194116195116196116197116198116199116200116201116202116203116204116205116206116207116208116209116210116211116212116213116214116215116216116217116218116219116220116221116222116223116224116225116226116227116228116229116230116231116232116233116234116235116236116237116238116239116240116241116242116243116244116245116246116247116248116249116250116251116252116253116254116255116256116257116258116259116260116261116262116263116264116265116266116267116268116269116270116271116272116273116274116275116276116277116278116279116280116281116282116283116284116285116286116287116288116289116290116291116292116293116294116295116296116297116298116299116300116301116302116303116304116305116306116307116308116309116310116311116312116313116314116315116316116317116318116319116320116321116322116323116324116325116326116327116328116329116330116331116332116333116334116335116336116337116338116339116340116341116342116343116344116345116346116347116348116349116350116351116352116353116354116355116356116357116358116359116360116361116362116363116364116365116366116367116368116369116370116371116372116373116374116375116376116377116378116379116380116381116382116383116384116385116386116387116388116389116390116391116392116393116394116395116396116397116398116399116400116401116402116403116404116405116406116407116408116409116410116411116412116413116414116415116416116417116418116419116420116421116422116423116424116425116426116427116428116429116430116431116432116433116434116435116436116437116438116439116440116441116442116443116444116445116446116447116448116449116450116451116452116453116454116455116456116457116458116459116460116461116462116463116464116465116466116467116468116469116470116471116472116473116474116475116476116477116478116479116480116481116482116483116484116485116486116487116488116489116490116491116492116493116494116495116496116497116498116499116500116501116502116503116504116505116506116507116508116509116510116511116512116513116514116515116516116517116518116519116520116521116522116523116524116525116526116527116528116529116530116531116532116533116534116535116536116537116538116539116540116541116542116543116544116545116546116547116548116549116550116551116552116553116554116555116556116557116558116559116560116561116562116563116564116565116566116567116568116569116570116571116572116573116574116575116576116577116578116579116580116581116582116583116584116585116586116587116588116589116590116591116592116593116594116595116596116597116598116599116600116601116602116603116604116605116606116607116608116609116610116611116612116613116614116615116616116617116618116619116620116621116622116623116624116625116626116627116628116629116630116631116632116633116634116635116636116637116638116639116640116641116642116643116644116645116646116647116648116649116650116651116652116653116654116655116656116657116658116659116660116661116662116663116664116665116666116667116668116669116670116671116672116673116674116675116676116677116678116679116680116681116682116683116684116685116686116687116688116689116690116691116692116693116694116695116696116697116698116699116700116701116702116703116704116705116706116707116708116709116710116711116712116713116714116715116716116717116718116719116720116721116722116723116724116725116726116727116728116729116730116731116732116733116734116735116736116737116738116739116740116741116742116743116744116745116746116747116748116749116750116751116752116753116754116755116756116757116758116759116760116761116762116763116764116765116766116767116768116769116770116771116772116773116774116775116776116777116778116779116780116781116782116783116784116785116786116787116788116789116790116791116792116793116794116795116796116797116798116799116800116801116802116803116804116805116806116807116808116809116810116811116812116813116814116815116816116817116818116819116820116821116822116823116824116825116826116827116828116829116830116831116832116833116834116835116836116837116838116839116840116841116842116843116844116845116846116847116848116849116850116851116852116853116854116855116856116857116858116859116860116861116862116863116864116865116866116867116868116869116870116871116872116873116874116875116876116877116878116879116880116881116882116883116884116885116886116887116888116889116890116891116892116893116894116895116896116897116898116899116900116901116902116903116904116905116906116907116908116909116910116911116912116913116914116915116916116917116918116919116920116921116922116923116924116925116926116927116928116929116930116931116932116933116934116935116936116937116938116939116940116941116942116943116944116945116946116947116948116949116950116951116952116953116954116955116956116957116958116959116960116961116962116963116964116965116966116967116968116969116970116971116972116973116974116975116976116977116978116979116980116981116982116983116984116985116986116987116988116989116990116991116992116993116994116995116996116997116998116999117000117001117002117003117004117005117006117007117008117009117010117011117012117013117014117015117016117017117018117019117020117021117022117023117024117025117026117027117028117029117030117031117032117033117034117035117036117037117038117039117040117041117042117043117044117045117046117047117048117049117050117051117052117053117054117055117056117057117058117059117060117061117062117063117064117065117066117067117068117069117070117071117072117073117074117075117076117077117078117079117080117081117082117083117084117085117086117087117088117089117090117091117092117093117094117095117096117097117098117099117100117101117102117103117104117105117106117107117108117109117110117111117112117113117114117115117116117117117118117119117120117121117122117123117124117125117126117127117128117129117130117131117132117133117134117135117136117137117138117139117140117141117142117143117144117145117146117147117148117149117150117151117152117153117154117155117156117157117158117159117160117161117162117163117164117165117166117167117168117169117170117171117172117173117174117175117176117177117178117179117180117181117182117183117184117185117186117187117188117189117190117191117192117193117194117195117196117197117198117199117200117201117202117203117204117205117206117207117208117209117210117211117212117213117214117215117216117217117218117219117220117221117222117223117224117225117226117227117228117229117230117231117232117233117234117235117236117237117238117239117240117241117242117243117244117245117246117247117248117249117250117251117252117253117254117255117256117257117258117259117260117261117262117263117264117265117266117267117268117269117270117271117272117273117274117275117276117277117278117279117280117281117282117283117284117285117286117287117288117289117290117291117292117293117294117295117296117297117298117299117300117301117302117303117304117305117306117307117308117309117310117311117312117313117314117315117316117317117318117319117320117321117322117323117324117325117326117327117328117329117330117331117332117333117334117335117336117337117338117339117340117341117342117343117344117345117346117347117348117349117350117351117352117353117354117355117356117357117358117359117360117361117362117363117364117365117366117367117368117369117370117371117372117373117374117375117376117377117378117379117380117381117382117383117384117385117386117387117388117389117390117391117392117393117394117395117396117397117398117399117400117401117402117403117404117405117406117407117408117409117410117411117412117413117414117415117416117417117418117419117420117421117422117423117424117425117426117427117428117429117430117431117432117433117434117435117436117437117438117439117440117441117442117443117444117445117446117447117448117449117450117451117452117453117454117455117456117457117458117459117460117461117462117463117464117465117466117467117468117469117470117471117472117473117474117475117476117477117478117479117480117481117482117483117484117485117486117487117488117489117490117491117492117493117494117495117496117497117498117499117500117501117502117503117504117505117506117507117508117509117510117511117512117513117514117515117516117517117518117519117520117521117522117523117524117525117526117527117528117529117530117531117532117533117534117535117536117537117538117539117540117541117542117543117544117545117546117547117548117549117550117551117552117553117554117555117556117557117558117559117560117561117562117563117564117565117566117567117568117569117570117571117572117573117574117575117576117577117578117579117580117581117582117583117584117585117586117587117588117589117590117591117592117593117594117595117596117597117598117599117600117601117602117603117604117605117606117607117608117609117610117611117612117613117614117615117616117617117618117619117620117621117622117623117624117625117626117627117628117629117630117631117632117633117634117635117636117637117638117639117640117641117642117643117644117645117646117647117648117649117650117651117652117653117654117655117656117657117658117659117660117661117662117663117664117665117666117667117668117669117670117671117672117673117674117675117676117677117678117679117680117681117682117683117684117685117686117687117688117689117690117691117692117693117694117695117696117697117698117699117700117701117702117703117704117705117706117707117708117709117710117711117712117713117714117715117716117717117718117719117720117721117722117723117724117725117726117727117728117729117730117731117732117733117734117735117736117737117738117739117740117741117742117743117744117745117746117747117748117749117750117751117752117753117754117755117756117757117758117759117760117761117762117763117764117765117766117767117768117769117770117771117772117773117774117775117776117777117778117779117780117781117782117783117784117785117786117787117788117789117790117791117792117793117794117795117796117797117798117799117800117801117802117803117804117805117806117807117808117809117810117811117812117813117814117815117816117817117818117819117820117821117822117823117824117825117826117827117828117829117830117831117832117833117834117835117836117837117838117839117840117841117842117843117844117845117846117847117848117849117850117851117852117853117854117855117856117857117858117859117860117861117862117863117864117865117866117867117868117869117870117871117872117873117874117875117876117877117878117879117880117881117882117883117884117885117886117887117888117889117890117891117892117893117894117895117896117897117898117899117900117901117902117903117904117905117906117907117908117909117910117911117912117913117914117915117916117917117918117919117920117921117922117923117924117925117926117927117928117929117930117931117932117933117934117935117936117937117938117939117940117941117942117943117944117945117946117947117948117949117950117951117952117953117954117955117956117957117958117959117960117961117962117963117964117965117966117967117968117969117970117971117972117973117974117975117976117977117978117979117980117981117982117983117984117985117986117987117988117989117990117991117992117993117994117995117996117997117998117999118000118001118002118003118004118005118006118007118008118009118010118011118012118013118014118015118016118017118018118019118020118021118022118023118024118025118026118027118028118029118030118031118032118033118034118035118036118037118038118039118040118041118042118043118044118045118046118047118048118049118050118051118052118053118054118055118056118057118058118059118060118061118062118063118064118065118066118067118068118069118070118071118072118073118074118075118076118077118078118079118080118081118082118083118084118085118086118087118088118089118090118091118092118093118094118095118096118097118098118099118100118101118102118103118104118105118106118107118108118109118110118111118112118113118114118115118116118117118118118119118120118121118122118123118124118125118126118127118128118129118130118131118132118133118134118135118136118137118138118139118140118141118142118143118144118145118146118147118148118149118150118151118152118153118154118155118156118157118158118159118160118161118162118163118164118165118166118167118168118169118170118171118172118173118174118175118176118177118178118179118180118181118182118183118184118185118186118187118188118189118190118191118192118193118194118195118196118197118198118199118200118201118202118203118204118205118206118207118208118209118210118211118212118213118214118215118216118217118218118219118220118221118222118223118224118225118226118227118228118229118230118231118232118233118234118235118236118237118238118239118240118241118242118243118244118245118246118247118248118249118250118251118252118253118254118255118256118257118258118259118260118261118262118263118264118265118266118267118268118269118270118271118272118273118274118275118276118277118278118279118280118281118282118283118284118285118286118287118288118289118290118291118292118293118294118295118296118297118298118299118300118301118302118303118304118305118306118307118308118309118310118311118312118313118314118315118316118317118318118319118320118321118322118323118324118325118326118327118328118329118330118331118332118333118334118335118336118337118338118339118340118341118342118343118344118345118346118347118348118349118350118351118352118353118354118355118356118357118358118359118360118361118362118363118364118365118366118367118368118369118370118371118372118373118374118375118376118377118378118379118380118381118382118383118384118385118386118387118388118389118390118391118392118393118394118395118396118397118398118399118400118401118402118403118404118405118406118407118408118409118410118411118412118413118414118415118416118417118418118419118420118421118422118423118424118425118426118427118428118429118430118431118432118433118434118435118436118437118438118439118440118441118442118443118444118445118446118447118448118449118450118451118452118453118454118455118456118457118458118459118460118461118462118463118464118465118466118467118468118469118470118471118472118473118474118475118476118477118478118479118480118481118482118483118484118485118486118487118488118489118490118491118492118493118494118495118496118497118498118499118500118501118502118503118504118505118506118507118508118509118510118511118512118513118514118515118516118517118518118519118520118521118522118523118524118525118526118527118528118529118530118531118532118533118534118535118536118537118538118539118540118541118542118543118544118545118546118547118548118549118550118551118552118553118554118555118556118557118558118559118560118561118562118563118564118565118566118567118568118569118570118571118572118573118574118575118576118577118578118579118580118581118582118583118584118585118586118587118588118589118590118591118592118593118594118595118596118597118598118599118600118601118602118603118604118605118606118607118608118609118610118611118612118613118614118615118616118617118618118619118620118621118622118623118624118625118626118627118628118629118630118631118632118633118634118635118636118637118638118639118640118641118642118643118644118645118646118647118648118649118650118651118652118653118654118655118656118657118658118659118660118661118662118663118664118665118666118667118668118669118670118671118672118673118674118675118676118677118678118679118680118681118682118683118684118685118686118687118688118689118690118691118692118693118694118695118696118697118698118699118700118701118702118703118704118705118706118707118708118709118710118711118712118713118714118715118716118717118718118719118720118721118722118723118724118725118726118727118728118729118730118731118732118733118734118735118736118737118738118739118740118741118742118743118744118745118746118747118748118749118750118751118752118753118754118755118756118757118758118759118760118761118762118763118764118765118766118767118768118769118770118771118772118773118774118775118776118777118778118779118780118781118782118783118784118785118786118787118788118789118790118791118792118793118794118795118796118797118798118799118800118801118802118803118804118805118806118807118808118809118810118811118812118813118814118815118816118817118818118819118820118821118822118823118824118825118826118827118828118829118830118831118832118833118834118835118836118837118838118839118840118841118842118843118844118845118846118847118848118849118850118851118852118853118854118855118856118857118858118859118860118861118862118863118864118865118866118867118868118869118870118871118872118873118874118875118876118877118878118879118880118881118882118883118884118885118886118887118888118889118890118891118892118893118894118895118896118897118898118899118900118901118902118903118904118905118906118907118908118909118910118911118912118913118914118915118916118917118918118919118920118921118922118923118924118925118926118927118928118929118930118931118932118933118934118935118936118937118938118939118940118941118942118943118944118945118946118947118948118949118950118951118952118953118954118955118956118957118958118959118960118961118962118963118964118965118966118967118968118969118970118971118972118973118974118975118976118977118978118979118980118981118982118983118984118985118986118987118988118989118990118991118992118993118994118995118996118997118998118999119000119001119002119003119004119005119006119007119008119009119010119011119012119013119014119015119016119017119018119019119020119021119022119023119024119025119026119027119028119029119030119031119032119033119034119035119036119037119038119039119040119041119042119043119044119045119046119047119048119049119050119051119052119053119054119055119056119057119058119059119060119061119062119063119064119065119066119067119068119069119070119071119072119073119074119075119076119077119078119079119080119081119082119083119084119085119086119087119088119089119090119091119092119093119094119095119096119097119098119099119100119101119102119103119104119105119106119107119108119109119110119111119112119113119114119115119116119117119118119119119120119121119122119123119124119125119126119127119128119129119130119131119132119133119134119135119136119137119138119139119140119141119142119143119144119145119146119147119148119149119150119151119152119153119154119155119156119157119158119159119160119161119162119163119164119165119166119167119168119169119170119171119172119173119174119175119176119177119178119179119180119181119182119183119184119185119186119187119188119189119190119191119192119193119194119195119196119197119198119199119200119201119202119203119204119205119206119207119208119209119210119211119212119213119214119215119216119217119218119219119220119221119222119223119224119225119226119227119228119229119230119231119232119233119234119235119236119237119238119239119240119241119242119243119244119245119246119247119248119249119250119251119252119253119254119255119256119257119258119259119260119261119262119263119264119265119266119267119268119269119270119271119272119273119274119275119276119277119278119279119280119281119282119283119284119285119286119287119288119289119290119291119292119293119294119295119296119297119298119299119300119301119302119303119304119305119306119307119308119309119310119311119312119313119314119315119316119317119318119319119320119321119322119323119324119325119326119327119328119329119330119331119332119333119334119335119336119337119338119339119340119341119342119343119344119345119346119347119348119349119350119351119352119353119354119355119356119357119358119359119360119361119362119363119364119365119366119367119368119369119370119371119372119373119374119375119376119377119378119379119380119381119382119383119384119385119386119387119388119389119390119391119392119393119394119395119396119397119398119399119400119401119402119403119404119405119406119407119408119409119410119411119412119413119414119415119416119417119418119419119420119421119422119423119424119425119426119427119428119429119430119431119432119433119434119435119436119437119438119439119440119441119442119443119444119445119446119447119448119449119450119451119452119453119454119455119456119457119458119459119460119461119462119463119464119465119466119467119468119469119470119471119472119473119474119475119476119477119478119479119480119481119482119483119484119485119486119487119488119489119490119491119492119493119494119495119496119497119498119499119500119501119502119503119504119505119506119507119508119509119510119511119512119513119514119515119516119517119518119519119520119521119522119523119524119525119526119527119528119529119530119531119532119533119534119535119536119537119538119539119540119541119542119543119544119545119546119547119548119549119550119551119552119553119554119555119556119557119558119559119560119561119562119563119564119565119566119567119568119569119570119571119572119573119574119575119576119577119578119579119580119581119582119583119584119585119586119587119588119589119590119591119592119593119594119595119596119597119598119599119600119601119602119603119604119605119606119607119608119609119610119611119612119613119614119615119616119617119618119619119620119621119622119623119624119625119626119627119628119629119630119631119632119633119634119635119636119637119638119639119640119641119642119643119644119645119646119647119648119649119650119651119652119653119654119655119656119657119658119659119660119661119662119663119664119665119666119667119668119669119670119671119672119673119674119675119676119677119678119679119680119681119682119683119684119685119686119687119688119689119690119691119692119693119694119695119696119697119698119699119700119701119702119703119704119705119706119707119708119709119710119711119712119713119714119715119716119717119718119719119720119721119722119723119724119725119726119727119728119729119730119731119732119733119734119735119736119737119738119739119740119741119742119743119744119745119746119747119748119749119750119751119752119753119754119755119756119757119758119759119760119761119762119763119764119765119766119767119768119769119770119771119772119773119774119775119776119777119778119779119780119781119782119783119784119785119786119787119788119789119790119791119792119793119794119795119796119797119798119799119800119801119802119803119804119805119806119807119808119809119810119811119812119813119814119815119816119817119818119819119820119821119822119823119824119825119826119827119828119829119830119831119832119833119834119835119836119837119838119839119840119841119842119843119844119845119846119847119848119849119850119851119852119853119854119855119856119857119858119859119860119861119862119863119864119865119866119867119868119869119870119871119872119873119874119875119876119877119878119879119880119881119882119883119884119885119886119887119888119889119890119891119892119893119894119895119896119897119898119899119900119901119902119903119904119905119906119907119908119909119910119911119912119913119914119915119916119917119918119919119920119921119922119923119924119925119926119927119928119929119930119931119932119933119934119935119936119937119938119939119940119941119942119943119944119945119946119947119948119949119950119951119952119953119954119955119956119957119958119959119960119961119962119963119964119965119966119967119968119969119970119971119972119973119974119975119976119977119978119979119980119981119982119983119984119985119986119987119988119989119990119991119992119993119994119995119996119997119998119999120000120001120002120003120004120005120006120007120008120009120010120011120012120013120014120015120016120017120018120019120020120021120022120023120024120025120026120027120028120029120030120031120032120033120034120035120036120037120038120039120040120041120042120043120044120045120046120047120048120049120050120051120052120053120054120055120056120057120058120059120060120061120062120063120064120065120066120067120068120069120070120071120072120073120074120075120076120077120078120079120080120081120082120083120084120085120086120087120088120089120090120091120092120093120094120095120096120097120098120099120100120101120102120103120104120105120106120107120108120109120110120111120112120113120114120115120116120117120118120119120120120121120122120123120124120125120126120127120128120129120130120131120132120133120134120135120136120137120138120139120140120141120142120143120144120145120146120147120148120149120150120151120152120153120154120155120156120157120158120159120160120161120162120163120164120165120166120167120168120169120170120171120172120173120174120175120176120177120178120179120180120181120182120183120184120185120186120187120188120189120190120191120192120193120194120195120196120197120198120199120200120201120202120203120204120205120206120207120208120209120210120211120212120213120214120215120216120217120218120219120220120221120222120223120224120225120226120227120228120229120230120231120232120233120234120235120236120237120238120239120240120241120242120243120244120245120246120247120248120249120250120251120252120253120254120255120256120257120258120259120260120261120262120263120264120265120266120267120268120269120270120271120272120273120274120275120276120277120278120279120280120281120282120283120284120285120286120287120288120289120290120291120292120293120294120295120296120297120298120299120300120301120302120303120304120305120306120307120308120309120310120311120312120313120314120315120316120317120318120319120320120321120322120323120324120325120326120327120328120329120330120331120332120333120334120335120336120337120338120339120340120341120342120343120344120345120346120347120348120349120350120351120352120353120354120355120356120357120358120359120360120361120362120363120364120365120366120367120368120369120370120371120372120373120374120375120376120377120378120379120380120381120382120383120384120385120386120387120388120389120390120391120392120393120394120395120396120397120398120399120400120401120402120403120404120405120406120407120408120409120410120411120412120413120414120415120416120417120418120419120420120421120422120423120424120425120426120427120428120429120430120431120432120433120434120435120436120437120438120439120440120441120442120443120444120445120446120447120448120449120450120451120452120453120454120455120456120457120458120459120460120461120462120463120464120465120466120467120468120469120470120471120472120473120474120475120476120477120478120479120480120481120482120483120484120485120486120487120488120489120490120491120492120493120494120495120496120497120498120499120500120501120502120503120504120505120506120507120508120509120510120511120512120513120514120515120516120517120518120519120520120521120522120523120524120525120526120527120528120529120530120531120532120533120534120535120536120537120538120539120540120541120542120543120544120545120546120547120548120549120550120551120552120553120554120555120556120557120558120559120560120561120562120563120564120565120566120567120568120569120570120571120572120573120574120575120576120577120578120579120580120581120582120583120584120585120586120587120588120589120590120591120592120593120594120595120596120597120598120599120600120601120602120603120604120605120606120607120608120609120610120611120612120613120614120615120616120617120618120619120620120621120622120623120624120625120626120627120628120629120630120631120632120633120634120635120636120637120638120639120640120641120642120643120644120645120646120647120648120649120650120651120652120653120654120655120656120657120658120659120660120661120662120663120664120665120666120667120668120669120670120671120672120673120674120675120676120677120678120679120680120681120682120683120684120685120686120687120688120689120690120691120692120693120694120695120696120697120698120699120700120701120702120703120704120705120706120707120708120709120710120711120712120713120714120715120716120717120718120719120720120721120722120723120724120725120726120727120728120729120730120731120732120733120734120735120736120737120738120739120740120741120742120743120744120745120746120747120748120749120750120751120752120753120754120755120756120757120758120759120760120761120762120763120764120765120766120767120768120769120770120771120772120773120774120775120776120777120778120779120780120781120782120783120784120785120786120787120788120789120790120791120792120793120794120795120796120797120798120799120800120801120802120803120804120805120806120807120808120809120810120811120812120813120814120815120816120817120818120819120820120821120822120823120824120825120826120827120828120829120830120831120832120833120834120835120836120837120838120839120840120841120842120843120844120845120846120847120848120849120850120851120852120853120854120855120856120857120858120859120860120861120862120863120864120865120866120867120868120869120870120871120872120873120874120875120876120877120878120879120880120881120882120883120884120885120886120887120888120889120890120891120892120893120894120895120896120897120898120899120900120901120902120903120904120905120906120907120908120909120910120911120912120913120914120915120916120917120918120919120920120921120922120923120924120925120926120927120928120929120930120931120932120933120934120935120936120937120938120939120940120941120942120943120944120945120946120947120948120949120950120951120952120953120954120955120956120957120958120959120960120961120962120963120964120965120966120967120968120969120970120971120972120973120974120975120976120977120978120979120980120981120982120983120984120985120986120987120988120989120990120991120992120993120994120995120996120997120998120999121000121001121002121003121004121005121006121007121008121009121010121011121012121013121014121015121016121017121018121019121020121021121022121023121024121025121026121027121028121029121030121031121032121033121034121035121036121037121038121039121040121041121042121043121044121045121046121047121048121049121050121051121052121053121054121055121056121057121058121059121060121061121062121063121064121065121066121067121068121069121070121071121072121073121074121075121076121077121078121079121080121081121082121083121084121085121086121087121088121089121090121091121092121093121094121095121096121097121098121099121100121101121102121103121104121105121106121107121108121109121110121111121112121113121114121115121116121117121118121119121120121121121122121123121124121125121126121127121128121129121130121131121132121133121134121135121136121137121138121139121140121141121142121143121144121145121146121147121148121149121150121151121152121153121154121155121156121157121158121159121160121161121162121163121164121165121166121167121168121169121170121171121172121173121174121175121176121177121178121179121180121181121182121183121184121185121186121187121188121189121190121191121192121193121194121195121196121197121198121199121200121201121202121203121204121205121206121207121208121209121210121211121212121213121214121215121216121217121218121219121220121221121222121223121224121225121226121227121228121229121230121231121232121233121234121235121236121237121238121239121240121241121242121243121244121245121246121247121248121249121250121251121252121253121254121255121256121257121258121259121260121261121262121263121264121265121266121267121268121269121270121271121272121273121274121275121276121277121278121279121280121281121282121283121284121285121286121287121288121289121290121291121292121293121294121295121296121297121298121299121300121301121302121303121304121305121306121307121308121309121310121311121312121313121314121315121316121317121318121319121320121321121322121323121324121325121326121327121328121329121330121331121332121333121334121335121336121337121338121339121340121341121342121343121344121345121346121347121348121349121350121351121352121353121354121355121356121357121358121359121360121361121362121363121364121365121366121367121368121369121370121371121372121373121374121375121376121377121378121379121380121381121382121383121384121385121386121387121388121389121390121391121392121393121394121395121396121397121398121399121400121401121402121403121404121405121406121407121408121409121410121411121412121413121414121415121416121417121418121419121420121421121422121423121424121425121426121427121428121429121430121431121432121433121434121435121436121437121438121439121440121441121442121443121444121445121446121447121448121449121450121451121452121453121454121455121456121457121458121459121460121461121462121463121464121465121466121467121468121469121470121471121472121473121474121475121476121477121478121479121480121481121482121483121484121485121486121487121488121489121490121491121492121493121494121495121496121497121498121499121500121501121502121503121504121505121506121507121508121509121510121511121512121513121514121515121516121517121518121519121520121521121522121523121524121525121526121527121528121529121530121531121532121533121534121535121536121537121538121539121540121541121542121543121544121545121546121547121548121549121550121551121552121553121554121555121556121557121558121559121560121561121562121563121564121565121566121567121568121569121570121571121572121573121574121575121576121577121578121579121580121581121582121583121584121585121586121587121588121589121590121591121592121593121594121595121596121597121598121599121600121601121602121603121604121605121606121607121608121609121610121611121612121613121614121615121616121617121618121619121620121621121622121623121624121625121626121627121628121629121630121631121632121633121634121635121636121637121638121639121640121641121642121643121644121645121646121647121648121649121650121651121652121653121654121655121656121657121658121659121660121661121662121663121664121665121666121667121668121669121670121671121672121673121674121675121676121677121678121679121680121681121682121683121684121685121686121687121688121689121690121691121692121693121694121695121696121697121698121699121700121701121702121703121704121705121706121707121708121709121710121711121712121713121714121715121716121717121718121719121720121721121722121723121724121725121726121727121728121729121730121731121732121733121734121735121736121737121738121739121740121741121742121743121744121745121746121747121748121749121750121751121752121753121754121755121756121757121758121759121760121761121762121763121764121765121766121767121768121769121770121771121772121773121774121775121776121777121778121779121780121781121782121783121784121785121786121787121788121789121790121791121792121793121794121795121796121797121798121799121800121801121802121803121804121805121806121807121808121809121810121811121812121813121814121815121816121817121818121819121820121821121822121823121824121825121826121827121828121829121830121831121832121833121834121835121836121837121838121839121840121841121842121843121844121845121846121847121848121849121850121851121852121853121854121855121856121857121858121859121860121861121862121863121864121865121866121867121868121869121870121871121872121873121874121875121876121877121878121879121880121881121882121883121884121885121886121887121888121889121890121891121892121893121894121895121896121897121898121899121900121901121902121903121904121905121906121907121908121909121910121911121912121913121914121915121916121917121918121919121920121921121922121923121924121925121926121927121928121929121930121931121932121933121934121935121936121937121938121939121940121941121942121943121944121945121946121947121948121949121950121951121952121953121954121955121956121957121958121959121960121961121962121963121964121965121966121967121968121969121970121971121972121973121974121975121976121977121978121979121980121981121982121983121984121985121986121987121988121989121990121991121992121993121994121995121996121997121998121999122000122001122002122003122004122005122006122007122008122009122010122011122012122013122014122015122016122017122018122019122020122021122022122023122024122025122026122027122028122029122030122031122032122033122034122035122036122037122038122039122040122041122042122043122044122045122046122047122048122049122050122051122052122053122054122055122056122057122058122059122060122061122062122063122064122065122066122067122068122069122070122071122072122073122074122075122076122077122078122079122080122081122082122083122084122085122086122087122088122089122090122091122092122093122094122095122096122097122098122099122100122101122102122103122104122105122106122107122108122109122110122111122112122113122114122115122116122117122118122119122120122121122122122123122124122125122126122127122128122129122130122131122132122133122134122135122136122137122138122139122140122141122142122143122144122145122146122147122148122149122150122151122152122153122154122155122156122157122158122159122160122161122162122163122164122165122166122167122168122169122170122171122172122173122174122175122176122177122178122179122180122181122182122183122184122185122186122187122188122189122190122191122192122193122194122195122196122197122198122199122200122201122202122203122204122205122206122207122208122209122210122211122212122213122214122215122216122217122218122219122220122221122222122223122224122225122226122227122228122229122230122231122232122233122234122235122236122237122238122239122240122241122242122243122244122245122246122247122248122249122250122251122252122253122254122255122256122257122258122259122260122261122262122263122264122265122266122267122268122269122270122271122272122273122274122275122276122277122278
  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. * It is recommended to use executeWhenCompile() or to make sure that scene.isReady() is called to get this observable raised.
  153. */
  154. this.onCompileObservable = new BABYLON.Observable();
  155. /**
  156. * Observable that will be called if an error occurs during shader compilation.
  157. */
  158. this.onErrorObservable = new BABYLON.Observable();
  159. /** @hidden */
  160. this._bonesComputationForcedToCPU = false;
  161. this._uniformBuffersNames = {};
  162. this._isReady = false;
  163. this._compilationError = "";
  164. this.name = baseName;
  165. if (attributesNamesOrOptions.attributes) {
  166. var options = attributesNamesOrOptions;
  167. this._engine = uniformsNamesOrEngine;
  168. this._attributesNames = options.attributes;
  169. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  170. this._samplers = options.samplers.slice();
  171. this.defines = options.defines;
  172. this.onError = options.onError;
  173. this.onCompiled = options.onCompiled;
  174. this._fallbacks = options.fallbacks;
  175. this._indexParameters = options.indexParameters;
  176. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  177. if (options.uniformBuffersNames) {
  178. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  179. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  180. }
  181. }
  182. }
  183. else {
  184. this._engine = engine;
  185. this.defines = defines;
  186. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  187. this._samplers = samplers ? samplers.slice() : [];
  188. this._attributesNames = attributesNamesOrOptions;
  189. this.onError = onError;
  190. this.onCompiled = onCompiled;
  191. this._indexParameters = indexParameters;
  192. this._fallbacks = fallbacks;
  193. }
  194. this.uniqueId = Effect._uniqueIdSeed++;
  195. var vertexSource;
  196. var fragmentSource;
  197. if (baseName.vertexElement) {
  198. vertexSource = document.getElementById(baseName.vertexElement);
  199. if (!vertexSource) {
  200. vertexSource = baseName.vertexElement;
  201. }
  202. }
  203. else {
  204. vertexSource = baseName.vertex || baseName;
  205. }
  206. if (baseName.fragmentElement) {
  207. fragmentSource = document.getElementById(baseName.fragmentElement);
  208. if (!fragmentSource) {
  209. fragmentSource = baseName.fragmentElement;
  210. }
  211. }
  212. else {
  213. fragmentSource = baseName.fragment || baseName;
  214. }
  215. this._loadVertexShader(vertexSource, function (vertexCode) {
  216. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  217. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  218. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  219. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  220. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  221. if (baseName) {
  222. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  223. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  224. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  225. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  226. }
  227. else {
  228. _this._vertexSourceCode = migratedVertexCode;
  229. _this._fragmentSourceCode = migratedFragmentCode;
  230. }
  231. _this._prepareEffect();
  232. });
  233. });
  234. });
  235. });
  236. });
  237. });
  238. }
  239. Object.defineProperty(Effect.prototype, "onBindObservable", {
  240. /**
  241. * Observable that will be called when effect is bound.
  242. */
  243. get: function () {
  244. if (!this._onBindObservable) {
  245. this._onBindObservable = new BABYLON.Observable();
  246. }
  247. return this._onBindObservable;
  248. },
  249. enumerable: true,
  250. configurable: true
  251. });
  252. Object.defineProperty(Effect.prototype, "key", {
  253. /**
  254. * Unique key for this effect
  255. */
  256. get: function () {
  257. return this._key;
  258. },
  259. enumerable: true,
  260. configurable: true
  261. });
  262. /**
  263. * If the effect has been compiled and prepared.
  264. * @returns if the effect is compiled and prepared.
  265. */
  266. Effect.prototype.isReady = function () {
  267. if (!this._isReady && this._program && this._program.isParallelCompiled) {
  268. return this._engine._isProgramCompiled(this._program);
  269. }
  270. return this._isReady;
  271. };
  272. /**
  273. * The engine the effect was initialized with.
  274. * @returns the engine.
  275. */
  276. Effect.prototype.getEngine = function () {
  277. return this._engine;
  278. };
  279. /**
  280. * The compiled webGL program for the effect
  281. * @returns the webGL program.
  282. */
  283. Effect.prototype.getProgram = function () {
  284. return this._program;
  285. };
  286. /**
  287. * The set of names of attribute variables for the shader.
  288. * @returns An array of attribute names.
  289. */
  290. Effect.prototype.getAttributesNames = function () {
  291. return this._attributesNames;
  292. };
  293. /**
  294. * Returns the attribute at the given index.
  295. * @param index The index of the attribute.
  296. * @returns The location of the attribute.
  297. */
  298. Effect.prototype.getAttributeLocation = function (index) {
  299. return this._attributes[index];
  300. };
  301. /**
  302. * Returns the attribute based on the name of the variable.
  303. * @param name of the attribute to look up.
  304. * @returns the attribute location.
  305. */
  306. Effect.prototype.getAttributeLocationByName = function (name) {
  307. var index = this._attributesNames.indexOf(name);
  308. return this._attributes[index];
  309. };
  310. /**
  311. * The number of attributes.
  312. * @returns the numnber of attributes.
  313. */
  314. Effect.prototype.getAttributesCount = function () {
  315. return this._attributes.length;
  316. };
  317. /**
  318. * Gets the index of a uniform variable.
  319. * @param uniformName of the uniform to look up.
  320. * @returns the index.
  321. */
  322. Effect.prototype.getUniformIndex = function (uniformName) {
  323. return this._uniformsNames.indexOf(uniformName);
  324. };
  325. /**
  326. * Returns the attribute based on the name of the variable.
  327. * @param uniformName of the uniform to look up.
  328. * @returns the location of the uniform.
  329. */
  330. Effect.prototype.getUniform = function (uniformName) {
  331. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  332. };
  333. /**
  334. * Returns an array of sampler variable names
  335. * @returns The array of sampler variable neames.
  336. */
  337. Effect.prototype.getSamplers = function () {
  338. return this._samplers;
  339. };
  340. /**
  341. * The error from the last compilation.
  342. * @returns the error string.
  343. */
  344. Effect.prototype.getCompilationError = function () {
  345. return this._compilationError;
  346. };
  347. /**
  348. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  349. * @param func The callback to be used.
  350. */
  351. Effect.prototype.executeWhenCompiled = function (func) {
  352. var _this = this;
  353. if (this.isReady()) {
  354. func(this);
  355. return;
  356. }
  357. this.onCompileObservable.add(function (effect) {
  358. func(effect);
  359. });
  360. if (!this._program || this._program.isParallelCompiled) {
  361. setTimeout(function () {
  362. _this._checkIsReady();
  363. }, 16);
  364. }
  365. };
  366. Effect.prototype._checkIsReady = function () {
  367. var _this = this;
  368. if (this.isReady()) {
  369. return;
  370. }
  371. setTimeout(function () {
  372. _this._checkIsReady();
  373. }, 16);
  374. };
  375. /** @hidden */
  376. Effect.prototype._loadVertexShader = function (vertex, callback) {
  377. if (BABYLON.Tools.IsWindowObjectExist()) {
  378. // DOM element ?
  379. if (vertex instanceof HTMLElement) {
  380. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  381. callback(vertexCode);
  382. return;
  383. }
  384. }
  385. // Base64 encoded ?
  386. if (vertex.substr(0, 7) === "base64:") {
  387. var vertexBinary = window.atob(vertex.substr(7));
  388. callback(vertexBinary);
  389. return;
  390. }
  391. // Is in local store ?
  392. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  393. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  394. return;
  395. }
  396. var vertexShaderUrl;
  397. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  398. vertexShaderUrl = vertex;
  399. }
  400. else {
  401. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  402. }
  403. // Vertex shader
  404. this._engine._loadFile(vertexShaderUrl + ".vertex.fx", callback);
  405. };
  406. /** @hidden */
  407. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  408. if (BABYLON.Tools.IsWindowObjectExist()) {
  409. // DOM element ?
  410. if (fragment instanceof HTMLElement) {
  411. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  412. callback(fragmentCode);
  413. return;
  414. }
  415. }
  416. // Base64 encoded ?
  417. if (fragment.substr(0, 7) === "base64:") {
  418. var fragmentBinary = window.atob(fragment.substr(7));
  419. callback(fragmentBinary);
  420. return;
  421. }
  422. // Is in local store ?
  423. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  424. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  425. return;
  426. }
  427. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  428. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  429. return;
  430. }
  431. var fragmentShaderUrl;
  432. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  433. fragmentShaderUrl = fragment;
  434. }
  435. else {
  436. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  437. }
  438. // Fragment shader
  439. this._engine._loadFile(fragmentShaderUrl + ".fragment.fx", callback);
  440. };
  441. /** @hidden */
  442. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  443. // Rebuild shaders source code
  444. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  445. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  446. vertexCode = prefix + vertexCode;
  447. fragmentCode = prefix + fragmentCode;
  448. // Number lines of shaders source code
  449. var i = 2;
  450. var regex = /\n/gm;
  451. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  452. i = 2;
  453. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  454. // Dump shaders name and formatted source code
  455. if (this.name.vertexElement) {
  456. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  457. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  458. }
  459. else if (this.name.vertex) {
  460. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  461. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  462. }
  463. else {
  464. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  465. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  466. }
  467. };
  468. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  469. var preparedSourceCode = this._processPrecision(sourceCode);
  470. if (this._engine.webGLVersion == 1) {
  471. callback(preparedSourceCode);
  472. return;
  473. }
  474. // Already converted
  475. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  476. callback(preparedSourceCode.replace("#version 300 es", ""));
  477. return;
  478. }
  479. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  480. // Remove extensions
  481. // #extension GL_OES_standard_derivatives : enable
  482. // #extension GL_EXT_shader_texture_lod : enable
  483. // #extension GL_EXT_frag_depth : enable
  484. // #extension GL_EXT_draw_buffers : require
  485. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  486. var result = preparedSourceCode.replace(regex, "");
  487. // Migrate to GLSL v300
  488. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  489. result = result.replace(/attribute[ \t]/g, "in ");
  490. result = result.replace(/[ \t]attribute/g, " in");
  491. result = result.replace(/texture2D\s*\(/g, "texture(");
  492. if (isFragment) {
  493. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  494. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  495. result = result.replace(/textureCube\s*\(/g, "texture(");
  496. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  497. result = result.replace(/gl_FragColor/g, "glFragColor");
  498. result = result.replace(/gl_FragData/g, "glFragData");
  499. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  500. }
  501. callback(result);
  502. };
  503. Effect.prototype._processIncludes = function (sourceCode, callback) {
  504. var _this = this;
  505. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  506. var match = regex.exec(sourceCode);
  507. var returnValue = new String(sourceCode);
  508. while (match != null) {
  509. var includeFile = match[1];
  510. // Uniform declaration
  511. if (includeFile.indexOf("__decl__") !== -1) {
  512. includeFile = includeFile.replace(/__decl__/, "");
  513. if (this._engine.supportsUniformBuffers) {
  514. includeFile = includeFile.replace(/Vertex/, "Ubo");
  515. includeFile = includeFile.replace(/Fragment/, "Ubo");
  516. }
  517. includeFile = includeFile + "Declaration";
  518. }
  519. if (Effect.IncludesShadersStore[includeFile]) {
  520. // Substitution
  521. var includeContent = Effect.IncludesShadersStore[includeFile];
  522. if (match[2]) {
  523. var splits = match[3].split(",");
  524. for (var index = 0; index < splits.length; index += 2) {
  525. var source = new RegExp(splits[index], "g");
  526. var dest = splits[index + 1];
  527. includeContent = includeContent.replace(source, dest);
  528. }
  529. }
  530. if (match[4]) {
  531. var indexString = match[5];
  532. if (indexString.indexOf("..") !== -1) {
  533. var indexSplits = indexString.split("..");
  534. var minIndex = parseInt(indexSplits[0]);
  535. var maxIndex = parseInt(indexSplits[1]);
  536. var sourceIncludeContent = includeContent.slice(0);
  537. includeContent = "";
  538. if (isNaN(maxIndex)) {
  539. maxIndex = this._indexParameters[indexSplits[1]];
  540. }
  541. for (var i = minIndex; i < maxIndex; i++) {
  542. if (!this._engine.supportsUniformBuffers) {
  543. // Ubo replacement
  544. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  545. return p1 + "{X}";
  546. });
  547. }
  548. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  549. }
  550. }
  551. else {
  552. if (!this._engine.supportsUniformBuffers) {
  553. // Ubo replacement
  554. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  555. return p1 + "{X}";
  556. });
  557. }
  558. includeContent = includeContent.replace(/\{X\}/g, indexString);
  559. }
  560. }
  561. // Replace
  562. returnValue = returnValue.replace(match[0], includeContent);
  563. }
  564. else {
  565. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  566. this._engine._loadFile(includeShaderUrl, function (fileContent) {
  567. Effect.IncludesShadersStore[includeFile] = fileContent;
  568. _this._processIncludes(returnValue, callback);
  569. });
  570. return;
  571. }
  572. match = regex.exec(sourceCode);
  573. }
  574. callback(returnValue);
  575. };
  576. Effect.prototype._processPrecision = function (source) {
  577. if (source.indexOf("precision highp float") === -1) {
  578. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  579. source = "precision mediump float;\n" + source;
  580. }
  581. else {
  582. source = "precision highp float;\n" + source;
  583. }
  584. }
  585. else {
  586. if (!this._engine.getCaps().highPrecisionShaderSupported) { // Moving highp to mediump
  587. source = source.replace("precision highp float", "precision mediump float");
  588. }
  589. }
  590. return source;
  591. };
  592. /**
  593. * Recompiles the webGL program
  594. * @param vertexSourceCode The source code for the vertex shader.
  595. * @param fragmentSourceCode The source code for the fragment shader.
  596. * @param onCompiled Callback called when completed.
  597. * @param onError Callback called on error.
  598. * @hidden
  599. */
  600. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  601. var _this = this;
  602. this._isReady = false;
  603. this._vertexSourceCodeOverride = vertexSourceCode;
  604. this._fragmentSourceCodeOverride = fragmentSourceCode;
  605. this.onError = function (effect, error) {
  606. if (onError) {
  607. onError(error);
  608. }
  609. };
  610. this.onCompiled = function () {
  611. var scenes = _this.getEngine().scenes;
  612. for (var i = 0; i < scenes.length; i++) {
  613. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  614. }
  615. if (onCompiled) {
  616. onCompiled(_this._program);
  617. }
  618. };
  619. this._fallbacks = null;
  620. this._prepareEffect();
  621. };
  622. /**
  623. * Gets the uniform locations of the the specified variable names
  624. * @param names THe names of the variables to lookup.
  625. * @returns Array of locations in the same order as variable names.
  626. */
  627. Effect.prototype.getSpecificUniformLocations = function (names) {
  628. var engine = this._engine;
  629. return engine.getUniforms(this._program, names);
  630. };
  631. /**
  632. * Prepares the effect
  633. * @hidden
  634. */
  635. Effect.prototype._prepareEffect = function () {
  636. var _this = this;
  637. var attributesNames = this._attributesNames;
  638. var defines = this.defines;
  639. var fallbacks = this._fallbacks;
  640. this._valueCache = {};
  641. var previousProgram = this._program;
  642. try {
  643. var engine_1 = this._engine;
  644. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  645. this._program = engine_1.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  646. }
  647. else {
  648. this._program = engine_1.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  649. }
  650. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  651. engine_1._executeWhenProgramIsCompiled(this._program, function () {
  652. if (engine_1.supportsUniformBuffers) {
  653. for (var name in _this._uniformBuffersNames) {
  654. _this.bindUniformBlock(name, _this._uniformBuffersNames[name]);
  655. }
  656. }
  657. _this._uniforms = engine_1.getUniforms(_this._program, _this._uniformsNames);
  658. _this._attributes = engine_1.getAttributes(_this._program, attributesNames);
  659. var index;
  660. for (index = 0; index < _this._samplers.length; index++) {
  661. var sampler = _this.getUniform(_this._samplers[index]);
  662. if (sampler == null) {
  663. _this._samplers.splice(index, 1);
  664. index--;
  665. }
  666. }
  667. engine_1.bindSamplers(_this);
  668. _this._compilationError = "";
  669. _this._isReady = true;
  670. if (_this.onCompiled) {
  671. _this.onCompiled(_this);
  672. }
  673. _this.onCompileObservable.notifyObservers(_this);
  674. _this.onCompileObservable.clear();
  675. // Unbind mesh reference in fallbacks
  676. if (_this._fallbacks) {
  677. _this._fallbacks.unBindMesh();
  678. }
  679. if (previousProgram) {
  680. _this.getEngine()._deleteProgram(previousProgram);
  681. }
  682. });
  683. if (this._program.isParallelCompiled) {
  684. this._checkIsReady();
  685. }
  686. }
  687. catch (e) {
  688. this._compilationError = e.message;
  689. // Let's go through fallbacks then
  690. BABYLON.Tools.Error("Unable to compile effect:");
  691. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  692. return " " + uniform;
  693. }));
  694. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  695. return " " + attribute;
  696. }));
  697. BABYLON.Tools.Error("Error: " + this._compilationError);
  698. if (previousProgram) {
  699. this._program = previousProgram;
  700. this._isReady = true;
  701. if (this.onError) {
  702. this.onError(this, this._compilationError);
  703. }
  704. this.onErrorObservable.notifyObservers(this);
  705. }
  706. if (fallbacks && fallbacks.isMoreFallbacks) {
  707. BABYLON.Tools.Error("Trying next fallback.");
  708. this.defines = fallbacks.reduce(this.defines, this);
  709. this._prepareEffect();
  710. }
  711. else { // Sorry we did everything we can
  712. if (this.onError) {
  713. this.onError(this, this._compilationError);
  714. }
  715. this.onErrorObservable.notifyObservers(this);
  716. this.onErrorObservable.clear();
  717. // Unbind mesh reference in fallbacks
  718. if (this._fallbacks) {
  719. this._fallbacks.unBindMesh();
  720. }
  721. }
  722. }
  723. };
  724. Object.defineProperty(Effect.prototype, "isSupported", {
  725. /**
  726. * Checks if the effect is supported. (Must be called after compilation)
  727. */
  728. get: function () {
  729. return this._compilationError === "";
  730. },
  731. enumerable: true,
  732. configurable: true
  733. });
  734. /**
  735. * Binds a texture to the engine to be used as output of the shader.
  736. * @param channel Name of the output variable.
  737. * @param texture Texture to bind.
  738. * @hidden
  739. */
  740. Effect.prototype._bindTexture = function (channel, texture) {
  741. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  742. };
  743. /**
  744. * Sets a texture on the engine to be used in the shader.
  745. * @param channel Name of the sampler variable.
  746. * @param texture Texture to set.
  747. */
  748. Effect.prototype.setTexture = function (channel, texture) {
  749. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  750. };
  751. /**
  752. * Sets a depth stencil texture from a render target on the engine to be used in the shader.
  753. * @param channel Name of the sampler variable.
  754. * @param texture Texture to set.
  755. */
  756. Effect.prototype.setDepthStencilTexture = function (channel, texture) {
  757. this._engine.setDepthStencilTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  758. };
  759. /**
  760. * Sets an array of textures on the engine to be used in the shader.
  761. * @param channel Name of the variable.
  762. * @param textures Textures to set.
  763. */
  764. Effect.prototype.setTextureArray = function (channel, textures) {
  765. if (this._samplers.indexOf(channel + "Ex") === -1) {
  766. var initialPos = this._samplers.indexOf(channel);
  767. for (var index = 1; index < textures.length; index++) {
  768. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  769. }
  770. }
  771. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  772. };
  773. /**
  774. * 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)
  775. * @param channel Name of the sampler variable.
  776. * @param postProcess Post process to get the input texture from.
  777. */
  778. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  779. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  780. };
  781. /**
  782. * (Warning! setTextureFromPostProcessOutput may be desired instead)
  783. * 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)
  784. * @param channel Name of the sampler variable.
  785. * @param postProcess Post process to get the output texture from.
  786. */
  787. Effect.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  788. this._engine.setTextureFromPostProcessOutput(this._samplers.indexOf(channel), postProcess);
  789. };
  790. /** @hidden */
  791. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  792. var cache = this._valueCache[uniformName];
  793. var flag = matrix.updateFlag;
  794. if (cache !== undefined && cache === flag) {
  795. return false;
  796. }
  797. this._valueCache[uniformName] = flag;
  798. return true;
  799. };
  800. /** @hidden */
  801. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  802. var cache = this._valueCache[uniformName];
  803. if (!cache) {
  804. cache = [x, y];
  805. this._valueCache[uniformName] = cache;
  806. return true;
  807. }
  808. var changed = false;
  809. if (cache[0] !== x) {
  810. cache[0] = x;
  811. changed = true;
  812. }
  813. if (cache[1] !== y) {
  814. cache[1] = y;
  815. changed = true;
  816. }
  817. return changed;
  818. };
  819. /** @hidden */
  820. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  821. var cache = this._valueCache[uniformName];
  822. if (!cache) {
  823. cache = [x, y, z];
  824. this._valueCache[uniformName] = cache;
  825. return true;
  826. }
  827. var changed = false;
  828. if (cache[0] !== x) {
  829. cache[0] = x;
  830. changed = true;
  831. }
  832. if (cache[1] !== y) {
  833. cache[1] = y;
  834. changed = true;
  835. }
  836. if (cache[2] !== z) {
  837. cache[2] = z;
  838. changed = true;
  839. }
  840. return changed;
  841. };
  842. /** @hidden */
  843. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  844. var cache = this._valueCache[uniformName];
  845. if (!cache) {
  846. cache = [x, y, z, w];
  847. this._valueCache[uniformName] = cache;
  848. return true;
  849. }
  850. var changed = false;
  851. if (cache[0] !== x) {
  852. cache[0] = x;
  853. changed = true;
  854. }
  855. if (cache[1] !== y) {
  856. cache[1] = y;
  857. changed = true;
  858. }
  859. if (cache[2] !== z) {
  860. cache[2] = z;
  861. changed = true;
  862. }
  863. if (cache[3] !== w) {
  864. cache[3] = w;
  865. changed = true;
  866. }
  867. return changed;
  868. };
  869. /**
  870. * Binds a buffer to a uniform.
  871. * @param buffer Buffer to bind.
  872. * @param name Name of the uniform variable to bind to.
  873. */
  874. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  875. var bufferName = this._uniformBuffersNames[name];
  876. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  877. return;
  878. }
  879. Effect._baseCache[bufferName] = buffer;
  880. this._engine.bindUniformBufferBase(buffer, bufferName);
  881. };
  882. /**
  883. * Binds block to a uniform.
  884. * @param blockName Name of the block to bind.
  885. * @param index Index to bind.
  886. */
  887. Effect.prototype.bindUniformBlock = function (blockName, index) {
  888. this._engine.bindUniformBlock(this._program, blockName, index);
  889. };
  890. /**
  891. * Sets an interger value on a uniform variable.
  892. * @param uniformName Name of the variable.
  893. * @param value Value to be set.
  894. * @returns this effect.
  895. */
  896. Effect.prototype.setInt = function (uniformName, value) {
  897. var cache = this._valueCache[uniformName];
  898. if (cache !== undefined && cache === value) {
  899. return this;
  900. }
  901. this._valueCache[uniformName] = value;
  902. this._engine.setInt(this.getUniform(uniformName), value);
  903. return this;
  904. };
  905. /**
  906. * Sets an int array on a uniform variable.
  907. * @param uniformName Name of the variable.
  908. * @param array array to be set.
  909. * @returns this effect.
  910. */
  911. Effect.prototype.setIntArray = function (uniformName, array) {
  912. this._valueCache[uniformName] = null;
  913. this._engine.setIntArray(this.getUniform(uniformName), array);
  914. return this;
  915. };
  916. /**
  917. * 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)
  918. * @param uniformName Name of the variable.
  919. * @param array array to be set.
  920. * @returns this effect.
  921. */
  922. Effect.prototype.setIntArray2 = function (uniformName, array) {
  923. this._valueCache[uniformName] = null;
  924. this._engine.setIntArray2(this.getUniform(uniformName), array);
  925. return this;
  926. };
  927. /**
  928. * 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)
  929. * @param uniformName Name of the variable.
  930. * @param array array to be set.
  931. * @returns this effect.
  932. */
  933. Effect.prototype.setIntArray3 = function (uniformName, array) {
  934. this._valueCache[uniformName] = null;
  935. this._engine.setIntArray3(this.getUniform(uniformName), array);
  936. return this;
  937. };
  938. /**
  939. * 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)
  940. * @param uniformName Name of the variable.
  941. * @param array array to be set.
  942. * @returns this effect.
  943. */
  944. Effect.prototype.setIntArray4 = function (uniformName, array) {
  945. this._valueCache[uniformName] = null;
  946. this._engine.setIntArray4(this.getUniform(uniformName), array);
  947. return this;
  948. };
  949. /**
  950. * Sets an float array on a uniform variable.
  951. * @param uniformName Name of the variable.
  952. * @param array array to be set.
  953. * @returns this effect.
  954. */
  955. Effect.prototype.setFloatArray = function (uniformName, array) {
  956. this._valueCache[uniformName] = null;
  957. this._engine.setFloatArray(this.getUniform(uniformName), array);
  958. return this;
  959. };
  960. /**
  961. * 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)
  962. * @param uniformName Name of the variable.
  963. * @param array array to be set.
  964. * @returns this effect.
  965. */
  966. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  967. this._valueCache[uniformName] = null;
  968. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  969. return this;
  970. };
  971. /**
  972. * 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)
  973. * @param uniformName Name of the variable.
  974. * @param array array to be set.
  975. * @returns this effect.
  976. */
  977. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  978. this._valueCache[uniformName] = null;
  979. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  980. return this;
  981. };
  982. /**
  983. * 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)
  984. * @param uniformName Name of the variable.
  985. * @param array array to be set.
  986. * @returns this effect.
  987. */
  988. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  989. this._valueCache[uniformName] = null;
  990. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  991. return this;
  992. };
  993. /**
  994. * Sets an array on a uniform variable.
  995. * @param uniformName Name of the variable.
  996. * @param array array to be set.
  997. * @returns this effect.
  998. */
  999. Effect.prototype.setArray = function (uniformName, array) {
  1000. this._valueCache[uniformName] = null;
  1001. this._engine.setArray(this.getUniform(uniformName), array);
  1002. return this;
  1003. };
  1004. /**
  1005. * 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)
  1006. * @param uniformName Name of the variable.
  1007. * @param array array to be set.
  1008. * @returns this effect.
  1009. */
  1010. Effect.prototype.setArray2 = function (uniformName, array) {
  1011. this._valueCache[uniformName] = null;
  1012. this._engine.setArray2(this.getUniform(uniformName), array);
  1013. return this;
  1014. };
  1015. /**
  1016. * 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)
  1017. * @param uniformName Name of the variable.
  1018. * @param array array to be set.
  1019. * @returns this effect.
  1020. */
  1021. Effect.prototype.setArray3 = function (uniformName, array) {
  1022. this._valueCache[uniformName] = null;
  1023. this._engine.setArray3(this.getUniform(uniformName), array);
  1024. return this;
  1025. };
  1026. /**
  1027. * 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)
  1028. * @param uniformName Name of the variable.
  1029. * @param array array to be set.
  1030. * @returns this effect.
  1031. */
  1032. Effect.prototype.setArray4 = function (uniformName, array) {
  1033. this._valueCache[uniformName] = null;
  1034. this._engine.setArray4(this.getUniform(uniformName), array);
  1035. return this;
  1036. };
  1037. /**
  1038. * Sets matrices on a uniform variable.
  1039. * @param uniformName Name of the variable.
  1040. * @param matrices matrices to be set.
  1041. * @returns this effect.
  1042. */
  1043. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1044. if (!matrices) {
  1045. return this;
  1046. }
  1047. this._valueCache[uniformName] = null;
  1048. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1049. return this;
  1050. };
  1051. /**
  1052. * Sets matrix on a uniform variable.
  1053. * @param uniformName Name of the variable.
  1054. * @param matrix matrix to be set.
  1055. * @returns this effect.
  1056. */
  1057. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1058. if (this._cacheMatrix(uniformName, matrix)) {
  1059. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1060. }
  1061. return this;
  1062. };
  1063. /**
  1064. * 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)
  1065. * @param uniformName Name of the variable.
  1066. * @param matrix matrix to be set.
  1067. * @returns this effect.
  1068. */
  1069. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1070. this._valueCache[uniformName] = null;
  1071. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1072. return this;
  1073. };
  1074. /**
  1075. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1076. * @param uniformName Name of the variable.
  1077. * @param matrix matrix to be set.
  1078. * @returns this effect.
  1079. */
  1080. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1081. this._valueCache[uniformName] = null;
  1082. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1083. return this;
  1084. };
  1085. /**
  1086. * Sets a float on a uniform variable.
  1087. * @param uniformName Name of the variable.
  1088. * @param value value to be set.
  1089. * @returns this effect.
  1090. */
  1091. Effect.prototype.setFloat = function (uniformName, value) {
  1092. var cache = this._valueCache[uniformName];
  1093. if (cache !== undefined && cache === value) {
  1094. return this;
  1095. }
  1096. this._valueCache[uniformName] = value;
  1097. this._engine.setFloat(this.getUniform(uniformName), value);
  1098. return this;
  1099. };
  1100. /**
  1101. * Sets a boolean on a uniform variable.
  1102. * @param uniformName Name of the variable.
  1103. * @param bool value to be set.
  1104. * @returns this effect.
  1105. */
  1106. Effect.prototype.setBool = function (uniformName, bool) {
  1107. var cache = this._valueCache[uniformName];
  1108. if (cache !== undefined && cache === bool) {
  1109. return this;
  1110. }
  1111. this._valueCache[uniformName] = bool;
  1112. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1113. return this;
  1114. };
  1115. /**
  1116. * Sets a Vector2 on a uniform variable.
  1117. * @param uniformName Name of the variable.
  1118. * @param vector2 vector2 to be set.
  1119. * @returns this effect.
  1120. */
  1121. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1122. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1123. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1124. }
  1125. return this;
  1126. };
  1127. /**
  1128. * Sets a float2 on a uniform variable.
  1129. * @param uniformName Name of the variable.
  1130. * @param x First float in float2.
  1131. * @param y Second float in float2.
  1132. * @returns this effect.
  1133. */
  1134. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1135. if (this._cacheFloat2(uniformName, x, y)) {
  1136. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1137. }
  1138. return this;
  1139. };
  1140. /**
  1141. * Sets a Vector3 on a uniform variable.
  1142. * @param uniformName Name of the variable.
  1143. * @param vector3 Value to be set.
  1144. * @returns this effect.
  1145. */
  1146. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1147. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1148. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1149. }
  1150. return this;
  1151. };
  1152. /**
  1153. * Sets a float3 on a uniform variable.
  1154. * @param uniformName Name of the variable.
  1155. * @param x First float in float3.
  1156. * @param y Second float in float3.
  1157. * @param z Third float in float3.
  1158. * @returns this effect.
  1159. */
  1160. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1161. if (this._cacheFloat3(uniformName, x, y, z)) {
  1162. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1163. }
  1164. return this;
  1165. };
  1166. /**
  1167. * Sets a Vector4 on a uniform variable.
  1168. * @param uniformName Name of the variable.
  1169. * @param vector4 Value to be set.
  1170. * @returns this effect.
  1171. */
  1172. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1173. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1174. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1175. }
  1176. return this;
  1177. };
  1178. /**
  1179. * Sets a float4 on a uniform variable.
  1180. * @param uniformName Name of the variable.
  1181. * @param x First float in float4.
  1182. * @param y Second float in float4.
  1183. * @param z Third float in float4.
  1184. * @param w Fourth float in float4.
  1185. * @returns this effect.
  1186. */
  1187. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1188. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1189. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1190. }
  1191. return this;
  1192. };
  1193. /**
  1194. * Sets a Color3 on a uniform variable.
  1195. * @param uniformName Name of the variable.
  1196. * @param color3 Value to be set.
  1197. * @returns this effect.
  1198. */
  1199. Effect.prototype.setColor3 = function (uniformName, color3) {
  1200. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1201. this._engine.setColor3(this.getUniform(uniformName), color3);
  1202. }
  1203. return this;
  1204. };
  1205. /**
  1206. * Sets a Color4 on a uniform variable.
  1207. * @param uniformName Name of the variable.
  1208. * @param color3 Value to be set.
  1209. * @param alpha Alpha value to be set.
  1210. * @returns this effect.
  1211. */
  1212. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1213. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1214. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1215. }
  1216. return this;
  1217. };
  1218. /**
  1219. * Sets a Color4 on a uniform variable
  1220. * @param uniformName defines the name of the variable
  1221. * @param color4 defines the value to be set
  1222. * @returns this effect.
  1223. */
  1224. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1225. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1226. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1227. }
  1228. return this;
  1229. };
  1230. /**
  1231. * This function will add a new shader to the shader store
  1232. * @param name the name of the shader
  1233. * @param pixelShader optional pixel shader content
  1234. * @param vertexShader optional vertex shader content
  1235. */
  1236. Effect.RegisterShader = function (name, pixelShader, vertexShader) {
  1237. if (pixelShader) {
  1238. Effect.ShadersStore[name + "PixelShader"] = pixelShader;
  1239. }
  1240. if (vertexShader) {
  1241. Effect.ShadersStore[name + "VertexShader"] = vertexShader;
  1242. }
  1243. };
  1244. /**
  1245. * Resets the cache of effects.
  1246. */
  1247. Effect.ResetCache = function () {
  1248. Effect._baseCache = {};
  1249. };
  1250. Effect._uniqueIdSeed = 0;
  1251. Effect._baseCache = {};
  1252. /**
  1253. * Store of each shader (The can be looked up using effect.key)
  1254. */
  1255. Effect.ShadersStore = {};
  1256. /**
  1257. * Store of each included file for a shader (The can be looked up using effect.key)
  1258. */
  1259. Effect.IncludesShadersStore = {};
  1260. return Effect;
  1261. }());
  1262. BABYLON.Effect = Effect;
  1263. })(BABYLON || (BABYLON = {}));
  1264. //# sourceMappingURL=babylon.effect.js.map
  1265. //# sourceMappingURL=babylon.types.js.map
  1266. var BABYLON;
  1267. (function (BABYLON) {
  1268. /**
  1269. * Gather the list of keyboard event types as constants.
  1270. */
  1271. var KeyboardEventTypes = /** @class */ (function () {
  1272. function KeyboardEventTypes() {
  1273. }
  1274. /**
  1275. * The keydown event is fired when a key becomes active (pressed).
  1276. */
  1277. KeyboardEventTypes.KEYDOWN = 0x01;
  1278. /**
  1279. * The keyup event is fired when a key has been released.
  1280. */
  1281. KeyboardEventTypes.KEYUP = 0x02;
  1282. return KeyboardEventTypes;
  1283. }());
  1284. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1285. /**
  1286. * This class is used to store keyboard related info for the onKeyboardObservable event.
  1287. */
  1288. var KeyboardInfo = /** @class */ (function () {
  1289. /**
  1290. * Instantiates a new keyboard info.
  1291. * This class is used to store keyboard related info for the onKeyboardObservable event.
  1292. * @param type Defines the type of event (BABYLON.KeyboardEventTypes)
  1293. * @param event Defines the related dom event
  1294. */
  1295. function KeyboardInfo(
  1296. /**
  1297. * Defines the type of event (BABYLON.KeyboardEventTypes)
  1298. */
  1299. type,
  1300. /**
  1301. * Defines the related dom event
  1302. */
  1303. event) {
  1304. this.type = type;
  1305. this.event = event;
  1306. }
  1307. return KeyboardInfo;
  1308. }());
  1309. BABYLON.KeyboardInfo = KeyboardInfo;
  1310. /**
  1311. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1312. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1313. */
  1314. var KeyboardInfoPre = /** @class */ (function (_super) {
  1315. __extends(KeyboardInfoPre, _super);
  1316. /**
  1317. * Instantiates a new keyboard pre info.
  1318. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1319. * @param type Defines the type of event (BABYLON.KeyboardEventTypes)
  1320. * @param event Defines the related dom event
  1321. */
  1322. function KeyboardInfoPre(
  1323. /**
  1324. * Defines the type of event (BABYLON.KeyboardEventTypes)
  1325. */
  1326. type,
  1327. /**
  1328. * Defines the related dom event
  1329. */
  1330. event) {
  1331. var _this = _super.call(this, type, event) || this;
  1332. _this.type = type;
  1333. _this.event = event;
  1334. _this.skipOnPointerObservable = false;
  1335. return _this;
  1336. }
  1337. return KeyboardInfoPre;
  1338. }(KeyboardInfo));
  1339. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1340. })(BABYLON || (BABYLON = {}));
  1341. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1342. var BABYLON;
  1343. (function (BABYLON) {
  1344. /**
  1345. * Gather the list of pointer event types as constants.
  1346. */
  1347. var PointerEventTypes = /** @class */ (function () {
  1348. function PointerEventTypes() {
  1349. }
  1350. /**
  1351. * 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.
  1352. */
  1353. PointerEventTypes.POINTERDOWN = 0x01;
  1354. /**
  1355. * The pointerup event is fired when a pointer is no longer active.
  1356. */
  1357. PointerEventTypes.POINTERUP = 0x02;
  1358. /**
  1359. * The pointermove event is fired when a pointer changes coordinates.
  1360. */
  1361. PointerEventTypes.POINTERMOVE = 0x04;
  1362. /**
  1363. * The pointerwheel event is fired when a mouse wheel has been rotated.
  1364. */
  1365. PointerEventTypes.POINTERWHEEL = 0x08;
  1366. /**
  1367. * The pointerpick event is fired when a mesh or sprite has been picked by the pointer.
  1368. */
  1369. PointerEventTypes.POINTERPICK = 0x10;
  1370. /**
  1371. * The pointertap event is fired when a the object has been touched and released without drag.
  1372. */
  1373. PointerEventTypes.POINTERTAP = 0x20;
  1374. /**
  1375. * The pointerdoubletap event is fired when a the object has been touched and released twice without drag.
  1376. */
  1377. PointerEventTypes.POINTERDOUBLETAP = 0x40;
  1378. return PointerEventTypes;
  1379. }());
  1380. BABYLON.PointerEventTypes = PointerEventTypes;
  1381. /**
  1382. * Base class of pointer info types.
  1383. */
  1384. var PointerInfoBase = /** @class */ (function () {
  1385. /**
  1386. * Instantiates the base class of pointers info.
  1387. * @param type Defines the type of event (BABYLON.PointerEventTypes)
  1388. * @param event Defines the related dom event
  1389. */
  1390. function PointerInfoBase(
  1391. /**
  1392. * Defines the type of event (BABYLON.PointerEventTypes)
  1393. */
  1394. type,
  1395. /**
  1396. * Defines the related dom event
  1397. */
  1398. event) {
  1399. this.type = type;
  1400. this.event = event;
  1401. }
  1402. return PointerInfoBase;
  1403. }());
  1404. BABYLON.PointerInfoBase = PointerInfoBase;
  1405. /**
  1406. * This class is used to store pointer related info for the onPrePointerObservable event.
  1407. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1408. */
  1409. var PointerInfoPre = /** @class */ (function (_super) {
  1410. __extends(PointerInfoPre, _super);
  1411. /**
  1412. * Instantiates a PointerInfoPre to store pointer related info to the onPrePointerObservable event.
  1413. * @param type Defines the type of event (BABYLON.PointerEventTypes)
  1414. * @param event Defines the related dom event
  1415. * @param localX Defines the local x coordinates of the pointer when the event occured
  1416. * @param localY Defines the local y coordinates of the pointer when the event occured
  1417. */
  1418. function PointerInfoPre(type, event, localX, localY) {
  1419. var _this = _super.call(this, type, event) || this;
  1420. /**
  1421. * Ray from a pointer if availible (eg. 6dof controller)
  1422. */
  1423. _this.ray = null;
  1424. _this.skipOnPointerObservable = false;
  1425. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1426. return _this;
  1427. }
  1428. return PointerInfoPre;
  1429. }(PointerInfoBase));
  1430. BABYLON.PointerInfoPre = PointerInfoPre;
  1431. /**
  1432. * This type contains all the data related to a pointer event in Babylon.js.
  1433. * 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.
  1434. */
  1435. var PointerInfo = /** @class */ (function (_super) {
  1436. __extends(PointerInfo, _super);
  1437. /**
  1438. * Instantiates a PointerInfo to store pointer related info to the onPointerObservable event.
  1439. * @param type Defines the type of event (BABYLON.PointerEventTypes)
  1440. * @param event Defines the related dom event
  1441. * @param pickInfo Defines the picking info associated to the info (if any)\
  1442. */
  1443. function PointerInfo(type, event,
  1444. /**
  1445. * Defines the picking info associated to the info (if any)\
  1446. */
  1447. pickInfo) {
  1448. var _this = _super.call(this, type, event) || this;
  1449. _this.pickInfo = pickInfo;
  1450. return _this;
  1451. }
  1452. return PointerInfo;
  1453. }(PointerInfoBase));
  1454. BABYLON.PointerInfo = PointerInfo;
  1455. })(BABYLON || (BABYLON = {}));
  1456. //# sourceMappingURL=babylon.pointerEvents.js.map
  1457. var BABYLON;
  1458. (function (BABYLON) {
  1459. /**
  1460. * Gather the list of clipboard event types as constants.
  1461. */
  1462. var ClipboardEventTypes = /** @class */ (function () {
  1463. function ClipboardEventTypes() {
  1464. }
  1465. /**
  1466. * The clipboard event is fired when a copy command is active (pressed).
  1467. */
  1468. ClipboardEventTypes.COPY = 0x01; //
  1469. /**
  1470. * The clipboard event is fired when a cut command is active (pressed).
  1471. */
  1472. ClipboardEventTypes.CUT = 0x02;
  1473. /**
  1474. * The clipboard event is fired when a paste command is active (pressed).
  1475. */
  1476. ClipboardEventTypes.PASTE = 0x03;
  1477. return ClipboardEventTypes;
  1478. }());
  1479. BABYLON.ClipboardEventTypes = ClipboardEventTypes;
  1480. /**
  1481. * This class is used to store clipboard related info for the onClipboardObservable event.
  1482. */
  1483. var ClipboardInfo = /** @class */ (function () {
  1484. /**
  1485. *Creates an instance of ClipboardInfo.
  1486. * @param {number} type
  1487. * @param {ClipboardEvent} event
  1488. */
  1489. function ClipboardInfo(
  1490. /**
  1491. * Defines the type of event (BABYLON.ClipboardEventTypes)
  1492. */
  1493. type,
  1494. /**
  1495. * Defines the related dom event
  1496. */
  1497. event) {
  1498. this.type = type;
  1499. this.event = event;
  1500. }
  1501. /**
  1502. * Get the clipboard event's type from the keycode.
  1503. * @param keyCode Defines the keyCode for the current keyboard event.
  1504. * @return {number}
  1505. */
  1506. ClipboardInfo.GetTypeFromCharacter = function (keyCode) {
  1507. var charCode = keyCode;
  1508. //TODO: add codes for extended ASCII
  1509. switch (charCode) {
  1510. case 67: return ClipboardEventTypes.COPY;
  1511. case 86: return ClipboardEventTypes.PASTE;
  1512. case 88: return ClipboardEventTypes.CUT;
  1513. default: return -1;
  1514. }
  1515. };
  1516. return ClipboardInfo;
  1517. }());
  1518. BABYLON.ClipboardInfo = ClipboardInfo;
  1519. })(BABYLON || (BABYLON = {}));
  1520. //# sourceMappingURL=babylon.clipboardEvents.js.map
  1521. var BABYLON;
  1522. (function (BABYLON) {
  1523. /** Class used to store color4 gradient */
  1524. var ColorGradient = /** @class */ (function () {
  1525. function ColorGradient() {
  1526. }
  1527. /**
  1528. * Will get a color picked randomly between color1 and color2.
  1529. * If color2 is undefined then color1 will be used
  1530. * @param result defines the target Color4 to store the result in
  1531. */
  1532. ColorGradient.prototype.getColorToRef = function (result) {
  1533. if (!this.color2) {
  1534. result.copyFrom(this.color1);
  1535. return;
  1536. }
  1537. BABYLON.Color4.LerpToRef(this.color1, this.color2, Math.random(), result);
  1538. };
  1539. return ColorGradient;
  1540. }());
  1541. BABYLON.ColorGradient = ColorGradient;
  1542. /** Class used to store color 3 gradient */
  1543. var Color3Gradient = /** @class */ (function () {
  1544. function Color3Gradient() {
  1545. }
  1546. return Color3Gradient;
  1547. }());
  1548. BABYLON.Color3Gradient = Color3Gradient;
  1549. /** Class used to store factor gradient */
  1550. var FactorGradient = /** @class */ (function () {
  1551. function FactorGradient() {
  1552. }
  1553. /**
  1554. * Will get a number picked randomly between factor1 and factor2.
  1555. * If factor2 is undefined then factor1 will be used
  1556. * @returns the picked number
  1557. */
  1558. FactorGradient.prototype.getFactor = function () {
  1559. if (this.factor2 === undefined) {
  1560. return this.factor1;
  1561. }
  1562. return BABYLON.Scalar.Lerp(this.factor1, this.factor2, Math.random());
  1563. };
  1564. return FactorGradient;
  1565. }());
  1566. BABYLON.FactorGradient = FactorGradient;
  1567. /**
  1568. * @ignore
  1569. * Application error to support additional information when loading a file
  1570. */
  1571. var LoadFileError = /** @class */ (function (_super) {
  1572. __extends(LoadFileError, _super);
  1573. /**
  1574. * Creates a new LoadFileError
  1575. * @param message defines the message of the error
  1576. * @param request defines the optional XHR request
  1577. */
  1578. function LoadFileError(message,
  1579. /** defines the optional XHR request */
  1580. request) {
  1581. var _this = _super.call(this, message) || this;
  1582. _this.request = request;
  1583. _this.name = "LoadFileError";
  1584. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  1585. return _this;
  1586. }
  1587. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  1588. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  1589. // Polyfill for Object.setPrototypeOf if necessary.
  1590. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  1591. return LoadFileError;
  1592. }(Error));
  1593. BABYLON.LoadFileError = LoadFileError;
  1594. /**
  1595. * Class used to define a retry strategy when error happens while loading assets
  1596. */
  1597. var RetryStrategy = /** @class */ (function () {
  1598. function RetryStrategy() {
  1599. }
  1600. /**
  1601. * Function used to defines an exponential back off strategy
  1602. * @param maxRetries defines the maximum number of retries (3 by default)
  1603. * @param baseInterval defines the interval between retries
  1604. * @returns the strategy function to use
  1605. */
  1606. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  1607. if (maxRetries === void 0) { maxRetries = 3; }
  1608. if (baseInterval === void 0) { baseInterval = 500; }
  1609. return function (url, request, retryIndex) {
  1610. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  1611. return -1;
  1612. }
  1613. return Math.pow(2, retryIndex) * baseInterval;
  1614. };
  1615. };
  1616. return RetryStrategy;
  1617. }());
  1618. BABYLON.RetryStrategy = RetryStrategy;
  1619. // Screenshots
  1620. var screenshotCanvas;
  1621. var cloneValue = function (source, destinationObject) {
  1622. if (!source) {
  1623. return null;
  1624. }
  1625. if (source instanceof BABYLON.Mesh) {
  1626. return null;
  1627. }
  1628. if (source instanceof BABYLON.SubMesh) {
  1629. return source.clone(destinationObject);
  1630. }
  1631. else if (source.clone) {
  1632. return source.clone();
  1633. }
  1634. return null;
  1635. };
  1636. /**
  1637. * Class containing a set of static utilities functions
  1638. */
  1639. var Tools = /** @class */ (function () {
  1640. function Tools() {
  1641. }
  1642. /**
  1643. * Read the content of a byte array at a specified coordinates (taking in account wrapping)
  1644. * @param u defines the coordinate on X axis
  1645. * @param v defines the coordinate on Y axis
  1646. * @param width defines the width of the source data
  1647. * @param height defines the height of the source data
  1648. * @param pixels defines the source byte array
  1649. * @param color defines the output color
  1650. */
  1651. Tools.FetchToRef = function (u, v, width, height, pixels, color) {
  1652. var wrappedU = ((Math.abs(u) * width) % width) | 0;
  1653. var wrappedV = ((Math.abs(v) * height) % height) | 0;
  1654. var position = (wrappedU + wrappedV * width) * 4;
  1655. color.r = pixels[position] / 255;
  1656. color.g = pixels[position + 1] / 255;
  1657. color.b = pixels[position + 2] / 255;
  1658. color.a = pixels[position + 3] / 255;
  1659. };
  1660. /**
  1661. * Interpolates between a and b via alpha
  1662. * @param a The lower value (returned when alpha = 0)
  1663. * @param b The upper value (returned when alpha = 1)
  1664. * @param alpha The interpolation-factor
  1665. * @return The mixed value
  1666. */
  1667. Tools.Mix = function (a, b, alpha) {
  1668. return a * (1 - alpha) + b * alpha;
  1669. };
  1670. /**
  1671. * Tries to instantiate a new object from a given class name
  1672. * @param className defines the class name to instantiate
  1673. * @returns the new object or null if the system was not able to do the instantiation
  1674. */
  1675. Tools.Instantiate = function (className) {
  1676. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  1677. return Tools.RegisteredExternalClasses[className];
  1678. }
  1679. var arr = className.split(".");
  1680. var fn = (window || this);
  1681. for (var i = 0, len = arr.length; i < len; i++) {
  1682. fn = fn[arr[i]];
  1683. }
  1684. if (typeof fn !== "function") {
  1685. return null;
  1686. }
  1687. return fn;
  1688. };
  1689. /**
  1690. * Provides a slice function that will work even on IE
  1691. * @param data defines the array to slice
  1692. * @param start defines the start of the data (optional)
  1693. * @param end defines the end of the data (optional)
  1694. * @returns the new sliced array
  1695. */
  1696. Tools.Slice = function (data, start, end) {
  1697. if (data.slice) {
  1698. return data.slice(start, end);
  1699. }
  1700. return Array.prototype.slice.call(data, start, end);
  1701. };
  1702. /**
  1703. * Polyfill for setImmediate
  1704. * @param action defines the action to execute after the current execution block
  1705. */
  1706. Tools.SetImmediate = function (action) {
  1707. if (Tools.IsWindowObjectExist() && window.setImmediate) {
  1708. window.setImmediate(action);
  1709. }
  1710. else {
  1711. setTimeout(action, 1);
  1712. }
  1713. };
  1714. /**
  1715. * Function indicating if a number is an exponent of 2
  1716. * @param value defines the value to test
  1717. * @returns true if the value is an exponent of 2
  1718. */
  1719. Tools.IsExponentOfTwo = function (value) {
  1720. var count = 1;
  1721. do {
  1722. count *= 2;
  1723. } while (count < value);
  1724. return count === value;
  1725. };
  1726. /**
  1727. * Returns the nearest 32-bit single precision float representation of a Number
  1728. * @param value A Number. If the parameter is of a different type, it will get converted
  1729. * to a number or to NaN if it cannot be converted
  1730. * @returns number
  1731. */
  1732. Tools.FloatRound = function (value) {
  1733. if (Math.fround) {
  1734. return Math.fround(value);
  1735. }
  1736. return (Tools._tmpFloatArray[0] = value);
  1737. };
  1738. /**
  1739. * Find the next highest power of two.
  1740. * @param x Number to start search from.
  1741. * @return Next highest power of two.
  1742. */
  1743. Tools.CeilingPOT = function (x) {
  1744. x--;
  1745. x |= x >> 1;
  1746. x |= x >> 2;
  1747. x |= x >> 4;
  1748. x |= x >> 8;
  1749. x |= x >> 16;
  1750. x++;
  1751. return x;
  1752. };
  1753. /**
  1754. * Find the next lowest power of two.
  1755. * @param x Number to start search from.
  1756. * @return Next lowest power of two.
  1757. */
  1758. Tools.FloorPOT = function (x) {
  1759. x = x | (x >> 1);
  1760. x = x | (x >> 2);
  1761. x = x | (x >> 4);
  1762. x = x | (x >> 8);
  1763. x = x | (x >> 16);
  1764. return x - (x >> 1);
  1765. };
  1766. /**
  1767. * Find the nearest power of two.
  1768. * @param x Number to start search from.
  1769. * @return Next nearest power of two.
  1770. */
  1771. Tools.NearestPOT = function (x) {
  1772. var c = Tools.CeilingPOT(x);
  1773. var f = Tools.FloorPOT(x);
  1774. return (c - x) > (x - f) ? f : c;
  1775. };
  1776. /**
  1777. * Get the closest exponent of two
  1778. * @param value defines the value to approximate
  1779. * @param max defines the maximum value to return
  1780. * @param mode defines how to define the closest value
  1781. * @returns closest exponent of two of the given value
  1782. */
  1783. Tools.GetExponentOfTwo = function (value, max, mode) {
  1784. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  1785. var pot;
  1786. switch (mode) {
  1787. case BABYLON.Engine.SCALEMODE_FLOOR:
  1788. pot = Tools.FloorPOT(value);
  1789. break;
  1790. case BABYLON.Engine.SCALEMODE_NEAREST:
  1791. pot = Tools.NearestPOT(value);
  1792. break;
  1793. case BABYLON.Engine.SCALEMODE_CEILING:
  1794. default:
  1795. pot = Tools.CeilingPOT(value);
  1796. break;
  1797. }
  1798. return Math.min(pot, max);
  1799. };
  1800. /**
  1801. * Extracts the filename from a path
  1802. * @param path defines the path to use
  1803. * @returns the filename
  1804. */
  1805. Tools.GetFilename = function (path) {
  1806. var index = path.lastIndexOf("/");
  1807. if (index < 0) {
  1808. return path;
  1809. }
  1810. return path.substring(index + 1);
  1811. };
  1812. /**
  1813. * Extracts the "folder" part of a path (everything before the filename).
  1814. * @param uri The URI to extract the info from
  1815. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  1816. * @returns The "folder" part of the path
  1817. */
  1818. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  1819. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  1820. var index = uri.lastIndexOf("/");
  1821. if (index < 0) {
  1822. if (returnUnchangedIfNoSlash) {
  1823. return uri;
  1824. }
  1825. return "";
  1826. }
  1827. return uri.substring(0, index + 1);
  1828. };
  1829. /**
  1830. * Extracts text content from a DOM element hierarchy
  1831. * @param element defines the root element
  1832. * @returns a string
  1833. */
  1834. Tools.GetDOMTextContent = function (element) {
  1835. var result = "";
  1836. var child = element.firstChild;
  1837. while (child) {
  1838. if (child.nodeType === 3) {
  1839. result += child.textContent;
  1840. }
  1841. child = (child.nextSibling);
  1842. }
  1843. return result;
  1844. };
  1845. /**
  1846. * Convert an angle in radians to degrees
  1847. * @param angle defines the angle to convert
  1848. * @returns the angle in degrees
  1849. */
  1850. Tools.ToDegrees = function (angle) {
  1851. return angle * 180 / Math.PI;
  1852. };
  1853. /**
  1854. * Convert an angle in degrees to radians
  1855. * @param angle defines the angle to convert
  1856. * @returns the angle in radians
  1857. */
  1858. Tools.ToRadians = function (angle) {
  1859. return angle * Math.PI / 180;
  1860. };
  1861. /**
  1862. * Encode a buffer to a base64 string
  1863. * @param buffer defines the buffer to encode
  1864. * @returns the encoded string
  1865. */
  1866. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  1867. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  1868. var output = "";
  1869. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  1870. var i = 0;
  1871. var bytes = new Uint8Array(buffer);
  1872. while (i < bytes.length) {
  1873. chr1 = bytes[i++];
  1874. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  1875. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  1876. enc1 = chr1 >> 2;
  1877. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  1878. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  1879. enc4 = chr3 & 63;
  1880. if (isNaN(chr2)) {
  1881. enc3 = enc4 = 64;
  1882. }
  1883. else if (isNaN(chr3)) {
  1884. enc4 = 64;
  1885. }
  1886. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  1887. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  1888. }
  1889. return "data:image/png;base64," + output;
  1890. };
  1891. /**
  1892. * Extracts minimum and maximum values from a list of indexed positions
  1893. * @param positions defines the positions to use
  1894. * @param indices defines the indices to the positions
  1895. * @param indexStart defines the start index
  1896. * @param indexCount defines the end index
  1897. * @param bias defines bias value to add to the result
  1898. * @return minimum and maximum values
  1899. */
  1900. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  1901. if (bias === void 0) { bias = null; }
  1902. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  1903. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  1904. for (var index = indexStart; index < indexStart + indexCount; index++) {
  1905. var offset = indices[index] * 3;
  1906. var x = positions[offset];
  1907. var y = positions[offset + 1];
  1908. var z = positions[offset + 2];
  1909. minimum.minimizeInPlaceFromFloats(x, y, z);
  1910. maximum.maximizeInPlaceFromFloats(x, y, z);
  1911. }
  1912. if (bias) {
  1913. minimum.x -= minimum.x * bias.x + bias.y;
  1914. minimum.y -= minimum.y * bias.x + bias.y;
  1915. minimum.z -= minimum.z * bias.x + bias.y;
  1916. maximum.x += maximum.x * bias.x + bias.y;
  1917. maximum.y += maximum.y * bias.x + bias.y;
  1918. maximum.z += maximum.z * bias.x + bias.y;
  1919. }
  1920. return {
  1921. minimum: minimum,
  1922. maximum: maximum
  1923. };
  1924. };
  1925. /**
  1926. * Extracts minimum and maximum values from a list of positions
  1927. * @param positions defines the positions to use
  1928. * @param start defines the start index in the positions array
  1929. * @param count defines the number of positions to handle
  1930. * @param bias defines bias value to add to the result
  1931. * @param stride defines the stride size to use (distance between two positions in the positions array)
  1932. * @return minimum and maximum values
  1933. */
  1934. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  1935. if (bias === void 0) { bias = null; }
  1936. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  1937. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  1938. if (!stride) {
  1939. stride = 3;
  1940. }
  1941. for (var index = start, offset = start * stride; index < start + count; index++, offset += stride) {
  1942. var x = positions[offset];
  1943. var y = positions[offset + 1];
  1944. var z = positions[offset + 2];
  1945. minimum.minimizeInPlaceFromFloats(x, y, z);
  1946. maximum.maximizeInPlaceFromFloats(x, y, z);
  1947. }
  1948. if (bias) {
  1949. minimum.x -= minimum.x * bias.x + bias.y;
  1950. minimum.y -= minimum.y * bias.x + bias.y;
  1951. minimum.z -= minimum.z * bias.x + bias.y;
  1952. maximum.x += maximum.x * bias.x + bias.y;
  1953. maximum.y += maximum.y * bias.x + bias.y;
  1954. maximum.z += maximum.z * bias.x + bias.y;
  1955. }
  1956. return {
  1957. minimum: minimum,
  1958. maximum: maximum
  1959. };
  1960. };
  1961. /**
  1962. * Returns an array if obj is not an array
  1963. * @param obj defines the object to evaluate as an array
  1964. * @param allowsNullUndefined defines a boolean indicating if obj is allowed to be null or undefined
  1965. * @returns either obj directly if obj is an array or a new array containing obj
  1966. */
  1967. Tools.MakeArray = function (obj, allowsNullUndefined) {
  1968. if (allowsNullUndefined !== true && (obj === undefined || obj == null)) {
  1969. return null;
  1970. }
  1971. return Array.isArray(obj) ? obj : [obj];
  1972. };
  1973. /**
  1974. * Returns an array of the given size filled with element built from the given constructor and the paramters
  1975. * @param size the number of element to construct and put in the array
  1976. * @param itemBuilder a callback responsible for creating new instance of item. Called once per array entry.
  1977. * @returns a new array filled with new objects
  1978. */
  1979. Tools.BuildArray = function (size, itemBuilder) {
  1980. var a = [];
  1981. for (var i = 0; i < size; ++i) {
  1982. a.push(itemBuilder());
  1983. }
  1984. return a;
  1985. };
  1986. /**
  1987. * Gets the pointer prefix to use
  1988. * @returns "pointer" if touch is enabled. Else returns "mouse"
  1989. */
  1990. Tools.GetPointerPrefix = function () {
  1991. var eventPrefix = "pointer";
  1992. // Check if pointer events are supported
  1993. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  1994. eventPrefix = "mouse";
  1995. }
  1996. return eventPrefix;
  1997. };
  1998. /**
  1999. * Queue a new function into the requested animation frame pool (ie. this function will be executed byt the browser for the next frame)
  2000. * @param func - the function to be called
  2001. * @param requester - the object that will request the next frame. Falls back to window.
  2002. * @returns frame number
  2003. */
  2004. Tools.QueueNewFrame = function (func, requester) {
  2005. if (!Tools.IsWindowObjectExist()) {
  2006. return setTimeout(func, 16);
  2007. }
  2008. if (!requester) {
  2009. requester = window;
  2010. }
  2011. if (requester.requestAnimationFrame) {
  2012. return requester.requestAnimationFrame(func);
  2013. }
  2014. else if (requester.msRequestAnimationFrame) {
  2015. return requester.msRequestAnimationFrame(func);
  2016. }
  2017. else if (requester.webkitRequestAnimationFrame) {
  2018. return requester.webkitRequestAnimationFrame(func);
  2019. }
  2020. else if (requester.mozRequestAnimationFrame) {
  2021. return requester.mozRequestAnimationFrame(func);
  2022. }
  2023. else if (requester.oRequestAnimationFrame) {
  2024. return requester.oRequestAnimationFrame(func);
  2025. }
  2026. else {
  2027. return window.setTimeout(func, 16);
  2028. }
  2029. };
  2030. /**
  2031. * Ask the browser to promote the current element to fullscreen rendering mode
  2032. * @param element defines the DOM element to promote
  2033. */
  2034. Tools.RequestFullscreen = function (element) {
  2035. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  2036. if (!requestFunction) {
  2037. return;
  2038. }
  2039. requestFunction.call(element);
  2040. };
  2041. /**
  2042. * Asks the browser to exit fullscreen mode
  2043. */
  2044. Tools.ExitFullscreen = function () {
  2045. if (document.exitFullscreen) {
  2046. document.exitFullscreen();
  2047. }
  2048. else if (document.mozCancelFullScreen) {
  2049. document.mozCancelFullScreen();
  2050. }
  2051. else if (document.webkitCancelFullScreen) {
  2052. document.webkitCancelFullScreen();
  2053. }
  2054. else if (document.msCancelFullScreen) {
  2055. document.msCancelFullScreen();
  2056. }
  2057. };
  2058. /**
  2059. * Sets the cors behavior on a dom element. This will add the required Tools.CorsBehavior to the element.
  2060. * @param url define the url we are trying
  2061. * @param element define the dom element where to configure the cors policy
  2062. */
  2063. Tools.SetCorsBehavior = function (url, element) {
  2064. if (url && url.indexOf("data:") === 0) {
  2065. return;
  2066. }
  2067. if (Tools.CorsBehavior) {
  2068. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  2069. element.crossOrigin = Tools.CorsBehavior;
  2070. }
  2071. else {
  2072. var result = Tools.CorsBehavior(url);
  2073. if (result) {
  2074. element.crossOrigin = result;
  2075. }
  2076. }
  2077. }
  2078. };
  2079. // External files
  2080. /**
  2081. * Removes unwanted characters from an url
  2082. * @param url defines the url to clean
  2083. * @returns the cleaned url
  2084. */
  2085. Tools.CleanUrl = function (url) {
  2086. url = url.replace(/#/mg, "%23");
  2087. return url;
  2088. };
  2089. /**
  2090. * Loads an image as an HTMLImageElement.
  2091. * @param input url string, ArrayBuffer, or Blob to load
  2092. * @param onLoad callback called when the image successfully loads
  2093. * @param onError callback called when the image fails to load
  2094. * @param offlineProvider offline provider for caching
  2095. * @returns the HTMLImageElement of the loaded image
  2096. */
  2097. Tools.LoadImage = function (input, onLoad, onError, offlineProvider) {
  2098. var url;
  2099. var usingObjectURL = false;
  2100. if (input instanceof ArrayBuffer) {
  2101. url = URL.createObjectURL(new Blob([input]));
  2102. usingObjectURL = true;
  2103. }
  2104. else if (input instanceof Blob) {
  2105. url = URL.createObjectURL(input);
  2106. usingObjectURL = true;
  2107. }
  2108. else {
  2109. url = Tools.CleanUrl(input);
  2110. url = Tools.PreprocessUrl(input);
  2111. }
  2112. var img = new Image();
  2113. Tools.SetCorsBehavior(url, img);
  2114. var loadHandler = function () {
  2115. if (usingObjectURL && img.src) {
  2116. URL.revokeObjectURL(img.src);
  2117. }
  2118. img.removeEventListener("load", loadHandler);
  2119. img.removeEventListener("error", errorHandler);
  2120. onLoad(img);
  2121. };
  2122. var errorHandler = function (err) {
  2123. if (usingObjectURL && img.src) {
  2124. URL.revokeObjectURL(img.src);
  2125. }
  2126. img.removeEventListener("load", loadHandler);
  2127. img.removeEventListener("error", errorHandler);
  2128. Tools.Error("Error while trying to load image: " + input);
  2129. if (onError) {
  2130. onError("Error while trying to load image: " + input, err);
  2131. }
  2132. };
  2133. img.addEventListener("load", loadHandler);
  2134. img.addEventListener("error", errorHandler);
  2135. var noOfflineSupport = function () {
  2136. img.src = url;
  2137. };
  2138. var loadFromOfflineSupport = function () {
  2139. if (offlineProvider) {
  2140. offlineProvider.loadImage(url, img);
  2141. }
  2142. };
  2143. if (url.substr(0, 5) !== "data:" && offlineProvider && offlineProvider.enableTexturesOffline) {
  2144. offlineProvider.open(loadFromOfflineSupport, noOfflineSupport);
  2145. }
  2146. else {
  2147. if (url.indexOf("file:") !== -1) {
  2148. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  2149. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  2150. try {
  2151. var blobURL;
  2152. try {
  2153. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  2154. }
  2155. catch (ex) {
  2156. // Chrome doesn't support oneTimeOnly parameter
  2157. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  2158. }
  2159. img.src = blobURL;
  2160. usingObjectURL = true;
  2161. }
  2162. catch (e) {
  2163. img.src = "";
  2164. }
  2165. return img;
  2166. }
  2167. }
  2168. noOfflineSupport();
  2169. }
  2170. return img;
  2171. };
  2172. /**
  2173. * Loads a file
  2174. * @param url url string, ArrayBuffer, or Blob to load
  2175. * @param onSuccess callback called when the file successfully loads
  2176. * @param onProgress callback called while file is loading (if the server supports this mode)
  2177. * @param offlineProvider defines the offline provider for caching
  2178. * @param useArrayBuffer defines a boolean indicating that date must be returned as ArrayBuffer
  2179. * @param onError callback called when the file fails to load
  2180. * @returns a file request object
  2181. */
  2182. Tools.LoadFile = function (url, onSuccess, onProgress, offlineProvider, useArrayBuffer, onError) {
  2183. url = Tools.CleanUrl(url);
  2184. url = Tools.PreprocessUrl(url);
  2185. // If file and file input are set
  2186. if (url.indexOf("file:") !== -1) {
  2187. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  2188. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  2189. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  2190. }
  2191. }
  2192. var loadUrl = Tools.BaseUrl + url;
  2193. var aborted = false;
  2194. var fileRequest = {
  2195. onCompleteObservable: new BABYLON.Observable(),
  2196. abort: function () { return aborted = true; },
  2197. };
  2198. var requestFile = function () {
  2199. var request = new XMLHttpRequest();
  2200. var retryHandle = null;
  2201. fileRequest.abort = function () {
  2202. aborted = true;
  2203. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  2204. request.abort();
  2205. }
  2206. if (retryHandle !== null) {
  2207. clearTimeout(retryHandle);
  2208. retryHandle = null;
  2209. }
  2210. };
  2211. var retryLoop = function (retryIndex) {
  2212. request.open('GET', loadUrl, true);
  2213. if (useArrayBuffer) {
  2214. request.responseType = "arraybuffer";
  2215. }
  2216. if (onProgress) {
  2217. request.addEventListener("progress", onProgress);
  2218. }
  2219. var onLoadEnd = function () {
  2220. request.removeEventListener("loadend", onLoadEnd);
  2221. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  2222. fileRequest.onCompleteObservable.clear();
  2223. };
  2224. request.addEventListener("loadend", onLoadEnd);
  2225. var onReadyStateChange = function () {
  2226. if (aborted) {
  2227. return;
  2228. }
  2229. // In case of undefined state in some browsers.
  2230. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  2231. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  2232. request.removeEventListener("readystatechange", onReadyStateChange);
  2233. if ((request.status >= 200 && request.status < 300) || (request.status === 0 && (!Tools.IsWindowObjectExist() || Tools.IsFileURL()))) {
  2234. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  2235. return;
  2236. }
  2237. var retryStrategy = Tools.DefaultRetryStrategy;
  2238. if (retryStrategy) {
  2239. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  2240. if (waitTime !== -1) {
  2241. // Prevent the request from completing for retry.
  2242. request.removeEventListener("loadend", onLoadEnd);
  2243. request = new XMLHttpRequest();
  2244. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  2245. return;
  2246. }
  2247. }
  2248. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  2249. if (onError) {
  2250. onError(request, e);
  2251. }
  2252. else {
  2253. throw e;
  2254. }
  2255. }
  2256. };
  2257. request.addEventListener("readystatechange", onReadyStateChange);
  2258. if (Tools.UseCustomRequestHeaders) {
  2259. Tools.InjectCustomRequestHeaders(request);
  2260. }
  2261. request.send();
  2262. };
  2263. retryLoop(0);
  2264. };
  2265. // Caching all files
  2266. if (offlineProvider && offlineProvider.enableSceneOffline) {
  2267. var noOfflineSupport_1 = function (request) {
  2268. if (request && request.status > 400) {
  2269. if (onError) {
  2270. onError(request);
  2271. }
  2272. }
  2273. else {
  2274. if (!aborted) {
  2275. requestFile();
  2276. }
  2277. }
  2278. };
  2279. var loadFromOfflineSupport = function () {
  2280. // TODO: database needs to support aborting and should return a IFileRequest
  2281. if (aborted) {
  2282. return;
  2283. }
  2284. if (offlineProvider) {
  2285. offlineProvider.loadFile(url, function (data) {
  2286. if (!aborted) {
  2287. onSuccess(data);
  2288. }
  2289. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  2290. }, onProgress ? function (event) {
  2291. if (!aborted) {
  2292. onProgress(event);
  2293. }
  2294. } : undefined, noOfflineSupport_1, useArrayBuffer);
  2295. }
  2296. };
  2297. offlineProvider.open(loadFromOfflineSupport, noOfflineSupport_1);
  2298. }
  2299. else {
  2300. requestFile();
  2301. }
  2302. return fileRequest;
  2303. };
  2304. /**
  2305. * Load a script (identified by an url). When the url returns, the
  2306. * content of this file is added into a new script element, attached to the DOM (body element)
  2307. * @param scriptUrl defines the url of the script to laod
  2308. * @param onSuccess defines the callback called when the script is loaded
  2309. * @param onError defines the callback to call if an error occurs
  2310. */
  2311. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  2312. if (!Tools.IsWindowObjectExist()) {
  2313. return;
  2314. }
  2315. var head = document.getElementsByTagName('head')[0];
  2316. var script = document.createElement('script');
  2317. script.type = 'text/javascript';
  2318. script.src = scriptUrl;
  2319. script.onload = function () {
  2320. if (onSuccess) {
  2321. onSuccess();
  2322. }
  2323. };
  2324. script.onerror = function (e) {
  2325. if (onError) {
  2326. onError("Unable to load script '" + scriptUrl + "'", e);
  2327. }
  2328. };
  2329. head.appendChild(script);
  2330. };
  2331. /**
  2332. * Loads a file from a blob
  2333. * @param fileToLoad defines the blob to use
  2334. * @param callback defines the callback to call when data is loaded
  2335. * @param progressCallback defines the callback to call during loading process
  2336. * @returns a file request object
  2337. */
  2338. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  2339. var reader = new FileReader();
  2340. var request = {
  2341. onCompleteObservable: new BABYLON.Observable(),
  2342. abort: function () { return reader.abort(); },
  2343. };
  2344. reader.onloadend = function (e) {
  2345. request.onCompleteObservable.notifyObservers(request);
  2346. };
  2347. reader.onload = function (e) {
  2348. //target doesn't have result from ts 1.3
  2349. callback(e.target['result']);
  2350. };
  2351. reader.onprogress = progressCallback;
  2352. reader.readAsDataURL(fileToLoad);
  2353. return request;
  2354. };
  2355. /**
  2356. * Loads a file
  2357. * @param fileToLoad defines the file to load
  2358. * @param callback defines the callback to call when data is loaded
  2359. * @param progressCallBack defines the callback to call during loading process
  2360. * @param useArrayBuffer defines a boolean indicating that data must be returned as an ArrayBuffer
  2361. * @returns a file request object
  2362. */
  2363. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  2364. var reader = new FileReader();
  2365. var request = {
  2366. onCompleteObservable: new BABYLON.Observable(),
  2367. abort: function () { return reader.abort(); },
  2368. };
  2369. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  2370. reader.onerror = function (e) {
  2371. Tools.Log("Error while reading file: " + fileToLoad.name);
  2372. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  2373. };
  2374. reader.onload = function (e) {
  2375. //target doesn't have result from ts 1.3
  2376. callback(e.target['result']);
  2377. };
  2378. if (progressCallBack) {
  2379. reader.onprogress = progressCallBack;
  2380. }
  2381. if (!useArrayBuffer) {
  2382. // Asynchronous read
  2383. reader.readAsText(fileToLoad);
  2384. }
  2385. else {
  2386. reader.readAsArrayBuffer(fileToLoad);
  2387. }
  2388. return request;
  2389. };
  2390. /**
  2391. * Creates a data url from a given string content
  2392. * @param content defines the content to convert
  2393. * @returns the new data url link
  2394. */
  2395. Tools.FileAsURL = function (content) {
  2396. var fileBlob = new Blob([content]);
  2397. var url = window.URL || window.webkitURL;
  2398. var link = url.createObjectURL(fileBlob);
  2399. return link;
  2400. };
  2401. /**
  2402. * Format the given number to a specific decimal format
  2403. * @param value defines the number to format
  2404. * @param decimals defines the number of decimals to use
  2405. * @returns the formatted string
  2406. */
  2407. Tools.Format = function (value, decimals) {
  2408. if (decimals === void 0) { decimals = 2; }
  2409. return value.toFixed(decimals);
  2410. };
  2411. /**
  2412. * Checks if a given vector is inside a specific range
  2413. * @param v defines the vector to test
  2414. * @param min defines the minimum range
  2415. * @param max defines the maximum range
  2416. */
  2417. Tools.CheckExtends = function (v, min, max) {
  2418. min.minimizeInPlace(v);
  2419. max.maximizeInPlace(v);
  2420. };
  2421. /**
  2422. * Tries to copy an object by duplicating every property
  2423. * @param source defines the source object
  2424. * @param destination defines the target object
  2425. * @param doNotCopyList defines a list of properties to avoid
  2426. * @param mustCopyList defines a list of properties to copy (even if they start with _)
  2427. */
  2428. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  2429. for (var prop in source) {
  2430. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  2431. continue;
  2432. }
  2433. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  2434. continue;
  2435. }
  2436. var sourceValue = source[prop];
  2437. var typeOfSourceValue = typeof sourceValue;
  2438. if (typeOfSourceValue === "function") {
  2439. continue;
  2440. }
  2441. try {
  2442. if (typeOfSourceValue === "object") {
  2443. if (sourceValue instanceof Array) {
  2444. destination[prop] = [];
  2445. if (sourceValue.length > 0) {
  2446. if (typeof sourceValue[0] == "object") {
  2447. for (var index = 0; index < sourceValue.length; index++) {
  2448. var clonedValue = cloneValue(sourceValue[index], destination);
  2449. if (destination[prop].indexOf(clonedValue) === -1) { // Test if auto inject was not done
  2450. destination[prop].push(clonedValue);
  2451. }
  2452. }
  2453. }
  2454. else {
  2455. destination[prop] = sourceValue.slice(0);
  2456. }
  2457. }
  2458. }
  2459. else {
  2460. destination[prop] = cloneValue(sourceValue, destination);
  2461. }
  2462. }
  2463. else {
  2464. destination[prop] = sourceValue;
  2465. }
  2466. }
  2467. catch (e) {
  2468. // Just ignore error (it could be because of a read-only property)
  2469. }
  2470. }
  2471. };
  2472. /**
  2473. * Gets a boolean indicating if the given object has no own property
  2474. * @param obj defines the object to test
  2475. * @returns true if object has no own property
  2476. */
  2477. Tools.IsEmpty = function (obj) {
  2478. for (var i in obj) {
  2479. if (obj.hasOwnProperty(i)) {
  2480. return false;
  2481. }
  2482. }
  2483. return true;
  2484. };
  2485. /**
  2486. * Function used to register events at window level
  2487. * @param events defines the events to register
  2488. */
  2489. Tools.RegisterTopRootEvents = function (events) {
  2490. for (var index = 0; index < events.length; index++) {
  2491. var event = events[index];
  2492. window.addEventListener(event.name, event.handler, false);
  2493. try {
  2494. if (window.parent) {
  2495. window.parent.addEventListener(event.name, event.handler, false);
  2496. }
  2497. }
  2498. catch (e) {
  2499. // Silently fails...
  2500. }
  2501. }
  2502. };
  2503. /**
  2504. * Function used to unregister events from window level
  2505. * @param events defines the events to unregister
  2506. */
  2507. Tools.UnregisterTopRootEvents = function (events) {
  2508. for (var index = 0; index < events.length; index++) {
  2509. var event = events[index];
  2510. window.removeEventListener(event.name, event.handler);
  2511. try {
  2512. if (window.parent) {
  2513. window.parent.removeEventListener(event.name, event.handler);
  2514. }
  2515. }
  2516. catch (e) {
  2517. // Silently fails...
  2518. }
  2519. }
  2520. };
  2521. /**
  2522. * Dumps the current bound framebuffer
  2523. * @param width defines the rendering width
  2524. * @param height defines the rendering height
  2525. * @param engine defines the hosting engine
  2526. * @param successCallback defines the callback triggered once the data are available
  2527. * @param mimeType defines the mime type of the result
  2528. * @param fileName defines the filename to download. If present, the result will automatically be downloaded
  2529. */
  2530. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  2531. if (mimeType === void 0) { mimeType = "image/png"; }
  2532. // Read the contents of the framebuffer
  2533. var numberOfChannelsByLine = width * 4;
  2534. var halfHeight = height / 2;
  2535. //Reading datas from WebGL
  2536. var data = engine.readPixels(0, 0, width, height);
  2537. //To flip image on Y axis.
  2538. for (var i = 0; i < halfHeight; i++) {
  2539. for (var j = 0; j < numberOfChannelsByLine; j++) {
  2540. var currentCell = j + i * numberOfChannelsByLine;
  2541. var targetLine = height - i - 1;
  2542. var targetCell = j + targetLine * numberOfChannelsByLine;
  2543. var temp = data[currentCell];
  2544. data[currentCell] = data[targetCell];
  2545. data[targetCell] = temp;
  2546. }
  2547. }
  2548. // Create a 2D canvas to store the result
  2549. if (!screenshotCanvas) {
  2550. screenshotCanvas = document.createElement('canvas');
  2551. }
  2552. screenshotCanvas.width = width;
  2553. screenshotCanvas.height = height;
  2554. var context = screenshotCanvas.getContext('2d');
  2555. if (context) {
  2556. // Copy the pixels to a 2D canvas
  2557. var imageData = context.createImageData(width, height);
  2558. var castData = (imageData.data);
  2559. castData.set(data);
  2560. context.putImageData(imageData, 0, 0);
  2561. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  2562. }
  2563. };
  2564. /**
  2565. * Converts the canvas data to blob.
  2566. * This acts as a polyfill for browsers not supporting the to blob function.
  2567. * @param canvas Defines the canvas to extract the data from
  2568. * @param successCallback Defines the callback triggered once the data are available
  2569. * @param mimeType Defines the mime type of the result
  2570. */
  2571. Tools.ToBlob = function (canvas, successCallback, mimeType) {
  2572. if (mimeType === void 0) { mimeType = "image/png"; }
  2573. // We need HTMLCanvasElement.toBlob for HD screenshots
  2574. if (!canvas.toBlob) {
  2575. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  2576. canvas.toBlob = function (callback, type, quality) {
  2577. var _this = this;
  2578. setTimeout(function () {
  2579. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  2580. for (var i = 0; i < len; i++) {
  2581. arr[i] = binStr.charCodeAt(i);
  2582. }
  2583. callback(new Blob([arr]));
  2584. });
  2585. };
  2586. }
  2587. canvas.toBlob(function (blob) {
  2588. successCallback(blob);
  2589. }, mimeType);
  2590. };
  2591. /**
  2592. * Encodes the canvas data to base 64 or automatically download the result if filename is defined
  2593. * @param successCallback defines the callback triggered once the data are available
  2594. * @param mimeType defines the mime type of the result
  2595. * @param fileName defines he filename to download. If present, the result will automatically be downloaded
  2596. */
  2597. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  2598. if (mimeType === void 0) { mimeType = "image/png"; }
  2599. if (successCallback) {
  2600. var base64Image = screenshotCanvas.toDataURL(mimeType);
  2601. successCallback(base64Image);
  2602. }
  2603. else {
  2604. this.ToBlob(screenshotCanvas, function (blob) {
  2605. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  2606. if (("download" in document.createElement("a"))) {
  2607. if (!fileName) {
  2608. var date = new Date();
  2609. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  2610. fileName = "screenshot_" + stringDate + ".png";
  2611. }
  2612. Tools.Download(blob, fileName);
  2613. }
  2614. else {
  2615. var url = URL.createObjectURL(blob);
  2616. var newWindow = window.open("");
  2617. if (!newWindow) {
  2618. return;
  2619. }
  2620. var img = newWindow.document.createElement("img");
  2621. img.onload = function () {
  2622. // no longer need to read the blob so it's revoked
  2623. URL.revokeObjectURL(url);
  2624. };
  2625. img.src = url;
  2626. newWindow.document.body.appendChild(img);
  2627. }
  2628. }, mimeType);
  2629. }
  2630. };
  2631. /**
  2632. * Downloads a blob in the browser
  2633. * @param blob defines the blob to download
  2634. * @param fileName defines the name of the downloaded file
  2635. */
  2636. Tools.Download = function (blob, fileName) {
  2637. if (navigator && navigator.msSaveBlob) {
  2638. navigator.msSaveBlob(blob, fileName);
  2639. return;
  2640. }
  2641. var url = window.URL.createObjectURL(blob);
  2642. var a = document.createElement("a");
  2643. document.body.appendChild(a);
  2644. a.style.display = "none";
  2645. a.href = url;
  2646. a.download = fileName;
  2647. a.addEventListener("click", function () {
  2648. if (a.parentElement) {
  2649. a.parentElement.removeChild(a);
  2650. }
  2651. });
  2652. a.click();
  2653. window.URL.revokeObjectURL(url);
  2654. };
  2655. /**
  2656. * Captures a screenshot of the current rendering
  2657. * @see http://doc.babylonjs.com/how_to/render_scene_on_a_png
  2658. * @param engine defines the rendering engine
  2659. * @param camera defines the source camera
  2660. * @param size This parameter can be set to a single number or to an object with the
  2661. * following (optional) properties: precision, width, height. If a single number is passed,
  2662. * it will be used for both width and height. If an object is passed, the screenshot size
  2663. * will be derived from the parameters. The precision property is a multiplier allowing
  2664. * rendering at a higher or lower resolution
  2665. * @param successCallback defines the callback receives a single parameter which contains the
  2666. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  2667. * src parameter of an <img> to display it
  2668. * @param mimeType defines the MIME type of the screenshot image (default: image/png).
  2669. * Check your browser for supported MIME types
  2670. */
  2671. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  2672. if (mimeType === void 0) { mimeType = "image/png"; }
  2673. var width;
  2674. var height;
  2675. // If a precision value is specified
  2676. if (size.precision) {
  2677. width = Math.round(engine.getRenderWidth() * size.precision);
  2678. height = Math.round(width / engine.getAspectRatio(camera));
  2679. }
  2680. else if (size.width && size.height) {
  2681. width = size.width;
  2682. height = size.height;
  2683. }
  2684. //If passing only width, computing height to keep display canvas ratio.
  2685. else if (size.width && !size.height) {
  2686. width = size.width;
  2687. height = Math.round(width / engine.getAspectRatio(camera));
  2688. }
  2689. //If passing only height, computing width to keep display canvas ratio.
  2690. else if (size.height && !size.width) {
  2691. height = size.height;
  2692. width = Math.round(height * engine.getAspectRatio(camera));
  2693. }
  2694. //Assuming here that "size" parameter is a number
  2695. else if (!isNaN(size)) {
  2696. height = size;
  2697. width = size;
  2698. }
  2699. else {
  2700. Tools.Error("Invalid 'size' parameter !");
  2701. return;
  2702. }
  2703. if (!screenshotCanvas) {
  2704. screenshotCanvas = document.createElement('canvas');
  2705. }
  2706. screenshotCanvas.width = width;
  2707. screenshotCanvas.height = height;
  2708. var renderContext = screenshotCanvas.getContext("2d");
  2709. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  2710. var newWidth = width;
  2711. var newHeight = newWidth / ratio;
  2712. if (newHeight > height) {
  2713. newHeight = height;
  2714. newWidth = newHeight * ratio;
  2715. }
  2716. var offsetX = Math.max(0, width - newWidth) / 2;
  2717. var offsetY = Math.max(0, height - newHeight) / 2;
  2718. var renderingCanvas = engine.getRenderingCanvas();
  2719. if (renderContext && renderingCanvas) {
  2720. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  2721. }
  2722. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  2723. };
  2724. /**
  2725. * Generates an image screenshot from the specified camera.
  2726. * @see http://doc.babylonjs.com/how_to/render_scene_on_a_png
  2727. * @param engine The engine to use for rendering
  2728. * @param camera The camera to use for rendering
  2729. * @param size This parameter can be set to a single number or to an object with the
  2730. * following (optional) properties: precision, width, height. If a single number is passed,
  2731. * it will be used for both width and height. If an object is passed, the screenshot size
  2732. * will be derived from the parameters. The precision property is a multiplier allowing
  2733. * rendering at a higher or lower resolution
  2734. * @param successCallback The callback receives a single parameter which contains the
  2735. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  2736. * src parameter of an <img> to display it
  2737. * @param mimeType The MIME type of the screenshot image (default: image/png).
  2738. * Check your browser for supported MIME types
  2739. * @param samples Texture samples (default: 1)
  2740. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  2741. * @param fileName A name for for the downloaded file.
  2742. */
  2743. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  2744. if (mimeType === void 0) { mimeType = "image/png"; }
  2745. if (samples === void 0) { samples = 1; }
  2746. if (antialiasing === void 0) { antialiasing = false; }
  2747. var width;
  2748. var height;
  2749. //If a precision value is specified
  2750. if (size.precision) {
  2751. width = Math.round(engine.getRenderWidth() * size.precision);
  2752. height = Math.round(width / engine.getAspectRatio(camera));
  2753. size = { width: width, height: height };
  2754. }
  2755. else if (size.width && size.height) {
  2756. width = size.width;
  2757. height = size.height;
  2758. }
  2759. //If passing only width, computing height to keep display canvas ratio.
  2760. else if (size.width && !size.height) {
  2761. width = size.width;
  2762. height = Math.round(width / engine.getAspectRatio(camera));
  2763. size = { width: width, height: height };
  2764. }
  2765. //If passing only height, computing width to keep display canvas ratio.
  2766. else if (size.height && !size.width) {
  2767. height = size.height;
  2768. width = Math.round(height * engine.getAspectRatio(camera));
  2769. size = { width: width, height: height };
  2770. }
  2771. //Assuming here that "size" parameter is a number
  2772. else if (!isNaN(size)) {
  2773. height = size;
  2774. width = size;
  2775. }
  2776. else {
  2777. Tools.Error("Invalid 'size' parameter !");
  2778. return;
  2779. }
  2780. var scene = camera.getScene();
  2781. var previousCamera = null;
  2782. if (scene.activeCamera !== camera) {
  2783. previousCamera = scene.activeCamera;
  2784. scene.activeCamera = camera;
  2785. }
  2786. var renderCanvas = engine.getRenderingCanvas();
  2787. if (!renderCanvas) {
  2788. Tools.Error("No rendering canvas found !");
  2789. return;
  2790. }
  2791. var originalSize = { width: renderCanvas.width, height: renderCanvas.height };
  2792. engine.setSize(width, height);
  2793. scene.render();
  2794. // At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  2795. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  2796. texture.renderList = null;
  2797. texture.samples = samples;
  2798. if (antialiasing) {
  2799. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  2800. }
  2801. texture.onAfterRenderObservable.add(function () {
  2802. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  2803. });
  2804. scene.incrementRenderId();
  2805. scene.resetCachedMaterial();
  2806. texture.render(true);
  2807. texture.dispose();
  2808. if (previousCamera) {
  2809. scene.activeCamera = previousCamera;
  2810. }
  2811. engine.setSize(originalSize.width, originalSize.height);
  2812. camera.getProjectionMatrix(true); // Force cache refresh;
  2813. };
  2814. /**
  2815. * Validates if xhr data is correct
  2816. * @param xhr defines the request to validate
  2817. * @param dataType defines the expected data type
  2818. * @returns true if data is correct
  2819. */
  2820. Tools.ValidateXHRData = function (xhr, dataType) {
  2821. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  2822. if (dataType === void 0) { dataType = 7; }
  2823. try {
  2824. if (dataType & 1) {
  2825. if (xhr.responseText && xhr.responseText.length > 0) {
  2826. return true;
  2827. }
  2828. else if (dataType === 1) {
  2829. return false;
  2830. }
  2831. }
  2832. if (dataType & 2) {
  2833. // Check header width and height since there is no "TGA" magic number
  2834. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  2835. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  2836. return true;
  2837. }
  2838. else if (dataType === 2) {
  2839. return false;
  2840. }
  2841. }
  2842. if (dataType & 4) {
  2843. // Check for the "DDS" magic number
  2844. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  2845. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  2846. return true;
  2847. }
  2848. else {
  2849. return false;
  2850. }
  2851. }
  2852. }
  2853. catch (e) {
  2854. // Global protection
  2855. }
  2856. return false;
  2857. };
  2858. /**
  2859. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  2860. * Be aware Math.random() could cause collisions, but:
  2861. * "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"
  2862. * @returns a pseudo random id
  2863. */
  2864. Tools.RandomId = function () {
  2865. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  2866. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  2867. return v.toString(16);
  2868. });
  2869. };
  2870. /**
  2871. * Test if the given uri is a base64 string
  2872. * @param uri The uri to test
  2873. * @return True if the uri is a base64 string or false otherwise
  2874. */
  2875. Tools.IsBase64 = function (uri) {
  2876. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  2877. };
  2878. /**
  2879. * Decode the given base64 uri.
  2880. * @param uri The uri to decode
  2881. * @return The decoded base64 data.
  2882. */
  2883. Tools.DecodeBase64 = function (uri) {
  2884. var decodedString = atob(uri.split(",")[1]);
  2885. var bufferLength = decodedString.length;
  2886. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  2887. for (var i = 0; i < bufferLength; i++) {
  2888. bufferView[i] = decodedString.charCodeAt(i);
  2889. }
  2890. return bufferView.buffer;
  2891. };
  2892. Tools._AddLogEntry = function (entry) {
  2893. Tools._LogCache = entry + Tools._LogCache;
  2894. if (Tools.OnNewCacheEntry) {
  2895. Tools.OnNewCacheEntry(entry);
  2896. }
  2897. };
  2898. Tools._FormatMessage = function (message) {
  2899. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  2900. var date = new Date();
  2901. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  2902. };
  2903. Tools._LogDisabled = function (message) {
  2904. // nothing to do
  2905. };
  2906. Tools._LogEnabled = function (message) {
  2907. var formattedMessage = Tools._FormatMessage(message);
  2908. console.log("BJS - " + formattedMessage);
  2909. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  2910. Tools._AddLogEntry(entry);
  2911. };
  2912. Tools._WarnDisabled = function (message) {
  2913. // nothing to do
  2914. };
  2915. Tools._WarnEnabled = function (message) {
  2916. var formattedMessage = Tools._FormatMessage(message);
  2917. console.warn("BJS - " + formattedMessage);
  2918. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  2919. Tools._AddLogEntry(entry);
  2920. };
  2921. Tools._ErrorDisabled = function (message) {
  2922. // nothing to do
  2923. };
  2924. Tools._ErrorEnabled = function (message) {
  2925. Tools.errorsCount++;
  2926. var formattedMessage = Tools._FormatMessage(message);
  2927. console.error("BJS - " + formattedMessage);
  2928. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  2929. Tools._AddLogEntry(entry);
  2930. };
  2931. Object.defineProperty(Tools, "LogCache", {
  2932. /**
  2933. * Gets current log cache (list of logs)
  2934. */
  2935. get: function () {
  2936. return Tools._LogCache;
  2937. },
  2938. enumerable: true,
  2939. configurable: true
  2940. });
  2941. /**
  2942. * Clears the log cache
  2943. */
  2944. Tools.ClearLogCache = function () {
  2945. Tools._LogCache = "";
  2946. Tools.errorsCount = 0;
  2947. };
  2948. Object.defineProperty(Tools, "LogLevels", {
  2949. /**
  2950. * Sets the current log level (MessageLogLevel / WarningLogLevel / ErrorLogLevel)
  2951. */
  2952. set: function (level) {
  2953. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  2954. Tools.Log = Tools._LogEnabled;
  2955. }
  2956. else {
  2957. Tools.Log = Tools._LogDisabled;
  2958. }
  2959. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  2960. Tools.Warn = Tools._WarnEnabled;
  2961. }
  2962. else {
  2963. Tools.Warn = Tools._WarnDisabled;
  2964. }
  2965. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  2966. Tools.Error = Tools._ErrorEnabled;
  2967. }
  2968. else {
  2969. Tools.Error = Tools._ErrorDisabled;
  2970. }
  2971. },
  2972. enumerable: true,
  2973. configurable: true
  2974. });
  2975. /**
  2976. * Checks if the loaded document was accessed via `file:`-Protocol.
  2977. * @returns boolean
  2978. */
  2979. Tools.IsFileURL = function () {
  2980. return location.protocol === "file:";
  2981. };
  2982. /**
  2983. * Checks if the window object exists
  2984. * @returns true if the window object exists
  2985. */
  2986. Tools.IsWindowObjectExist = function () {
  2987. return (typeof window) !== "undefined";
  2988. };
  2989. Object.defineProperty(Tools, "PerformanceLogLevel", {
  2990. /**
  2991. * Sets the current performance log level
  2992. */
  2993. set: function (level) {
  2994. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  2995. Tools.StartPerformanceCounter = Tools._StartUserMark;
  2996. Tools.EndPerformanceCounter = Tools._EndUserMark;
  2997. return;
  2998. }
  2999. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  3000. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  3001. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  3002. return;
  3003. }
  3004. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  3005. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  3006. },
  3007. enumerable: true,
  3008. configurable: true
  3009. });
  3010. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  3011. };
  3012. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  3013. };
  3014. Tools._StartUserMark = function (counterName, condition) {
  3015. if (condition === void 0) { condition = true; }
  3016. if (!Tools._performance) {
  3017. if (!Tools.IsWindowObjectExist()) {
  3018. return;
  3019. }
  3020. Tools._performance = window.performance;
  3021. }
  3022. if (!condition || !Tools._performance.mark) {
  3023. return;
  3024. }
  3025. Tools._performance.mark(counterName + "-Begin");
  3026. };
  3027. Tools._EndUserMark = function (counterName, condition) {
  3028. if (condition === void 0) { condition = true; }
  3029. if (!condition || !Tools._performance.mark) {
  3030. return;
  3031. }
  3032. Tools._performance.mark(counterName + "-End");
  3033. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  3034. };
  3035. Tools._StartPerformanceConsole = function (counterName, condition) {
  3036. if (condition === void 0) { condition = true; }
  3037. if (!condition) {
  3038. return;
  3039. }
  3040. Tools._StartUserMark(counterName, condition);
  3041. if (console.time) {
  3042. console.time(counterName);
  3043. }
  3044. };
  3045. Tools._EndPerformanceConsole = function (counterName, condition) {
  3046. if (condition === void 0) { condition = true; }
  3047. if (!condition) {
  3048. return;
  3049. }
  3050. Tools._EndUserMark(counterName, condition);
  3051. if (console.time) {
  3052. console.timeEnd(counterName);
  3053. }
  3054. };
  3055. /**
  3056. * Injects the @see CustomRequestHeaders into the given request
  3057. * @param request the request that should be used for injection
  3058. */
  3059. Tools.InjectCustomRequestHeaders = function (request) {
  3060. for (var key in Tools.CustomRequestHeaders) {
  3061. var val = Tools.CustomRequestHeaders[key];
  3062. if (val) {
  3063. request.setRequestHeader(key, val);
  3064. }
  3065. }
  3066. };
  3067. Object.defineProperty(Tools, "Now", {
  3068. /**
  3069. * Gets either window.performance.now() if supported or Date.now() else
  3070. */
  3071. get: function () {
  3072. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  3073. return window.performance.now();
  3074. }
  3075. return Date.now();
  3076. },
  3077. enumerable: true,
  3078. configurable: true
  3079. });
  3080. /**
  3081. * This method will return the name of the class used to create the instance of the given object.
  3082. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  3083. * @param object the object to get the class name from
  3084. * @param isType defines if the object is actually a type
  3085. * @returns the name of the class, will be "object" for a custom data type not using the @className decorator
  3086. */
  3087. Tools.GetClassName = function (object, isType) {
  3088. if (isType === void 0) { isType = false; }
  3089. var name = null;
  3090. if (!isType && object.getClassName) {
  3091. name = object.getClassName();
  3092. }
  3093. else {
  3094. if (object instanceof Object) {
  3095. var classObj = isType ? object : Object.getPrototypeOf(object);
  3096. name = classObj.constructor["__bjsclassName__"];
  3097. }
  3098. if (!name) {
  3099. name = typeof object;
  3100. }
  3101. }
  3102. return name;
  3103. };
  3104. /**
  3105. * Gets the first element of an array satisfying a given predicate
  3106. * @param array defines the array to browse
  3107. * @param predicate defines the predicate to use
  3108. * @returns null if not found or the element
  3109. */
  3110. Tools.First = function (array, predicate) {
  3111. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  3112. var el = array_1[_i];
  3113. if (predicate(el)) {
  3114. return el;
  3115. }
  3116. }
  3117. return null;
  3118. };
  3119. /**
  3120. * This method will return the name of the full name of the class, including its owning module (if any).
  3121. * 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).
  3122. * @param object the object to get the class name from
  3123. * @param isType defines if the object is actually a type
  3124. * @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.
  3125. * @ignorenaming
  3126. */
  3127. Tools.getFullClassName = function (object, isType) {
  3128. if (isType === void 0) { isType = false; }
  3129. var className = null;
  3130. var moduleName = null;
  3131. if (!isType && object.getClassName) {
  3132. className = object.getClassName();
  3133. }
  3134. else {
  3135. if (object instanceof Object) {
  3136. var classObj = isType ? object : Object.getPrototypeOf(object);
  3137. className = classObj.constructor["__bjsclassName__"];
  3138. moduleName = classObj.constructor["__bjsmoduleName__"];
  3139. }
  3140. if (!className) {
  3141. className = typeof object;
  3142. }
  3143. }
  3144. if (!className) {
  3145. return null;
  3146. }
  3147. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  3148. };
  3149. /**
  3150. * Returns a promise that resolves after the given amount of time.
  3151. * @param delay Number of milliseconds to delay
  3152. * @returns Promise that resolves after the given amount of time
  3153. */
  3154. Tools.DelayAsync = function (delay) {
  3155. return new Promise(function (resolve) {
  3156. setTimeout(function () {
  3157. resolve();
  3158. }, delay);
  3159. });
  3160. };
  3161. /**
  3162. * Gets the current gradient from an array of IValueGradient
  3163. * @param ratio defines the current ratio to get
  3164. * @param gradients defines the array of IValueGradient
  3165. * @param updateFunc defines the callback function used to get the final value from the selected gradients
  3166. */
  3167. Tools.GetCurrentGradient = function (ratio, gradients, updateFunc) {
  3168. for (var gradientIndex = 0; gradientIndex < gradients.length - 1; gradientIndex++) {
  3169. var currentGradient = gradients[gradientIndex];
  3170. var nextGradient = gradients[gradientIndex + 1];
  3171. if (ratio >= currentGradient.gradient && ratio <= nextGradient.gradient) {
  3172. var scale = (ratio - currentGradient.gradient) / (nextGradient.gradient - currentGradient.gradient);
  3173. updateFunc(currentGradient, nextGradient, scale);
  3174. return;
  3175. }
  3176. }
  3177. // Use last index if over
  3178. var lastIndex = gradients.length - 1;
  3179. updateFunc(gradients[lastIndex], gradients[lastIndex], 1.0);
  3180. };
  3181. /**
  3182. * Gets or sets the base URL to use to load assets
  3183. */
  3184. Tools.BaseUrl = "";
  3185. /**
  3186. * Enable/Disable Custom HTTP Request Headers globally.
  3187. * default = false
  3188. * @see CustomRequestHeaders
  3189. */
  3190. Tools.UseCustomRequestHeaders = false;
  3191. /**
  3192. * Custom HTTP Request Headers to be sent with XMLHttpRequests
  3193. * i.e. when loading files, where the server/service expects an Authorization header.
  3194. * @see InjectCustomRequestHeaders injects them to an XMLHttpRequest
  3195. */
  3196. Tools.CustomRequestHeaders = {};
  3197. /**
  3198. * Gets or sets the retry strategy to apply when an error happens while loading an asset
  3199. */
  3200. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  3201. /**
  3202. * Default behaviour for cors in the application.
  3203. * It can be a string if the expected behavior is identical in the entire app.
  3204. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  3205. */
  3206. Tools.CorsBehavior = "anonymous";
  3207. /**
  3208. * Gets or sets a global variable indicating if fallback texture must be used when a texture cannot be loaded
  3209. * @ignorenaming
  3210. */
  3211. Tools.UseFallbackTexture = true;
  3212. /**
  3213. * Use this object to register external classes like custom textures or material
  3214. * to allow the laoders to instantiate them
  3215. */
  3216. Tools.RegisteredExternalClasses = {};
  3217. /**
  3218. * Texture content used if a texture cannot loaded
  3219. * @ignorenaming
  3220. */
  3221. 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";
  3222. Tools._tmpFloatArray = new Float32Array(1);
  3223. /**
  3224. * Gets or sets a function used to pre-process url before using them to load assets
  3225. */
  3226. Tools.PreprocessUrl = function (url) {
  3227. return url;
  3228. };
  3229. // Logs
  3230. /**
  3231. * No log
  3232. */
  3233. Tools.NoneLogLevel = 0;
  3234. /**
  3235. * Only message logs
  3236. */
  3237. Tools.MessageLogLevel = 1;
  3238. /**
  3239. * Only warning logs
  3240. */
  3241. Tools.WarningLogLevel = 2;
  3242. /**
  3243. * Only error logs
  3244. */
  3245. Tools.ErrorLogLevel = 4;
  3246. /**
  3247. * All logs
  3248. */
  3249. Tools.AllLogLevel = 7;
  3250. Tools._LogCache = "";
  3251. /**
  3252. * Gets a value indicating the number of loading errors
  3253. * @ignorenaming
  3254. */
  3255. Tools.errorsCount = 0;
  3256. /**
  3257. * Log a message to the console
  3258. */
  3259. Tools.Log = Tools._LogEnabled;
  3260. /**
  3261. * Write a warning message to the console
  3262. */
  3263. Tools.Warn = Tools._WarnEnabled;
  3264. /**
  3265. * Write an error message to the console
  3266. */
  3267. Tools.Error = Tools._ErrorEnabled;
  3268. // Performances
  3269. /**
  3270. * No performance log
  3271. */
  3272. Tools.PerformanceNoneLogLevel = 0;
  3273. /**
  3274. * Use user marks to log performance
  3275. */
  3276. Tools.PerformanceUserMarkLogLevel = 1;
  3277. /**
  3278. * Log performance to the console
  3279. */
  3280. Tools.PerformanceConsoleLogLevel = 2;
  3281. /**
  3282. * Starts a performance counter
  3283. */
  3284. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  3285. /**
  3286. * Ends a specific performance coutner
  3287. */
  3288. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  3289. return Tools;
  3290. }());
  3291. BABYLON.Tools = Tools;
  3292. /**
  3293. * This class is used to track a performance counter which is number based.
  3294. * The user has access to many properties which give statistics of different nature.
  3295. *
  3296. * The implementer can track two kinds of Performance Counter: time and count.
  3297. * 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.
  3298. * 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.
  3299. */
  3300. var PerfCounter = /** @class */ (function () {
  3301. /**
  3302. * Creates a new counter
  3303. */
  3304. function PerfCounter() {
  3305. this._startMonitoringTime = 0;
  3306. this._min = 0;
  3307. this._max = 0;
  3308. this._average = 0;
  3309. this._lastSecAverage = 0;
  3310. this._current = 0;
  3311. this._totalValueCount = 0;
  3312. this._totalAccumulated = 0;
  3313. this._lastSecAccumulated = 0;
  3314. this._lastSecTime = 0;
  3315. this._lastSecValueCount = 0;
  3316. }
  3317. Object.defineProperty(PerfCounter.prototype, "min", {
  3318. /**
  3319. * Returns the smallest value ever
  3320. */
  3321. get: function () {
  3322. return this._min;
  3323. },
  3324. enumerable: true,
  3325. configurable: true
  3326. });
  3327. Object.defineProperty(PerfCounter.prototype, "max", {
  3328. /**
  3329. * Returns the biggest value ever
  3330. */
  3331. get: function () {
  3332. return this._max;
  3333. },
  3334. enumerable: true,
  3335. configurable: true
  3336. });
  3337. Object.defineProperty(PerfCounter.prototype, "average", {
  3338. /**
  3339. * Returns the average value since the performance counter is running
  3340. */
  3341. get: function () {
  3342. return this._average;
  3343. },
  3344. enumerable: true,
  3345. configurable: true
  3346. });
  3347. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  3348. /**
  3349. * Returns the average value of the last second the counter was monitored
  3350. */
  3351. get: function () {
  3352. return this._lastSecAverage;
  3353. },
  3354. enumerable: true,
  3355. configurable: true
  3356. });
  3357. Object.defineProperty(PerfCounter.prototype, "current", {
  3358. /**
  3359. * Returns the current value
  3360. */
  3361. get: function () {
  3362. return this._current;
  3363. },
  3364. enumerable: true,
  3365. configurable: true
  3366. });
  3367. Object.defineProperty(PerfCounter.prototype, "total", {
  3368. /**
  3369. * Gets the accumulated total
  3370. */
  3371. get: function () {
  3372. return this._totalAccumulated;
  3373. },
  3374. enumerable: true,
  3375. configurable: true
  3376. });
  3377. Object.defineProperty(PerfCounter.prototype, "count", {
  3378. /**
  3379. * Gets the total value count
  3380. */
  3381. get: function () {
  3382. return this._totalValueCount;
  3383. },
  3384. enumerable: true,
  3385. configurable: true
  3386. });
  3387. /**
  3388. * Call this method to start monitoring a new frame.
  3389. * 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.
  3390. */
  3391. PerfCounter.prototype.fetchNewFrame = function () {
  3392. this._totalValueCount++;
  3393. this._current = 0;
  3394. this._lastSecValueCount++;
  3395. };
  3396. /**
  3397. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  3398. * @param newCount the count value to add to the monitored count
  3399. * @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.
  3400. */
  3401. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  3402. if (!PerfCounter.Enabled) {
  3403. return;
  3404. }
  3405. this._current += newCount;
  3406. if (fetchResult) {
  3407. this._fetchResult();
  3408. }
  3409. };
  3410. /**
  3411. * Start monitoring this performance counter
  3412. */
  3413. PerfCounter.prototype.beginMonitoring = function () {
  3414. if (!PerfCounter.Enabled) {
  3415. return;
  3416. }
  3417. this._startMonitoringTime = Tools.Now;
  3418. };
  3419. /**
  3420. * Compute the time lapsed since the previous beginMonitoring() call.
  3421. * @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
  3422. */
  3423. PerfCounter.prototype.endMonitoring = function (newFrame) {
  3424. if (newFrame === void 0) { newFrame = true; }
  3425. if (!PerfCounter.Enabled) {
  3426. return;
  3427. }
  3428. if (newFrame) {
  3429. this.fetchNewFrame();
  3430. }
  3431. var currentTime = Tools.Now;
  3432. this._current = currentTime - this._startMonitoringTime;
  3433. if (newFrame) {
  3434. this._fetchResult();
  3435. }
  3436. };
  3437. PerfCounter.prototype._fetchResult = function () {
  3438. this._totalAccumulated += this._current;
  3439. this._lastSecAccumulated += this._current;
  3440. // Min/Max update
  3441. this._min = Math.min(this._min, this._current);
  3442. this._max = Math.max(this._max, this._current);
  3443. this._average = this._totalAccumulated / this._totalValueCount;
  3444. // Reset last sec?
  3445. var now = Tools.Now;
  3446. if ((now - this._lastSecTime) > 1000) {
  3447. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  3448. this._lastSecTime = now;
  3449. this._lastSecAccumulated = 0;
  3450. this._lastSecValueCount = 0;
  3451. }
  3452. };
  3453. /**
  3454. * Gets or sets a global boolean to turn on and off all the counters
  3455. */
  3456. PerfCounter.Enabled = true;
  3457. return PerfCounter;
  3458. }());
  3459. BABYLON.PerfCounter = PerfCounter;
  3460. /**
  3461. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  3462. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  3463. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  3464. * @param name The name of the class, case should be preserved
  3465. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  3466. */
  3467. function className(name, module) {
  3468. return function (target) {
  3469. target["__bjsclassName__"] = name;
  3470. target["__bjsmoduleName__"] = (module != null) ? module : null;
  3471. };
  3472. }
  3473. BABYLON.className = className;
  3474. /**
  3475. * An implementation of a loop for asynchronous functions.
  3476. */
  3477. var AsyncLoop = /** @class */ (function () {
  3478. /**
  3479. * Constructor.
  3480. * @param iterations the number of iterations.
  3481. * @param func the function to run each iteration
  3482. * @param successCallback the callback that will be called upon succesful execution
  3483. * @param offset starting offset.
  3484. */
  3485. function AsyncLoop(
  3486. /**
  3487. * Defines the number of iterations for the loop
  3488. */
  3489. iterations, func, successCallback, offset) {
  3490. if (offset === void 0) { offset = 0; }
  3491. this.iterations = iterations;
  3492. this.index = offset - 1;
  3493. this._done = false;
  3494. this._fn = func;
  3495. this._successCallback = successCallback;
  3496. }
  3497. /**
  3498. * Execute the next iteration. Must be called after the last iteration was finished.
  3499. */
  3500. AsyncLoop.prototype.executeNext = function () {
  3501. if (!this._done) {
  3502. if (this.index + 1 < this.iterations) {
  3503. ++this.index;
  3504. this._fn(this);
  3505. }
  3506. else {
  3507. this.breakLoop();
  3508. }
  3509. }
  3510. };
  3511. /**
  3512. * Break the loop and run the success callback.
  3513. */
  3514. AsyncLoop.prototype.breakLoop = function () {
  3515. this._done = true;
  3516. this._successCallback();
  3517. };
  3518. /**
  3519. * Create and run an async loop.
  3520. * @param iterations the number of iterations.
  3521. * @param fn the function to run each iteration
  3522. * @param successCallback the callback that will be called upon succesful execution
  3523. * @param offset starting offset.
  3524. * @returns the created async loop object
  3525. */
  3526. AsyncLoop.Run = function (iterations, fn, successCallback, offset) {
  3527. if (offset === void 0) { offset = 0; }
  3528. var loop = new AsyncLoop(iterations, fn, successCallback, offset);
  3529. loop.executeNext();
  3530. return loop;
  3531. };
  3532. /**
  3533. * A for-loop that will run a given number of iterations synchronous and the rest async.
  3534. * @param iterations total number of iterations
  3535. * @param syncedIterations number of synchronous iterations in each async iteration.
  3536. * @param fn the function to call each iteration.
  3537. * @param callback a success call back that will be called when iterating stops.
  3538. * @param breakFunction a break condition (optional)
  3539. * @param timeout timeout settings for the setTimeout function. default - 0.
  3540. * @returns the created async loop object
  3541. */
  3542. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  3543. if (timeout === void 0) { timeout = 0; }
  3544. return AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  3545. if (breakFunction && breakFunction()) {
  3546. loop.breakLoop();
  3547. }
  3548. else {
  3549. setTimeout(function () {
  3550. for (var i = 0; i < syncedIterations; ++i) {
  3551. var iteration = (loop.index * syncedIterations) + i;
  3552. if (iteration >= iterations) {
  3553. break;
  3554. }
  3555. fn(iteration);
  3556. if (breakFunction && breakFunction()) {
  3557. loop.breakLoop();
  3558. break;
  3559. }
  3560. }
  3561. loop.executeNext();
  3562. }, timeout);
  3563. }
  3564. }, callback);
  3565. };
  3566. return AsyncLoop;
  3567. }());
  3568. BABYLON.AsyncLoop = AsyncLoop;
  3569. })(BABYLON || (BABYLON = {}));
  3570. //# sourceMappingURL=babylon.tools.js.map
  3571. var BABYLON;
  3572. (function (BABYLON) {
  3573. /**
  3574. * Constant used to convert a value to gamma space
  3575. * @ignorenaming
  3576. */
  3577. BABYLON.ToGammaSpace = 1 / 2.2;
  3578. /**
  3579. * Constant used to convert a value to linear space
  3580. * @ignorenaming
  3581. */
  3582. BABYLON.ToLinearSpace = 2.2;
  3583. /**
  3584. * Constant used to define the minimal number value in Babylon.js
  3585. * @ignorenaming
  3586. */
  3587. BABYLON.Epsilon = 0.001;
  3588. /**
  3589. * Class used to hold a RBG color
  3590. */
  3591. var Color3 = /** @class */ (function () {
  3592. /**
  3593. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  3594. * @param r defines the red component (between 0 and 1, default is 0)
  3595. * @param g defines the green component (between 0 and 1, default is 0)
  3596. * @param b defines the blue component (between 0 and 1, default is 0)
  3597. */
  3598. function Color3(
  3599. /**
  3600. * Defines the red component (between 0 and 1, default is 0)
  3601. */
  3602. r,
  3603. /**
  3604. * Defines the green component (between 0 and 1, default is 0)
  3605. */
  3606. g,
  3607. /**
  3608. * Defines the blue component (between 0 and 1, default is 0)
  3609. */
  3610. b) {
  3611. if (r === void 0) { r = 0; }
  3612. if (g === void 0) { g = 0; }
  3613. if (b === void 0) { b = 0; }
  3614. this.r = r;
  3615. this.g = g;
  3616. this.b = b;
  3617. }
  3618. /**
  3619. * Creates a string with the Color3 current values
  3620. * @returns the string representation of the Color3 object
  3621. */
  3622. Color3.prototype.toString = function () {
  3623. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  3624. };
  3625. /**
  3626. * Returns the string "Color3"
  3627. * @returns "Color3"
  3628. */
  3629. Color3.prototype.getClassName = function () {
  3630. return "Color3";
  3631. };
  3632. /**
  3633. * Compute the Color3 hash code
  3634. * @returns an unique number that can be used to hash Color3 objects
  3635. */
  3636. Color3.prototype.getHashCode = function () {
  3637. var hash = this.r || 0;
  3638. hash = (hash * 397) ^ (this.g || 0);
  3639. hash = (hash * 397) ^ (this.b || 0);
  3640. return hash;
  3641. };
  3642. // Operators
  3643. /**
  3644. * Stores in the given array from the given starting index the red, green, blue values as successive elements
  3645. * @param array defines the array where to store the r,g,b components
  3646. * @param index defines an optional index in the target array to define where to start storing values
  3647. * @returns the current Color3 object
  3648. */
  3649. Color3.prototype.toArray = function (array, index) {
  3650. if (index === void 0) { index = 0; }
  3651. array[index] = this.r;
  3652. array[index + 1] = this.g;
  3653. array[index + 2] = this.b;
  3654. return this;
  3655. };
  3656. /**
  3657. * Returns a new Color4 object from the current Color3 and the given alpha
  3658. * @param alpha defines the alpha component on the new Color4 object (default is 1)
  3659. * @returns a new Color4 object
  3660. */
  3661. Color3.prototype.toColor4 = function (alpha) {
  3662. if (alpha === void 0) { alpha = 1; }
  3663. return new Color4(this.r, this.g, this.b, alpha);
  3664. };
  3665. /**
  3666. * Returns a new array populated with 3 numeric elements : red, green and blue values
  3667. * @returns the new array
  3668. */
  3669. Color3.prototype.asArray = function () {
  3670. var result = new Array();
  3671. this.toArray(result, 0);
  3672. return result;
  3673. };
  3674. /**
  3675. * Returns the luminance value
  3676. * @returns a float value
  3677. */
  3678. Color3.prototype.toLuminance = function () {
  3679. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  3680. };
  3681. /**
  3682. * Multiply each Color3 rgb values by the given Color3 rgb values in a new Color3 object
  3683. * @param otherColor defines the second operand
  3684. * @returns the new Color3 object
  3685. */
  3686. Color3.prototype.multiply = function (otherColor) {
  3687. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  3688. };
  3689. /**
  3690. * Multiply the rgb values of the Color3 and the given Color3 and stores the result in the object "result"
  3691. * @param otherColor defines the second operand
  3692. * @param result defines the Color3 object where to store the result
  3693. * @returns the current Color3
  3694. */
  3695. Color3.prototype.multiplyToRef = function (otherColor, result) {
  3696. result.r = this.r * otherColor.r;
  3697. result.g = this.g * otherColor.g;
  3698. result.b = this.b * otherColor.b;
  3699. return this;
  3700. };
  3701. /**
  3702. * Determines equality between Color3 objects
  3703. * @param otherColor defines the second operand
  3704. * @returns true if the rgb values are equal to the given ones
  3705. */
  3706. Color3.prototype.equals = function (otherColor) {
  3707. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  3708. };
  3709. /**
  3710. * Determines equality between the current Color3 object and a set of r,b,g values
  3711. * @param r defines the red component to check
  3712. * @param g defines the green component to check
  3713. * @param b defines the blue component to check
  3714. * @returns true if the rgb values are equal to the given ones
  3715. */
  3716. Color3.prototype.equalsFloats = function (r, g, b) {
  3717. return this.r === r && this.g === g && this.b === b;
  3718. };
  3719. /**
  3720. * Multiplies in place each rgb value by scale
  3721. * @param scale defines the scaling factor
  3722. * @returns the updated Color3
  3723. */
  3724. Color3.prototype.scale = function (scale) {
  3725. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  3726. };
  3727. /**
  3728. * Multiplies the rgb values by scale and stores the result into "result"
  3729. * @param scale defines the scaling factor
  3730. * @param result defines the Color3 object where to store the result
  3731. * @returns the unmodified current Color3
  3732. */
  3733. Color3.prototype.scaleToRef = function (scale, result) {
  3734. result.r = this.r * scale;
  3735. result.g = this.g * scale;
  3736. result.b = this.b * scale;
  3737. return this;
  3738. };
  3739. /**
  3740. * Scale the current Color3 values by a factor and add the result to a given Color3
  3741. * @param scale defines the scale factor
  3742. * @param result defines color to store the result into
  3743. * @returns the unmodified current Color3
  3744. */
  3745. Color3.prototype.scaleAndAddToRef = function (scale, result) {
  3746. result.r += this.r * scale;
  3747. result.g += this.g * scale;
  3748. result.b += this.b * scale;
  3749. return this;
  3750. };
  3751. /**
  3752. * Clamps the rgb values by the min and max values and stores the result into "result"
  3753. * @param min defines minimum clamping value (default is 0)
  3754. * @param max defines maximum clamping value (default is 1)
  3755. * @param result defines color to store the result into
  3756. * @returns the original Color3
  3757. */
  3758. Color3.prototype.clampToRef = function (min, max, result) {
  3759. if (min === void 0) { min = 0; }
  3760. if (max === void 0) { max = 1; }
  3761. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  3762. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  3763. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  3764. return this;
  3765. };
  3766. /**
  3767. * Creates a new Color3 set with the added values of the current Color3 and of the given one
  3768. * @param otherColor defines the second operand
  3769. * @returns the new Color3
  3770. */
  3771. Color3.prototype.add = function (otherColor) {
  3772. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  3773. };
  3774. /**
  3775. * Stores the result of the addition of the current Color3 and given one rgb values into "result"
  3776. * @param otherColor defines the second operand
  3777. * @param result defines Color3 object to store the result into
  3778. * @returns the unmodified current Color3
  3779. */
  3780. Color3.prototype.addToRef = function (otherColor, result) {
  3781. result.r = this.r + otherColor.r;
  3782. result.g = this.g + otherColor.g;
  3783. result.b = this.b + otherColor.b;
  3784. return this;
  3785. };
  3786. /**
  3787. * Returns a new Color3 set with the subtracted values of the given one from the current Color3
  3788. * @param otherColor defines the second operand
  3789. * @returns the new Color3
  3790. */
  3791. Color3.prototype.subtract = function (otherColor) {
  3792. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  3793. };
  3794. /**
  3795. * Stores the result of the subtraction of given one from the current Color3 rgb values into "result"
  3796. * @param otherColor defines the second operand
  3797. * @param result defines Color3 object to store the result into
  3798. * @returns the unmodified current Color3
  3799. */
  3800. Color3.prototype.subtractToRef = function (otherColor, result) {
  3801. result.r = this.r - otherColor.r;
  3802. result.g = this.g - otherColor.g;
  3803. result.b = this.b - otherColor.b;
  3804. return this;
  3805. };
  3806. /**
  3807. * Copy the current object
  3808. * @returns a new Color3 copied the current one
  3809. */
  3810. Color3.prototype.clone = function () {
  3811. return new Color3(this.r, this.g, this.b);
  3812. };
  3813. /**
  3814. * Copies the rgb values from the source in the current Color3
  3815. * @param source defines the source Color3 object
  3816. * @returns the updated Color3 object
  3817. */
  3818. Color3.prototype.copyFrom = function (source) {
  3819. this.r = source.r;
  3820. this.g = source.g;
  3821. this.b = source.b;
  3822. return this;
  3823. };
  3824. /**
  3825. * Updates the Color3 rgb values from the given floats
  3826. * @param r defines the red component to read from
  3827. * @param g defines the green component to read from
  3828. * @param b defines the blue component to read from
  3829. * @returns the current Color3 object
  3830. */
  3831. Color3.prototype.copyFromFloats = function (r, g, b) {
  3832. this.r = r;
  3833. this.g = g;
  3834. this.b = b;
  3835. return this;
  3836. };
  3837. /**
  3838. * Updates the Color3 rgb values from the given floats
  3839. * @param r defines the red component to read from
  3840. * @param g defines the green component to read from
  3841. * @param b defines the blue component to read from
  3842. * @returns the current Color3 object
  3843. */
  3844. Color3.prototype.set = function (r, g, b) {
  3845. return this.copyFromFloats(r, g, b);
  3846. };
  3847. /**
  3848. * Compute the Color3 hexadecimal code as a string
  3849. * @returns a string containing the hexadecimal representation of the Color3 object
  3850. */
  3851. Color3.prototype.toHexString = function () {
  3852. var intR = (this.r * 255) | 0;
  3853. var intG = (this.g * 255) | 0;
  3854. var intB = (this.b * 255) | 0;
  3855. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  3856. };
  3857. /**
  3858. * Computes a new Color3 converted from the current one to linear space
  3859. * @returns a new Color3 object
  3860. */
  3861. Color3.prototype.toLinearSpace = function () {
  3862. var convertedColor = new Color3();
  3863. this.toLinearSpaceToRef(convertedColor);
  3864. return convertedColor;
  3865. };
  3866. /**
  3867. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  3868. * @param convertedColor defines the Color3 object where to store the linear space version
  3869. * @returns the unmodified Color3
  3870. */
  3871. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  3872. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  3873. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  3874. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  3875. return this;
  3876. };
  3877. /**
  3878. * Computes a new Color3 converted from the current one to gamma space
  3879. * @returns a new Color3 object
  3880. */
  3881. Color3.prototype.toGammaSpace = function () {
  3882. var convertedColor = new Color3();
  3883. this.toGammaSpaceToRef(convertedColor);
  3884. return convertedColor;
  3885. };
  3886. /**
  3887. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  3888. * @param convertedColor defines the Color3 object where to store the gamma space version
  3889. * @returns the unmodified Color3
  3890. */
  3891. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  3892. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  3893. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  3894. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  3895. return this;
  3896. };
  3897. /**
  3898. * Creates a new Color3 from the string containing valid hexadecimal values
  3899. * @param hex defines a string containing valid hexadecimal values
  3900. * @returns a new Color3 object
  3901. */
  3902. Color3.FromHexString = function (hex) {
  3903. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  3904. return new Color3(0, 0, 0);
  3905. }
  3906. var r = parseInt(hex.substring(1, 3), 16);
  3907. var g = parseInt(hex.substring(3, 5), 16);
  3908. var b = parseInt(hex.substring(5, 7), 16);
  3909. return Color3.FromInts(r, g, b);
  3910. };
  3911. /**
  3912. * Creates a new Vector3 from the starting index of the given array
  3913. * @param array defines the source array
  3914. * @param offset defines an offset in the source array
  3915. * @returns a new Color3 object
  3916. */
  3917. Color3.FromArray = function (array, offset) {
  3918. if (offset === void 0) { offset = 0; }
  3919. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  3920. };
  3921. /**
  3922. * Creates a new Color3 from integer values (< 256)
  3923. * @param r defines the red component to read from (value between 0 and 255)
  3924. * @param g defines the green component to read from (value between 0 and 255)
  3925. * @param b defines the blue component to read from (value between 0 and 255)
  3926. * @returns a new Color3 object
  3927. */
  3928. Color3.FromInts = function (r, g, b) {
  3929. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  3930. };
  3931. /**
  3932. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  3933. * @param start defines the start Color3 value
  3934. * @param end defines the end Color3 value
  3935. * @param amount defines the gradient value between start and end
  3936. * @returns a new Color3 object
  3937. */
  3938. Color3.Lerp = function (start, end, amount) {
  3939. var result = new Color3(0.0, 0.0, 0.0);
  3940. Color3.LerpToRef(start, end, amount, result);
  3941. return result;
  3942. };
  3943. /**
  3944. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  3945. * @param left defines the start value
  3946. * @param right defines the end value
  3947. * @param amount defines the gradient factor
  3948. * @param result defines the Color3 object where to store the result
  3949. */
  3950. Color3.LerpToRef = function (left, right, amount, result) {
  3951. result.r = left.r + ((right.r - left.r) * amount);
  3952. result.g = left.g + ((right.g - left.g) * amount);
  3953. result.b = left.b + ((right.b - left.b) * amount);
  3954. };
  3955. /**
  3956. * Returns a Color3 value containing a red color
  3957. * @returns a new Color3 object
  3958. */
  3959. Color3.Red = function () { return new Color3(1, 0, 0); };
  3960. /**
  3961. * Returns a Color3 value containing a green color
  3962. * @returns a new Color3 object
  3963. */
  3964. Color3.Green = function () { return new Color3(0, 1, 0); };
  3965. /**
  3966. * Returns a Color3 value containing a blue color
  3967. * @returns a new Color3 object
  3968. */
  3969. Color3.Blue = function () { return new Color3(0, 0, 1); };
  3970. /**
  3971. * Returns a Color3 value containing a black color
  3972. * @returns a new Color3 object
  3973. */
  3974. Color3.Black = function () { return new Color3(0, 0, 0); };
  3975. Object.defineProperty(Color3, "BlackReadOnly", {
  3976. /**
  3977. * Gets a Color3 value containing a black color that must not be updated
  3978. */
  3979. get: function () {
  3980. return Color3._BlackReadOnly;
  3981. },
  3982. enumerable: true,
  3983. configurable: true
  3984. });
  3985. /**
  3986. * Returns a Color3 value containing a white color
  3987. * @returns a new Color3 object
  3988. */
  3989. Color3.White = function () { return new Color3(1, 1, 1); };
  3990. /**
  3991. * Returns a Color3 value containing a purple color
  3992. * @returns a new Color3 object
  3993. */
  3994. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  3995. /**
  3996. * Returns a Color3 value containing a magenta color
  3997. * @returns a new Color3 object
  3998. */
  3999. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  4000. /**
  4001. * Returns a Color3 value containing a yellow color
  4002. * @returns a new Color3 object
  4003. */
  4004. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  4005. /**
  4006. * Returns a Color3 value containing a gray color
  4007. * @returns a new Color3 object
  4008. */
  4009. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  4010. /**
  4011. * Returns a Color3 value containing a teal color
  4012. * @returns a new Color3 object
  4013. */
  4014. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  4015. /**
  4016. * Returns a Color3 value containing a random color
  4017. * @returns a new Color3 object
  4018. */
  4019. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  4020. // Statics
  4021. Color3._BlackReadOnly = Color3.Black();
  4022. return Color3;
  4023. }());
  4024. BABYLON.Color3 = Color3;
  4025. /**
  4026. * Class used to hold a RBGA color
  4027. */
  4028. var Color4 = /** @class */ (function () {
  4029. /**
  4030. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  4031. * @param r defines the red component (between 0 and 1, default is 0)
  4032. * @param g defines the green component (between 0 and 1, default is 0)
  4033. * @param b defines the blue component (between 0 and 1, default is 0)
  4034. * @param a defines the alpha component (between 0 and 1, default is 1)
  4035. */
  4036. function Color4(
  4037. /**
  4038. * Defines the red component (between 0 and 1, default is 0)
  4039. */
  4040. r,
  4041. /**
  4042. * Defines the green component (between 0 and 1, default is 0)
  4043. */
  4044. g,
  4045. /**
  4046. * Defines the blue component (between 0 and 1, default is 0)
  4047. */
  4048. b,
  4049. /**
  4050. * Defines the alpha component (between 0 and 1, default is 1)
  4051. */
  4052. a) {
  4053. if (r === void 0) { r = 0; }
  4054. if (g === void 0) { g = 0; }
  4055. if (b === void 0) { b = 0; }
  4056. if (a === void 0) { a = 1; }
  4057. this.r = r;
  4058. this.g = g;
  4059. this.b = b;
  4060. this.a = a;
  4061. }
  4062. // Operators
  4063. /**
  4064. * Adds in place the given Color4 values to the current Color4 object
  4065. * @param right defines the second operand
  4066. * @returns the current updated Color4 object
  4067. */
  4068. Color4.prototype.addInPlace = function (right) {
  4069. this.r += right.r;
  4070. this.g += right.g;
  4071. this.b += right.b;
  4072. this.a += right.a;
  4073. return this;
  4074. };
  4075. /**
  4076. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  4077. * @returns the new array
  4078. */
  4079. Color4.prototype.asArray = function () {
  4080. var result = new Array();
  4081. this.toArray(result, 0);
  4082. return result;
  4083. };
  4084. /**
  4085. * Stores from the starting index in the given array the Color4 successive values
  4086. * @param array defines the array where to store the r,g,b components
  4087. * @param index defines an optional index in the target array to define where to start storing values
  4088. * @returns the current Color4 object
  4089. */
  4090. Color4.prototype.toArray = function (array, index) {
  4091. if (index === void 0) { index = 0; }
  4092. array[index] = this.r;
  4093. array[index + 1] = this.g;
  4094. array[index + 2] = this.b;
  4095. array[index + 3] = this.a;
  4096. return this;
  4097. };
  4098. /**
  4099. * Determines equality between Color4 objects
  4100. * @param otherColor defines the second operand
  4101. * @returns true if the rgba values are equal to the given ones
  4102. */
  4103. Color4.prototype.equals = function (otherColor) {
  4104. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b && this.a === otherColor.a;
  4105. };
  4106. /**
  4107. * Creates a new Color4 set with the added values of the current Color4 and of the given one
  4108. * @param right defines the second operand
  4109. * @returns a new Color4 object
  4110. */
  4111. Color4.prototype.add = function (right) {
  4112. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  4113. };
  4114. /**
  4115. * Creates a new Color4 set with the subtracted values of the given one from the current Color4
  4116. * @param right defines the second operand
  4117. * @returns a new Color4 object
  4118. */
  4119. Color4.prototype.subtract = function (right) {
  4120. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  4121. };
  4122. /**
  4123. * Subtracts the given ones from the current Color4 values and stores the results in "result"
  4124. * @param right defines the second operand
  4125. * @param result defines the Color4 object where to store the result
  4126. * @returns the current Color4 object
  4127. */
  4128. Color4.prototype.subtractToRef = function (right, result) {
  4129. result.r = this.r - right.r;
  4130. result.g = this.g - right.g;
  4131. result.b = this.b - right.b;
  4132. result.a = this.a - right.a;
  4133. return this;
  4134. };
  4135. /**
  4136. * Creates a new Color4 with the current Color4 values multiplied by scale
  4137. * @param scale defines the scaling factor to apply
  4138. * @returns a new Color4 object
  4139. */
  4140. Color4.prototype.scale = function (scale) {
  4141. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  4142. };
  4143. /**
  4144. * Multiplies the current Color4 values by scale and stores the result in "result"
  4145. * @param scale defines the scaling factor to apply
  4146. * @param result defines the Color4 object where to store the result
  4147. * @returns the current unmodified Color4
  4148. */
  4149. Color4.prototype.scaleToRef = function (scale, result) {
  4150. result.r = this.r * scale;
  4151. result.g = this.g * scale;
  4152. result.b = this.b * scale;
  4153. result.a = this.a * scale;
  4154. return this;
  4155. };
  4156. /**
  4157. * Scale the current Color4 values by a factor and add the result to a given Color4
  4158. * @param scale defines the scale factor
  4159. * @param result defines the Color4 object where to store the result
  4160. * @returns the unmodified current Color4
  4161. */
  4162. Color4.prototype.scaleAndAddToRef = function (scale, result) {
  4163. result.r += this.r * scale;
  4164. result.g += this.g * scale;
  4165. result.b += this.b * scale;
  4166. result.a += this.a * scale;
  4167. return this;
  4168. };
  4169. /**
  4170. * Clamps the rgb values by the min and max values and stores the result into "result"
  4171. * @param min defines minimum clamping value (default is 0)
  4172. * @param max defines maximum clamping value (default is 1)
  4173. * @param result defines color to store the result into.
  4174. * @returns the cuurent Color4
  4175. */
  4176. Color4.prototype.clampToRef = function (min, max, result) {
  4177. if (min === void 0) { min = 0; }
  4178. if (max === void 0) { max = 1; }
  4179. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  4180. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  4181. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  4182. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  4183. return this;
  4184. };
  4185. /**
  4186. * Multipy an Color4 value by another and return a new Color4 object
  4187. * @param color defines the Color4 value to multiply by
  4188. * @returns a new Color4 object
  4189. */
  4190. Color4.prototype.multiply = function (color) {
  4191. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  4192. };
  4193. /**
  4194. * Multipy a Color4 value by another and push the result in a reference value
  4195. * @param color defines the Color4 value to multiply by
  4196. * @param result defines the Color4 to fill the result in
  4197. * @returns the result Color4
  4198. */
  4199. Color4.prototype.multiplyToRef = function (color, result) {
  4200. result.r = this.r * color.r;
  4201. result.g = this.g * color.g;
  4202. result.b = this.b * color.b;
  4203. result.a = this.a * color.a;
  4204. return result;
  4205. };
  4206. /**
  4207. * Creates a string with the Color4 current values
  4208. * @returns the string representation of the Color4 object
  4209. */
  4210. Color4.prototype.toString = function () {
  4211. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  4212. };
  4213. /**
  4214. * Returns the string "Color4"
  4215. * @returns "Color4"
  4216. */
  4217. Color4.prototype.getClassName = function () {
  4218. return "Color4";
  4219. };
  4220. /**
  4221. * Compute the Color4 hash code
  4222. * @returns an unique number that can be used to hash Color4 objects
  4223. */
  4224. Color4.prototype.getHashCode = function () {
  4225. var hash = this.r || 0;
  4226. hash = (hash * 397) ^ (this.g || 0);
  4227. hash = (hash * 397) ^ (this.b || 0);
  4228. hash = (hash * 397) ^ (this.a || 0);
  4229. return hash;
  4230. };
  4231. /**
  4232. * Creates a new Color4 copied from the current one
  4233. * @returns a new Color4 object
  4234. */
  4235. Color4.prototype.clone = function () {
  4236. return new Color4(this.r, this.g, this.b, this.a);
  4237. };
  4238. /**
  4239. * Copies the given Color4 values into the current one
  4240. * @param source defines the source Color4 object
  4241. * @returns the current updated Color4 object
  4242. */
  4243. Color4.prototype.copyFrom = function (source) {
  4244. this.r = source.r;
  4245. this.g = source.g;
  4246. this.b = source.b;
  4247. this.a = source.a;
  4248. return this;
  4249. };
  4250. /**
  4251. * Copies the given float values into the current one
  4252. * @param r defines the red component to read from
  4253. * @param g defines the green component to read from
  4254. * @param b defines the blue component to read from
  4255. * @param a defines the alpha component to read from
  4256. * @returns the current updated Color4 object
  4257. */
  4258. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  4259. this.r = r;
  4260. this.g = g;
  4261. this.b = b;
  4262. this.a = a;
  4263. return this;
  4264. };
  4265. /**
  4266. * Copies the given float values into the current one
  4267. * @param r defines the red component to read from
  4268. * @param g defines the green component to read from
  4269. * @param b defines the blue component to read from
  4270. * @param a defines the alpha component to read from
  4271. * @returns the current updated Color4 object
  4272. */
  4273. Color4.prototype.set = function (r, g, b, a) {
  4274. return this.copyFromFloats(r, g, b, a);
  4275. };
  4276. /**
  4277. * Compute the Color4 hexadecimal code as a string
  4278. * @returns a string containing the hexadecimal representation of the Color4 object
  4279. */
  4280. Color4.prototype.toHexString = function () {
  4281. var intR = (this.r * 255) | 0;
  4282. var intG = (this.g * 255) | 0;
  4283. var intB = (this.b * 255) | 0;
  4284. var intA = (this.a * 255) | 0;
  4285. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  4286. };
  4287. /**
  4288. * Computes a new Color4 converted from the current one to linear space
  4289. * @returns a new Color4 object
  4290. */
  4291. Color4.prototype.toLinearSpace = function () {
  4292. var convertedColor = new Color4();
  4293. this.toLinearSpaceToRef(convertedColor);
  4294. return convertedColor;
  4295. };
  4296. /**
  4297. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  4298. * @param convertedColor defines the Color4 object where to store the linear space version
  4299. * @returns the unmodified Color4
  4300. */
  4301. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  4302. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  4303. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  4304. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  4305. convertedColor.a = this.a;
  4306. return this;
  4307. };
  4308. /**
  4309. * Computes a new Color4 converted from the current one to gamma space
  4310. * @returns a new Color4 object
  4311. */
  4312. Color4.prototype.toGammaSpace = function () {
  4313. var convertedColor = new Color4();
  4314. this.toGammaSpaceToRef(convertedColor);
  4315. return convertedColor;
  4316. };
  4317. /**
  4318. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  4319. * @param convertedColor defines the Color4 object where to store the gamma space version
  4320. * @returns the unmodified Color4
  4321. */
  4322. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  4323. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  4324. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  4325. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  4326. convertedColor.a = this.a;
  4327. return this;
  4328. };
  4329. // Statics
  4330. /**
  4331. * Creates a new Color4 from the string containing valid hexadecimal values
  4332. * @param hex defines a string containing valid hexadecimal values
  4333. * @returns a new Color4 object
  4334. */
  4335. Color4.FromHexString = function (hex) {
  4336. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  4337. return new Color4(0.0, 0.0, 0.0, 0.0);
  4338. }
  4339. var r = parseInt(hex.substring(1, 3), 16);
  4340. var g = parseInt(hex.substring(3, 5), 16);
  4341. var b = parseInt(hex.substring(5, 7), 16);
  4342. var a = parseInt(hex.substring(7, 9), 16);
  4343. return Color4.FromInts(r, g, b, a);
  4344. };
  4345. /**
  4346. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  4347. * @param left defines the start value
  4348. * @param right defines the end value
  4349. * @param amount defines the gradient factor
  4350. * @returns a new Color4 object
  4351. */
  4352. Color4.Lerp = function (left, right, amount) {
  4353. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  4354. Color4.LerpToRef(left, right, amount, result);
  4355. return result;
  4356. };
  4357. /**
  4358. * Set the given "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  4359. * @param left defines the start value
  4360. * @param right defines the end value
  4361. * @param amount defines the gradient factor
  4362. * @param result defines the Color4 object where to store data
  4363. */
  4364. Color4.LerpToRef = function (left, right, amount, result) {
  4365. result.r = left.r + (right.r - left.r) * amount;
  4366. result.g = left.g + (right.g - left.g) * amount;
  4367. result.b = left.b + (right.b - left.b) * amount;
  4368. result.a = left.a + (right.a - left.a) * amount;
  4369. };
  4370. /**
  4371. * Creates a new Color4 from a Color3 and an alpha value
  4372. * @param color3 defines the source Color3 to read from
  4373. * @param alpha defines the alpha component (1.0 by default)
  4374. * @returns a new Color4 object
  4375. */
  4376. Color4.FromColor3 = function (color3, alpha) {
  4377. if (alpha === void 0) { alpha = 1.0; }
  4378. return new Color4(color3.r, color3.g, color3.b, alpha);
  4379. };
  4380. /**
  4381. * Creates a new Color4 from the starting index element of the given array
  4382. * @param array defines the source array to read from
  4383. * @param offset defines the offset in the source array
  4384. * @returns a new Color4 object
  4385. */
  4386. Color4.FromArray = function (array, offset) {
  4387. if (offset === void 0) { offset = 0; }
  4388. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4389. };
  4390. /**
  4391. * Creates a new Color3 from integer values (< 256)
  4392. * @param r defines the red component to read from (value between 0 and 255)
  4393. * @param g defines the green component to read from (value between 0 and 255)
  4394. * @param b defines the blue component to read from (value between 0 and 255)
  4395. * @param a defines the alpha component to read from (value between 0 and 255)
  4396. * @returns a new Color3 object
  4397. */
  4398. Color4.FromInts = function (r, g, b, a) {
  4399. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  4400. };
  4401. /**
  4402. * Check the content of a given array and convert it to an array containing RGBA data
  4403. * If the original array was already containing count * 4 values then it is returned directly
  4404. * @param colors defines the array to check
  4405. * @param count defines the number of RGBA data to expect
  4406. * @returns an array containing count * 4 values (RGBA)
  4407. */
  4408. Color4.CheckColors4 = function (colors, count) {
  4409. // Check if color3 was used
  4410. if (colors.length === count * 3) {
  4411. var colors4 = [];
  4412. for (var index = 0; index < colors.length; index += 3) {
  4413. var newIndex = (index / 3) * 4;
  4414. colors4[newIndex] = colors[index];
  4415. colors4[newIndex + 1] = colors[index + 1];
  4416. colors4[newIndex + 2] = colors[index + 2];
  4417. colors4[newIndex + 3] = 1.0;
  4418. }
  4419. return colors4;
  4420. }
  4421. return colors;
  4422. };
  4423. return Color4;
  4424. }());
  4425. BABYLON.Color4 = Color4;
  4426. /**
  4427. * Class representing a vector containing 2 coordinates
  4428. */
  4429. var Vector2 = /** @class */ (function () {
  4430. /**
  4431. * Creates a new Vector2 from the given x and y coordinates
  4432. * @param x defines the first coordinate
  4433. * @param y defines the second coordinate
  4434. */
  4435. function Vector2(
  4436. /** defines the first coordinate */
  4437. x,
  4438. /** defines the second coordinate */
  4439. y) {
  4440. if (x === void 0) { x = 0; }
  4441. if (y === void 0) { y = 0; }
  4442. this.x = x;
  4443. this.y = y;
  4444. }
  4445. /**
  4446. * Gets a string with the Vector2 coordinates
  4447. * @returns a string with the Vector2 coordinates
  4448. */
  4449. Vector2.prototype.toString = function () {
  4450. return "{X: " + this.x + " Y:" + this.y + "}";
  4451. };
  4452. /**
  4453. * Gets class name
  4454. * @returns the string "Vector2"
  4455. */
  4456. Vector2.prototype.getClassName = function () {
  4457. return "Vector2";
  4458. };
  4459. /**
  4460. * Gets current vector hash code
  4461. * @returns the Vector2 hash code as a number
  4462. */
  4463. Vector2.prototype.getHashCode = function () {
  4464. var hash = this.x || 0;
  4465. hash = (hash * 397) ^ (this.y || 0);
  4466. return hash;
  4467. };
  4468. // Operators
  4469. /**
  4470. * Sets the Vector2 coordinates in the given array or Float32Array from the given index.
  4471. * @param array defines the source array
  4472. * @param index defines the offset in source array
  4473. * @returns the current Vector2
  4474. */
  4475. Vector2.prototype.toArray = function (array, index) {
  4476. if (index === void 0) { index = 0; }
  4477. array[index] = this.x;
  4478. array[index + 1] = this.y;
  4479. return this;
  4480. };
  4481. /**
  4482. * Copy the current vector to an array
  4483. * @returns a new array with 2 elements: the Vector2 coordinates.
  4484. */
  4485. Vector2.prototype.asArray = function () {
  4486. var result = new Array();
  4487. this.toArray(result, 0);
  4488. return result;
  4489. };
  4490. /**
  4491. * Sets the Vector2 coordinates with the given Vector2 coordinates
  4492. * @param source defines the source Vector2
  4493. * @returns the current updated Vector2
  4494. */
  4495. Vector2.prototype.copyFrom = function (source) {
  4496. this.x = source.x;
  4497. this.y = source.y;
  4498. return this;
  4499. };
  4500. /**
  4501. * Sets the Vector2 coordinates with the given floats
  4502. * @param x defines the first coordinate
  4503. * @param y defines the second coordinate
  4504. * @returns the current updated Vector2
  4505. */
  4506. Vector2.prototype.copyFromFloats = function (x, y) {
  4507. this.x = x;
  4508. this.y = y;
  4509. return this;
  4510. };
  4511. /**
  4512. * Sets the Vector2 coordinates with the given floats
  4513. * @param x defines the first coordinate
  4514. * @param y defines the second coordinate
  4515. * @returns the current updated Vector2
  4516. */
  4517. Vector2.prototype.set = function (x, y) {
  4518. return this.copyFromFloats(x, y);
  4519. };
  4520. /**
  4521. * Add another vector with the current one
  4522. * @param otherVector defines the other vector
  4523. * @returns a new Vector2 set with the addition of the current Vector2 and the given one coordinates
  4524. */
  4525. Vector2.prototype.add = function (otherVector) {
  4526. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  4527. };
  4528. /**
  4529. * Sets the "result" coordinates with the addition of the current Vector2 and the given one coordinates
  4530. * @param otherVector defines the other vector
  4531. * @param result defines the target vector
  4532. * @returns the unmodified current Vector2
  4533. */
  4534. Vector2.prototype.addToRef = function (otherVector, result) {
  4535. result.x = this.x + otherVector.x;
  4536. result.y = this.y + otherVector.y;
  4537. return this;
  4538. };
  4539. /**
  4540. * Set the Vector2 coordinates by adding the given Vector2 coordinates
  4541. * @param otherVector defines the other vector
  4542. * @returns the current updated Vector2
  4543. */
  4544. Vector2.prototype.addInPlace = function (otherVector) {
  4545. this.x += otherVector.x;
  4546. this.y += otherVector.y;
  4547. return this;
  4548. };
  4549. /**
  4550. * Gets a new Vector2 by adding the current Vector2 coordinates to the given Vector3 x, y coordinates
  4551. * @param otherVector defines the other vector
  4552. * @returns a new Vector2
  4553. */
  4554. Vector2.prototype.addVector3 = function (otherVector) {
  4555. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  4556. };
  4557. /**
  4558. * Gets a new Vector2 set with the subtracted coordinates of the given one from the current Vector2
  4559. * @param otherVector defines the other vector
  4560. * @returns a new Vector2
  4561. */
  4562. Vector2.prototype.subtract = function (otherVector) {
  4563. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  4564. };
  4565. /**
  4566. * Sets the "result" coordinates with the subtraction of the given one from the current Vector2 coordinates.
  4567. * @param otherVector defines the other vector
  4568. * @param result defines the target vector
  4569. * @returns the unmodified current Vector2
  4570. */
  4571. Vector2.prototype.subtractToRef = function (otherVector, result) {
  4572. result.x = this.x - otherVector.x;
  4573. result.y = this.y - otherVector.y;
  4574. return this;
  4575. };
  4576. /**
  4577. * Sets the current Vector2 coordinates by subtracting from it the given one coordinates
  4578. * @param otherVector defines the other vector
  4579. * @returns the current updated Vector2
  4580. */
  4581. Vector2.prototype.subtractInPlace = function (otherVector) {
  4582. this.x -= otherVector.x;
  4583. this.y -= otherVector.y;
  4584. return this;
  4585. };
  4586. /**
  4587. * Multiplies in place the current Vector2 coordinates by the given ones
  4588. * @param otherVector defines the other vector
  4589. * @returns the current updated Vector2
  4590. */
  4591. Vector2.prototype.multiplyInPlace = function (otherVector) {
  4592. this.x *= otherVector.x;
  4593. this.y *= otherVector.y;
  4594. return this;
  4595. };
  4596. /**
  4597. * Returns a new Vector2 set with the multiplication of the current Vector2 and the given one coordinates
  4598. * @param otherVector defines the other vector
  4599. * @returns a new Vector2
  4600. */
  4601. Vector2.prototype.multiply = function (otherVector) {
  4602. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  4603. };
  4604. /**
  4605. * Sets "result" coordinates with the multiplication of the current Vector2 and the given one coordinates
  4606. * @param otherVector defines the other vector
  4607. * @param result defines the target vector
  4608. * @returns the unmodified current Vector2
  4609. */
  4610. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  4611. result.x = this.x * otherVector.x;
  4612. result.y = this.y * otherVector.y;
  4613. return this;
  4614. };
  4615. /**
  4616. * Gets a new Vector2 set with the Vector2 coordinates multiplied by the given floats
  4617. * @param x defines the first coordinate
  4618. * @param y defines the second coordinate
  4619. * @returns a new Vector2
  4620. */
  4621. Vector2.prototype.multiplyByFloats = function (x, y) {
  4622. return new Vector2(this.x * x, this.y * y);
  4623. };
  4624. /**
  4625. * Returns a new Vector2 set with the Vector2 coordinates divided by the given one coordinates
  4626. * @param otherVector defines the other vector
  4627. * @returns a new Vector2
  4628. */
  4629. Vector2.prototype.divide = function (otherVector) {
  4630. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  4631. };
  4632. /**
  4633. * Sets the "result" coordinates with the Vector2 divided by the given one coordinates
  4634. * @param otherVector defines the other vector
  4635. * @param result defines the target vector
  4636. * @returns the unmodified current Vector2
  4637. */
  4638. Vector2.prototype.divideToRef = function (otherVector, result) {
  4639. result.x = this.x / otherVector.x;
  4640. result.y = this.y / otherVector.y;
  4641. return this;
  4642. };
  4643. /**
  4644. * Divides the current Vector2 coordinates by the given ones
  4645. * @param otherVector defines the other vector
  4646. * @returns the current updated Vector2
  4647. */
  4648. Vector2.prototype.divideInPlace = function (otherVector) {
  4649. return this.divideToRef(otherVector, this);
  4650. };
  4651. /**
  4652. * Gets a new Vector2 with current Vector2 negated coordinates
  4653. * @returns a new Vector2
  4654. */
  4655. Vector2.prototype.negate = function () {
  4656. return new Vector2(-this.x, -this.y);
  4657. };
  4658. /**
  4659. * Multiply the Vector2 coordinates by scale
  4660. * @param scale defines the scaling factor
  4661. * @returns the current updated Vector2
  4662. */
  4663. Vector2.prototype.scaleInPlace = function (scale) {
  4664. this.x *= scale;
  4665. this.y *= scale;
  4666. return this;
  4667. };
  4668. /**
  4669. * Returns a new Vector2 scaled by "scale" from the current Vector2
  4670. * @param scale defines the scaling factor
  4671. * @returns a new Vector2
  4672. */
  4673. Vector2.prototype.scale = function (scale) {
  4674. var result = new Vector2(0, 0);
  4675. this.scaleToRef(scale, result);
  4676. return result;
  4677. };
  4678. /**
  4679. * Scale the current Vector2 values by a factor to a given Vector2
  4680. * @param scale defines the scale factor
  4681. * @param result defines the Vector2 object where to store the result
  4682. * @returns the unmodified current Vector2
  4683. */
  4684. Vector2.prototype.scaleToRef = function (scale, result) {
  4685. result.x = this.x * scale;
  4686. result.y = this.y * scale;
  4687. return this;
  4688. };
  4689. /**
  4690. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  4691. * @param scale defines the scale factor
  4692. * @param result defines the Vector2 object where to store the result
  4693. * @returns the unmodified current Vector2
  4694. */
  4695. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  4696. result.x += this.x * scale;
  4697. result.y += this.y * scale;
  4698. return this;
  4699. };
  4700. /**
  4701. * Gets a boolean if two vectors are equals
  4702. * @param otherVector defines the other vector
  4703. * @returns true if the given vector coordinates strictly equal the current Vector2 ones
  4704. */
  4705. Vector2.prototype.equals = function (otherVector) {
  4706. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  4707. };
  4708. /**
  4709. * Gets a boolean if two vectors are equals (using an epsilon value)
  4710. * @param otherVector defines the other vector
  4711. * @param epsilon defines the minimal distance to consider equality
  4712. * @returns true if the given vector coordinates are close to the current ones by a distance of epsilon.
  4713. */
  4714. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  4715. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  4716. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  4717. };
  4718. /**
  4719. * Gets a new Vector2 from current Vector2 floored values
  4720. * @returns a new Vector2
  4721. */
  4722. Vector2.prototype.floor = function () {
  4723. return new Vector2(Math.floor(this.x), Math.floor(this.y));
  4724. };
  4725. /**
  4726. * Gets a new Vector2 from current Vector2 floored values
  4727. * @returns a new Vector2
  4728. */
  4729. Vector2.prototype.fract = function () {
  4730. return new Vector2(this.x - Math.floor(this.x), this.y - Math.floor(this.y));
  4731. };
  4732. // Properties
  4733. /**
  4734. * Gets the length of the vector
  4735. * @returns the vector length (float)
  4736. */
  4737. Vector2.prototype.length = function () {
  4738. return Math.sqrt(this.x * this.x + this.y * this.y);
  4739. };
  4740. /**
  4741. * Gets the vector squared length
  4742. * @returns the vector squared length (float)
  4743. */
  4744. Vector2.prototype.lengthSquared = function () {
  4745. return (this.x * this.x + this.y * this.y);
  4746. };
  4747. // Methods
  4748. /**
  4749. * Normalize the vector
  4750. * @returns the current updated Vector2
  4751. */
  4752. Vector2.prototype.normalize = function () {
  4753. var len = this.length();
  4754. if (len === 0) {
  4755. return this;
  4756. }
  4757. var num = 1.0 / len;
  4758. this.x *= num;
  4759. this.y *= num;
  4760. return this;
  4761. };
  4762. /**
  4763. * Gets a new Vector2 copied from the Vector2
  4764. * @returns a new Vector2
  4765. */
  4766. Vector2.prototype.clone = function () {
  4767. return new Vector2(this.x, this.y);
  4768. };
  4769. // Statics
  4770. /**
  4771. * Gets a new Vector2(0, 0)
  4772. * @returns a new Vector2
  4773. */
  4774. Vector2.Zero = function () {
  4775. return new Vector2(0, 0);
  4776. };
  4777. /**
  4778. * Gets a new Vector2(1, 1)
  4779. * @returns a new Vector2
  4780. */
  4781. Vector2.One = function () {
  4782. return new Vector2(1, 1);
  4783. };
  4784. /**
  4785. * Gets a new Vector2 set from the given index element of the given array
  4786. * @param array defines the data source
  4787. * @param offset defines the offset in the data source
  4788. * @returns a new Vector2
  4789. */
  4790. Vector2.FromArray = function (array, offset) {
  4791. if (offset === void 0) { offset = 0; }
  4792. return new Vector2(array[offset], array[offset + 1]);
  4793. };
  4794. /**
  4795. * Sets "result" from the given index element of the given array
  4796. * @param array defines the data source
  4797. * @param offset defines the offset in the data source
  4798. * @param result defines the target vector
  4799. */
  4800. Vector2.FromArrayToRef = function (array, offset, result) {
  4801. result.x = array[offset];
  4802. result.y = array[offset + 1];
  4803. };
  4804. /**
  4805. * Gets a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the given four Vector2
  4806. * @param value1 defines 1st point of control
  4807. * @param value2 defines 2nd point of control
  4808. * @param value3 defines 3rd point of control
  4809. * @param value4 defines 4th point of control
  4810. * @param amount defines the interpolation factor
  4811. * @returns a new Vector2
  4812. */
  4813. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  4814. var squared = amount * amount;
  4815. var cubed = amount * squared;
  4816. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  4817. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  4818. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  4819. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  4820. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  4821. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  4822. return new Vector2(x, y);
  4823. };
  4824. /**
  4825. * 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".
  4826. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  4827. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate
  4828. * @param value defines the value to clamp
  4829. * @param min defines the lower limit
  4830. * @param max defines the upper limit
  4831. * @returns a new Vector2
  4832. */
  4833. Vector2.Clamp = function (value, min, max) {
  4834. var x = value.x;
  4835. x = (x > max.x) ? max.x : x;
  4836. x = (x < min.x) ? min.x : x;
  4837. var y = value.y;
  4838. y = (y > max.y) ? max.y : y;
  4839. y = (y < min.y) ? min.y : y;
  4840. return new Vector2(x, y);
  4841. };
  4842. /**
  4843. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2"
  4844. * @param value1 defines the 1st control point
  4845. * @param tangent1 defines the outgoing tangent
  4846. * @param value2 defines the 2nd control point
  4847. * @param tangent2 defines the incoming tangent
  4848. * @param amount defines the interpolation factor
  4849. * @returns a new Vector2
  4850. */
  4851. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  4852. var squared = amount * amount;
  4853. var cubed = amount * squared;
  4854. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  4855. var part2 = (-2.0 * cubed) + (3.0 * squared);
  4856. var part3 = (cubed - (2.0 * squared)) + amount;
  4857. var part4 = cubed - squared;
  4858. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  4859. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  4860. return new Vector2(x, y);
  4861. };
  4862. /**
  4863. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  4864. * @param start defines the start vector
  4865. * @param end defines the end vector
  4866. * @param amount defines the interpolation factor
  4867. * @returns a new Vector2
  4868. */
  4869. Vector2.Lerp = function (start, end, amount) {
  4870. var x = start.x + ((end.x - start.x) * amount);
  4871. var y = start.y + ((end.y - start.y) * amount);
  4872. return new Vector2(x, y);
  4873. };
  4874. /**
  4875. * Gets the dot product of the vector "left" and the vector "right"
  4876. * @param left defines first vector
  4877. * @param right defines second vector
  4878. * @returns the dot product (float)
  4879. */
  4880. Vector2.Dot = function (left, right) {
  4881. return left.x * right.x + left.y * right.y;
  4882. };
  4883. /**
  4884. * Returns a new Vector2 equal to the normalized given vector
  4885. * @param vector defines the vector to normalize
  4886. * @returns a new Vector2
  4887. */
  4888. Vector2.Normalize = function (vector) {
  4889. var newVector = vector.clone();
  4890. newVector.normalize();
  4891. return newVector;
  4892. };
  4893. /**
  4894. * Gets a new Vector2 set with the minimal coordinate values from the "left" and "right" vectors
  4895. * @param left defines 1st vector
  4896. * @param right defines 2nd vector
  4897. * @returns a new Vector2
  4898. */
  4899. Vector2.Minimize = function (left, right) {
  4900. var x = (left.x < right.x) ? left.x : right.x;
  4901. var y = (left.y < right.y) ? left.y : right.y;
  4902. return new Vector2(x, y);
  4903. };
  4904. /**
  4905. * Gets a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors
  4906. * @param left defines 1st vector
  4907. * @param right defines 2nd vector
  4908. * @returns a new Vector2
  4909. */
  4910. Vector2.Maximize = function (left, right) {
  4911. var x = (left.x > right.x) ? left.x : right.x;
  4912. var y = (left.y > right.y) ? left.y : right.y;
  4913. return new Vector2(x, y);
  4914. };
  4915. /**
  4916. * Gets a new Vector2 set with the transformed coordinates of the given vector by the given transformation matrix
  4917. * @param vector defines the vector to transform
  4918. * @param transformation defines the matrix to apply
  4919. * @returns a new Vector2
  4920. */
  4921. Vector2.Transform = function (vector, transformation) {
  4922. var r = Vector2.Zero();
  4923. Vector2.TransformToRef(vector, transformation, r);
  4924. return r;
  4925. };
  4926. /**
  4927. * Transforms the given vector coordinates by the given transformation matrix and stores the result in the vector "result" coordinates
  4928. * @param vector defines the vector to transform
  4929. * @param transformation defines the matrix to apply
  4930. * @param result defines the target vector
  4931. */
  4932. Vector2.TransformToRef = function (vector, transformation, result) {
  4933. var m = transformation.m;
  4934. var x = (vector.x * m[0]) + (vector.y * m[4]) + m[12];
  4935. var y = (vector.x * m[1]) + (vector.y * m[5]) + m[13];
  4936. result.x = x;
  4937. result.y = y;
  4938. };
  4939. /**
  4940. * Determines if a given vector is included in a triangle
  4941. * @param p defines the vector to test
  4942. * @param p0 defines 1st triangle point
  4943. * @param p1 defines 2nd triangle point
  4944. * @param p2 defines 3rd triangle point
  4945. * @returns true if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  4946. */
  4947. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  4948. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  4949. var sign = a < 0 ? -1 : 1;
  4950. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  4951. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  4952. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  4953. };
  4954. /**
  4955. * Gets the distance between the vectors "value1" and "value2"
  4956. * @param value1 defines first vector
  4957. * @param value2 defines second vector
  4958. * @returns the distance between vectors
  4959. */
  4960. Vector2.Distance = function (value1, value2) {
  4961. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  4962. };
  4963. /**
  4964. * Returns the squared distance between the vectors "value1" and "value2"
  4965. * @param value1 defines first vector
  4966. * @param value2 defines second vector
  4967. * @returns the squared distance between vectors
  4968. */
  4969. Vector2.DistanceSquared = function (value1, value2) {
  4970. var x = value1.x - value2.x;
  4971. var y = value1.y - value2.y;
  4972. return (x * x) + (y * y);
  4973. };
  4974. /**
  4975. * Gets a new Vector2 located at the center of the vectors "value1" and "value2"
  4976. * @param value1 defines first vector
  4977. * @param value2 defines second vector
  4978. * @returns a new Vector2
  4979. */
  4980. Vector2.Center = function (value1, value2) {
  4981. var center = value1.add(value2);
  4982. center.scaleInPlace(0.5);
  4983. return center;
  4984. };
  4985. /**
  4986. * Gets the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  4987. * @param p defines the middle point
  4988. * @param segA defines one point of the segment
  4989. * @param segB defines the other point of the segment
  4990. * @returns the shortest distance
  4991. */
  4992. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  4993. var l2 = Vector2.DistanceSquared(segA, segB);
  4994. if (l2 === 0.0) {
  4995. return Vector2.Distance(p, segA);
  4996. }
  4997. var v = segB.subtract(segA);
  4998. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  4999. var proj = segA.add(v.multiplyByFloats(t, t));
  5000. return Vector2.Distance(p, proj);
  5001. };
  5002. return Vector2;
  5003. }());
  5004. BABYLON.Vector2 = Vector2;
  5005. /**
  5006. * Classed used to store (x,y,z) vector representation
  5007. * A Vector3 is the main object used in 3D geometry
  5008. * It can represent etiher the coordinates of a point the space, either a direction
  5009. * Reminder: Babylon.js uses a left handed forward facing system
  5010. */
  5011. var Vector3 = /** @class */ (function () {
  5012. /**
  5013. * Creates a new Vector3 object from the given x, y, z (floats) coordinates.
  5014. * @param x defines the first coordinates (on X axis)
  5015. * @param y defines the second coordinates (on Y axis)
  5016. * @param z defines the third coordinates (on Z axis)
  5017. */
  5018. function Vector3(
  5019. /**
  5020. * Defines the first coordinates (on X axis)
  5021. */
  5022. x,
  5023. /**
  5024. * Defines the second coordinates (on Y axis)
  5025. */
  5026. y,
  5027. /**
  5028. * Defines the third coordinates (on Z axis)
  5029. */
  5030. z) {
  5031. if (x === void 0) { x = 0; }
  5032. if (y === void 0) { y = 0; }
  5033. if (z === void 0) { z = 0; }
  5034. this.x = x;
  5035. this.y = y;
  5036. this.z = z;
  5037. }
  5038. /**
  5039. * Creates a string representation of the Vector3
  5040. * @returns a string with the Vector3 coordinates.
  5041. */
  5042. Vector3.prototype.toString = function () {
  5043. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  5044. };
  5045. /**
  5046. * Gets the class name
  5047. * @returns the string "Vector3"
  5048. */
  5049. Vector3.prototype.getClassName = function () {
  5050. return "Vector3";
  5051. };
  5052. /**
  5053. * Creates the Vector3 hash code
  5054. * @returns a number which tends to be unique between Vector3 instances
  5055. */
  5056. Vector3.prototype.getHashCode = function () {
  5057. var hash = this.x || 0;
  5058. hash = (hash * 397) ^ (this.y || 0);
  5059. hash = (hash * 397) ^ (this.z || 0);
  5060. return hash;
  5061. };
  5062. // Operators
  5063. /**
  5064. * Creates an array containing three elements : the coordinates of the Vector3
  5065. * @returns a new array of numbers
  5066. */
  5067. Vector3.prototype.asArray = function () {
  5068. var result = [];
  5069. this.toArray(result, 0);
  5070. return result;
  5071. };
  5072. /**
  5073. * Populates the given array or Float32Array from the given index with the successive coordinates of the Vector3
  5074. * @param array defines the destination array
  5075. * @param index defines the offset in the destination array
  5076. * @returns the current Vector3
  5077. */
  5078. Vector3.prototype.toArray = function (array, index) {
  5079. if (index === void 0) { index = 0; }
  5080. array[index] = this.x;
  5081. array[index + 1] = this.y;
  5082. array[index + 2] = this.z;
  5083. return this;
  5084. };
  5085. /**
  5086. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  5087. * @returns a new Quaternion object, computed from the Vector3 coordinates
  5088. */
  5089. Vector3.prototype.toQuaternion = function () {
  5090. return BABYLON.Quaternion.RotationYawPitchRoll(this.y, this.x, this.z);
  5091. };
  5092. /**
  5093. * Adds the given vector to the current Vector3
  5094. * @param otherVector defines the second operand
  5095. * @returns the current updated Vector3
  5096. */
  5097. Vector3.prototype.addInPlace = function (otherVector) {
  5098. return this.addInPlaceFromFloats(otherVector.x, otherVector.y, otherVector.z);
  5099. };
  5100. /**
  5101. * Adds the given coordinates to the current Vector3
  5102. * @param x defines the x coordinate of the operand
  5103. * @param y defines the y coordinate of the operand
  5104. * @param z defines the z coordinate of the operand
  5105. * @returns the current updated Vector3
  5106. */
  5107. Vector3.prototype.addInPlaceFromFloats = function (x, y, z) {
  5108. this.x += x;
  5109. this.y += y;
  5110. this.z += z;
  5111. return this;
  5112. };
  5113. /**
  5114. * Gets a new Vector3, result of the addition the current Vector3 and the given vector
  5115. * @param otherVector defines the second operand
  5116. * @returns the resulting Vector3
  5117. */
  5118. Vector3.prototype.add = function (otherVector) {
  5119. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  5120. };
  5121. /**
  5122. * Adds the current Vector3 to the given one and stores the result in the vector "result"
  5123. * @param otherVector defines the second operand
  5124. * @param result defines the Vector3 object where to store the result
  5125. * @returns the current Vector3
  5126. */
  5127. Vector3.prototype.addToRef = function (otherVector, result) {
  5128. return result.copyFromFloats(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  5129. };
  5130. /**
  5131. * Subtract the given vector from the current Vector3
  5132. * @param otherVector defines the second operand
  5133. * @returns the current updated Vector3
  5134. */
  5135. Vector3.prototype.subtractInPlace = function (otherVector) {
  5136. this.x -= otherVector.x;
  5137. this.y -= otherVector.y;
  5138. this.z -= otherVector.z;
  5139. return this;
  5140. };
  5141. /**
  5142. * Returns a new Vector3, result of the subtraction of the given vector from the current Vector3
  5143. * @param otherVector defines the second operand
  5144. * @returns the resulting Vector3
  5145. */
  5146. Vector3.prototype.subtract = function (otherVector) {
  5147. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  5148. };
  5149. /**
  5150. * Subtracts the given vector from the current Vector3 and stores the result in the vector "result".
  5151. * @param otherVector defines the second operand
  5152. * @param result defines the Vector3 object where to store the result
  5153. * @returns the current Vector3
  5154. */
  5155. Vector3.prototype.subtractToRef = function (otherVector, result) {
  5156. return this.subtractFromFloatsToRef(otherVector.x, otherVector.y, otherVector.z, result);
  5157. };
  5158. /**
  5159. * Returns a new Vector3 set with the subtraction of the given floats from the current Vector3 coordinates
  5160. * @param x defines the x coordinate of the operand
  5161. * @param y defines the y coordinate of the operand
  5162. * @param z defines the z coordinate of the operand
  5163. * @returns the resulting Vector3
  5164. */
  5165. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  5166. return new Vector3(this.x - x, this.y - y, this.z - z);
  5167. };
  5168. /**
  5169. * Subtracts the given floats from the current Vector3 coordinates and set the given vector "result" with this result
  5170. * @param x defines the x coordinate of the operand
  5171. * @param y defines the y coordinate of the operand
  5172. * @param z defines the z coordinate of the operand
  5173. * @param result defines the Vector3 object where to store the result
  5174. * @returns the current Vector3
  5175. */
  5176. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  5177. return result.copyFromFloats(this.x - x, this.y - y, this.z - z);
  5178. };
  5179. /**
  5180. * Gets a new Vector3 set with the current Vector3 negated coordinates
  5181. * @returns a new Vector3
  5182. */
  5183. Vector3.prototype.negate = function () {
  5184. return new Vector3(-this.x, -this.y, -this.z);
  5185. };
  5186. /**
  5187. * Multiplies the Vector3 coordinates by the float "scale"
  5188. * @param scale defines the multiplier factor
  5189. * @returns the current updated Vector3
  5190. */
  5191. Vector3.prototype.scaleInPlace = function (scale) {
  5192. this.x *= scale;
  5193. this.y *= scale;
  5194. this.z *= scale;
  5195. return this;
  5196. };
  5197. /**
  5198. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  5199. * @param scale defines the multiplier factor
  5200. * @returns a new Vector3
  5201. */
  5202. Vector3.prototype.scale = function (scale) {
  5203. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  5204. };
  5205. /**
  5206. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the given vector "result" coordinates
  5207. * @param scale defines the multiplier factor
  5208. * @param result defines the Vector3 object where to store the result
  5209. * @returns the current Vector3
  5210. */
  5211. Vector3.prototype.scaleToRef = function (scale, result) {
  5212. return result.copyFromFloats(this.x * scale, this.y * scale, this.z * scale);
  5213. };
  5214. /**
  5215. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  5216. * @param scale defines the scale factor
  5217. * @param result defines the Vector3 object where to store the result
  5218. * @returns the unmodified current Vector3
  5219. */
  5220. Vector3.prototype.scaleAndAddToRef = function (scale, result) {
  5221. return result.addInPlaceFromFloats(this.x * scale, this.y * scale, this.z * scale);
  5222. };
  5223. /**
  5224. * Returns true if the current Vector3 and the given vector coordinates are strictly equal
  5225. * @param otherVector defines the second operand
  5226. * @returns true if both vectors are equals
  5227. */
  5228. Vector3.prototype.equals = function (otherVector) {
  5229. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  5230. };
  5231. /**
  5232. * Returns true if the current Vector3 and the given vector coordinates are distant less than epsilon
  5233. * @param otherVector defines the second operand
  5234. * @param epsilon defines the minimal distance to define values as equals
  5235. * @returns true if both vectors are distant less than epsilon
  5236. */
  5237. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  5238. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  5239. 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);
  5240. };
  5241. /**
  5242. * Returns true if the current Vector3 coordinates equals the given floats
  5243. * @param x defines the x coordinate of the operand
  5244. * @param y defines the y coordinate of the operand
  5245. * @param z defines the z coordinate of the operand
  5246. * @returns true if both vectors are equals
  5247. */
  5248. Vector3.prototype.equalsToFloats = function (x, y, z) {
  5249. return this.x === x && this.y === y && this.z === z;
  5250. };
  5251. /**
  5252. * Multiplies the current Vector3 coordinates by the given ones
  5253. * @param otherVector defines the second operand
  5254. * @returns the current updated Vector3
  5255. */
  5256. Vector3.prototype.multiplyInPlace = function (otherVector) {
  5257. this.x *= otherVector.x;
  5258. this.y *= otherVector.y;
  5259. this.z *= otherVector.z;
  5260. return this;
  5261. };
  5262. /**
  5263. * Returns a new Vector3, result of the multiplication of the current Vector3 by the given vector
  5264. * @param otherVector defines the second operand
  5265. * @returns the new Vector3
  5266. */
  5267. Vector3.prototype.multiply = function (otherVector) {
  5268. return this.multiplyByFloats(otherVector.x, otherVector.y, otherVector.z);
  5269. };
  5270. /**
  5271. * Multiplies the current Vector3 by the given one and stores the result in the given vector "result"
  5272. * @param otherVector defines the second operand
  5273. * @param result defines the Vector3 object where to store the result
  5274. * @returns the current Vector3
  5275. */
  5276. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  5277. return result.copyFromFloats(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  5278. };
  5279. /**
  5280. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the given floats
  5281. * @param x defines the x coordinate of the operand
  5282. * @param y defines the y coordinate of the operand
  5283. * @param z defines the z coordinate of the operand
  5284. * @returns the new Vector3
  5285. */
  5286. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  5287. return new Vector3(this.x * x, this.y * y, this.z * z);
  5288. };
  5289. /**
  5290. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the given ones
  5291. * @param otherVector defines the second operand
  5292. * @returns the new Vector3
  5293. */
  5294. Vector3.prototype.divide = function (otherVector) {
  5295. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  5296. };
  5297. /**
  5298. * Divides the current Vector3 coordinates by the given ones and stores the result in the given vector "result"
  5299. * @param otherVector defines the second operand
  5300. * @param result defines the Vector3 object where to store the result
  5301. * @returns the current Vector3
  5302. */
  5303. Vector3.prototype.divideToRef = function (otherVector, result) {
  5304. return result.copyFromFloats(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  5305. };
  5306. /**
  5307. * Divides the current Vector3 coordinates by the given ones.
  5308. * @param otherVector defines the second operand
  5309. * @returns the current updated Vector3
  5310. */
  5311. Vector3.prototype.divideInPlace = function (otherVector) {
  5312. return this.divideToRef(otherVector, this);
  5313. };
  5314. /**
  5315. * Updates the current Vector3 with the minimal coordinate values between its and the given vector ones
  5316. * @param other defines the second operand
  5317. * @returns the current updated Vector3
  5318. */
  5319. Vector3.prototype.minimizeInPlace = function (other) {
  5320. return this.minimizeInPlaceFromFloats(other.x, other.y, other.z);
  5321. };
  5322. /**
  5323. * Updates the current Vector3 with the maximal coordinate values between its and the given vector ones.
  5324. * @param other defines the second operand
  5325. * @returns the current updated Vector3
  5326. */
  5327. Vector3.prototype.maximizeInPlace = function (other) {
  5328. return this.maximizeInPlaceFromFloats(other.x, other.y, other.z);
  5329. };
  5330. /**
  5331. * Updates the current Vector3 with the minimal coordinate values between its and the given coordinates
  5332. * @param x defines the x coordinate of the operand
  5333. * @param y defines the y coordinate of the operand
  5334. * @param z defines the z coordinate of the operand
  5335. * @returns the current updated Vector3
  5336. */
  5337. Vector3.prototype.minimizeInPlaceFromFloats = function (x, y, z) {
  5338. if (x < this.x) {
  5339. this.x = x;
  5340. }
  5341. if (y < this.y) {
  5342. this.y = y;
  5343. }
  5344. if (z < this.z) {
  5345. this.z = z;
  5346. }
  5347. return this;
  5348. };
  5349. /**
  5350. * Updates the current Vector3 with the maximal coordinate values between its and the given coordinates.
  5351. * @param x defines the x coordinate of the operand
  5352. * @param y defines the y coordinate of the operand
  5353. * @param z defines the z coordinate of the operand
  5354. * @returns the current updated Vector3
  5355. */
  5356. Vector3.prototype.maximizeInPlaceFromFloats = function (x, y, z) {
  5357. if (x > this.x) {
  5358. this.x = x;
  5359. }
  5360. if (y > this.y) {
  5361. this.y = y;
  5362. }
  5363. if (z > this.z) {
  5364. this.z = z;
  5365. }
  5366. return this;
  5367. };
  5368. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  5369. /**
  5370. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  5371. */
  5372. get: function () {
  5373. var absX = Math.abs(this.x);
  5374. var absY = Math.abs(this.y);
  5375. if (absX !== absY) {
  5376. return true;
  5377. }
  5378. var absZ = Math.abs(this.z);
  5379. if (absX !== absZ) {
  5380. return true;
  5381. }
  5382. if (absY !== absZ) {
  5383. return true;
  5384. }
  5385. return false;
  5386. },
  5387. enumerable: true,
  5388. configurable: true
  5389. });
  5390. /**
  5391. * Gets a new Vector3 from current Vector3 floored values
  5392. * @returns a new Vector3
  5393. */
  5394. Vector3.prototype.floor = function () {
  5395. return new Vector3(Math.floor(this.x), Math.floor(this.y), Math.floor(this.z));
  5396. };
  5397. /**
  5398. * Gets a new Vector3 from current Vector3 floored values
  5399. * @returns a new Vector3
  5400. */
  5401. Vector3.prototype.fract = function () {
  5402. return new Vector3(this.x - Math.floor(this.x), this.y - Math.floor(this.y), this.z - Math.floor(this.z));
  5403. };
  5404. // Properties
  5405. /**
  5406. * Gets the length of the Vector3
  5407. * @returns the length of the Vecto3
  5408. */
  5409. Vector3.prototype.length = function () {
  5410. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  5411. };
  5412. /**
  5413. * Gets the squared length of the Vector3
  5414. * @returns squared length of the Vector3
  5415. */
  5416. Vector3.prototype.lengthSquared = function () {
  5417. return (this.x * this.x + this.y * this.y + this.z * this.z);
  5418. };
  5419. /**
  5420. * Normalize the current Vector3.
  5421. * Please note that this is an in place operation.
  5422. * @returns the current updated Vector3
  5423. */
  5424. Vector3.prototype.normalize = function () {
  5425. return this.normalizeFromLength(this.length());
  5426. };
  5427. /**
  5428. * Reorders the x y z properties of the vector in place
  5429. * @param order new ordering of the properties (eg. for vector 1,2,3 with "ZYX" will produce 3,2,1)
  5430. * @returns the current updated vector
  5431. */
  5432. Vector3.prototype.reorderInPlace = function (order) {
  5433. var _this = this;
  5434. order = order.toLowerCase();
  5435. if (order === "xyz") {
  5436. return this;
  5437. }
  5438. MathTmp.Vector3[0].copyFrom(this);
  5439. ["x", "y", "z"].forEach(function (val, i) {
  5440. _this[val] = MathTmp.Vector3[0][order[i]];
  5441. });
  5442. return this;
  5443. };
  5444. /**
  5445. * Rotates the vector around 0,0,0 by a quaternion
  5446. * @param quaternion the rotation quaternion
  5447. * @param result vector to store the result
  5448. * @returns the resulting vector
  5449. */
  5450. Vector3.prototype.rotateByQuaternionToRef = function (quaternion, result) {
  5451. quaternion.toRotationMatrix(MathTmp.Matrix[0]);
  5452. Vector3.TransformCoordinatesToRef(this, MathTmp.Matrix[0], result);
  5453. return result;
  5454. };
  5455. /**
  5456. * Rotates a vector around a given point
  5457. * @param quaternion the rotation quaternion
  5458. * @param point the point to rotate around
  5459. * @param result vector to store the result
  5460. * @returns the resulting vector
  5461. */
  5462. Vector3.prototype.rotateByQuaternionAroundPointToRef = function (quaternion, point, result) {
  5463. this.subtractToRef(point, MathTmp.Vector3[0]);
  5464. MathTmp.Vector3[0].rotateByQuaternionToRef(quaternion, MathTmp.Vector3[0]);
  5465. point.addToRef(MathTmp.Vector3[0], result);
  5466. return result;
  5467. };
  5468. /**
  5469. * Normalize the current Vector3 with the given input length.
  5470. * Please note that this is an in place operation.
  5471. * @param len the length of the vector
  5472. * @returns the current updated Vector3
  5473. */
  5474. Vector3.prototype.normalizeFromLength = function (len) {
  5475. if (len === 0 || len === 1.0) {
  5476. return this;
  5477. }
  5478. return this.scaleInPlace(1.0 / len);
  5479. };
  5480. /**
  5481. * Normalize the current Vector3 to a new vector
  5482. * @returns the new Vector3
  5483. */
  5484. Vector3.prototype.normalizeToNew = function () {
  5485. var normalized = new Vector3(0, 0, 0);
  5486. this.normalizeToRef(normalized);
  5487. return normalized;
  5488. };
  5489. /**
  5490. * Normalize the current Vector3 to the reference
  5491. * @param reference define the Vector3 to update
  5492. * @returns the updated Vector3
  5493. */
  5494. Vector3.prototype.normalizeToRef = function (reference) {
  5495. var len = this.length();
  5496. if (len === 0 || len === 1.0) {
  5497. return reference.copyFromFloats(this.x, this.y, this.z);
  5498. }
  5499. return this.scaleToRef(1.0 / len, reference);
  5500. };
  5501. /**
  5502. * Creates a new Vector3 copied from the current Vector3
  5503. * @returns the new Vector3
  5504. */
  5505. Vector3.prototype.clone = function () {
  5506. return new Vector3(this.x, this.y, this.z);
  5507. };
  5508. /**
  5509. * Copies the given vector coordinates to the current Vector3 ones
  5510. * @param source defines the source Vector3
  5511. * @returns the current updated Vector3
  5512. */
  5513. Vector3.prototype.copyFrom = function (source) {
  5514. return this.copyFromFloats(source.x, source.y, source.z);
  5515. };
  5516. /**
  5517. * Copies the given floats to the current Vector3 coordinates
  5518. * @param x defines the x coordinate of the operand
  5519. * @param y defines the y coordinate of the operand
  5520. * @param z defines the z coordinate of the operand
  5521. * @returns the current updated Vector3
  5522. */
  5523. Vector3.prototype.copyFromFloats = function (x, y, z) {
  5524. this.x = x;
  5525. this.y = y;
  5526. this.z = z;
  5527. return this;
  5528. };
  5529. /**
  5530. * Copies the given floats to the current Vector3 coordinates
  5531. * @param x defines the x coordinate of the operand
  5532. * @param y defines the y coordinate of the operand
  5533. * @param z defines the z coordinate of the operand
  5534. * @returns the current updated Vector3
  5535. */
  5536. Vector3.prototype.set = function (x, y, z) {
  5537. return this.copyFromFloats(x, y, z);
  5538. };
  5539. /**
  5540. * Copies the given float to the current Vector3 coordinates
  5541. * @param v defines the x, y and z coordinates of the operand
  5542. * @returns the current updated Vector3
  5543. */
  5544. Vector3.prototype.setAll = function (v) {
  5545. this.x = this.y = this.z = v;
  5546. return this;
  5547. };
  5548. // Statics
  5549. /**
  5550. * Get the clip factor between two vectors
  5551. * @param vector0 defines the first operand
  5552. * @param vector1 defines the second operand
  5553. * @param axis defines the axis to use
  5554. * @param size defines the size along the axis
  5555. * @returns the clip factor
  5556. */
  5557. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  5558. var d0 = Vector3.Dot(vector0, axis) - size;
  5559. var d1 = Vector3.Dot(vector1, axis) - size;
  5560. var s = d0 / (d0 - d1);
  5561. return s;
  5562. };
  5563. /**
  5564. * Get angle between two vectors
  5565. * @param vector0 angle between vector0 and vector1
  5566. * @param vector1 angle between vector0 and vector1
  5567. * @param normal direction of the normal
  5568. * @return the angle between vector0 and vector1
  5569. */
  5570. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  5571. var v0 = vector0.normalizeToRef(MathTmp.Vector3[1]);
  5572. var v1 = vector1.normalizeToRef(MathTmp.Vector3[2]);
  5573. var dot = Vector3.Dot(v0, v1);
  5574. var n = MathTmp.Vector3[3];
  5575. Vector3.CrossToRef(v0, v1, n);
  5576. if (Vector3.Dot(n, normal) > 0) {
  5577. return Math.acos(dot);
  5578. }
  5579. return -Math.acos(dot);
  5580. };
  5581. /**
  5582. * Returns a new Vector3 set from the index "offset" of the given array
  5583. * @param array defines the source array
  5584. * @param offset defines the offset in the source array
  5585. * @returns the new Vector3
  5586. */
  5587. Vector3.FromArray = function (array, offset) {
  5588. if (offset === void 0) { offset = 0; }
  5589. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  5590. };
  5591. /**
  5592. * Returns a new Vector3 set from the index "offset" of the given Float32Array
  5593. * This function is deprecated. Use FromArray instead
  5594. * @param array defines the source array
  5595. * @param offset defines the offset in the source array
  5596. * @returns the new Vector3
  5597. */
  5598. Vector3.FromFloatArray = function (array, offset) {
  5599. return Vector3.FromArray(array, offset);
  5600. };
  5601. /**
  5602. * Sets the given vector "result" with the element values from the index "offset" of the given array
  5603. * @param array defines the source array
  5604. * @param offset defines the offset in the source array
  5605. * @param result defines the Vector3 where to store the result
  5606. */
  5607. Vector3.FromArrayToRef = function (array, offset, result) {
  5608. result.x = array[offset];
  5609. result.y = array[offset + 1];
  5610. result.z = array[offset + 2];
  5611. };
  5612. /**
  5613. * Sets the given vector "result" with the element values from the index "offset" of the given Float32Array
  5614. * This function is deprecated. Use FromArrayToRef instead.
  5615. * @param array defines the source array
  5616. * @param offset defines the offset in the source array
  5617. * @param result defines the Vector3 where to store the result
  5618. */
  5619. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  5620. return Vector3.FromArrayToRef(array, offset, result);
  5621. };
  5622. /**
  5623. * Sets the given vector "result" with the given floats.
  5624. * @param x defines the x coordinate of the source
  5625. * @param y defines the y coordinate of the source
  5626. * @param z defines the z coordinate of the source
  5627. * @param result defines the Vector3 where to store the result
  5628. */
  5629. Vector3.FromFloatsToRef = function (x, y, z, result) {
  5630. result.copyFromFloats(x, y, z);
  5631. };
  5632. /**
  5633. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  5634. * @returns a new empty Vector3
  5635. */
  5636. Vector3.Zero = function () {
  5637. return new Vector3(0.0, 0.0, 0.0);
  5638. };
  5639. /**
  5640. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  5641. * @returns a new unit Vector3
  5642. */
  5643. Vector3.One = function () {
  5644. return new Vector3(1.0, 1.0, 1.0);
  5645. };
  5646. /**
  5647. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  5648. * @returns a new up Vector3
  5649. */
  5650. Vector3.Up = function () {
  5651. return new Vector3(0.0, 1.0, 0.0);
  5652. };
  5653. Object.defineProperty(Vector3, "UpReadOnly", {
  5654. /**
  5655. * Gets a up Vector3 that must not be updated
  5656. */
  5657. get: function () {
  5658. return Vector3._UpReadOnly;
  5659. },
  5660. enumerable: true,
  5661. configurable: true
  5662. });
  5663. /**
  5664. * Returns a new Vector3 set to (0.0, -1.0, 0.0)
  5665. * @returns a new down Vector3
  5666. */
  5667. Vector3.Down = function () {
  5668. return new Vector3(0.0, -1.0, 0.0);
  5669. };
  5670. /**
  5671. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  5672. * @returns a new forward Vector3
  5673. */
  5674. Vector3.Forward = function () {
  5675. return new Vector3(0.0, 0.0, 1.0);
  5676. };
  5677. /**
  5678. * Returns a new Vector3 set to (0.0, 0.0, -1.0)
  5679. * @returns a new forward Vector3
  5680. */
  5681. Vector3.Backward = function () {
  5682. return new Vector3(0.0, 0.0, -1.0);
  5683. };
  5684. /**
  5685. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  5686. * @returns a new right Vector3
  5687. */
  5688. Vector3.Right = function () {
  5689. return new Vector3(1.0, 0.0, 0.0);
  5690. };
  5691. /**
  5692. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  5693. * @returns a new left Vector3
  5694. */
  5695. Vector3.Left = function () {
  5696. return new Vector3(-1.0, 0.0, 0.0);
  5697. };
  5698. /**
  5699. * Returns a new Vector3 set with the result of the transformation by the given matrix of the given vector.
  5700. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  5701. * @param vector defines the Vector3 to transform
  5702. * @param transformation defines the transformation matrix
  5703. * @returns the transformed Vector3
  5704. */
  5705. Vector3.TransformCoordinates = function (vector, transformation) {
  5706. var result = Vector3.Zero();
  5707. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  5708. return result;
  5709. };
  5710. /**
  5711. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given vector
  5712. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  5713. * @param vector defines the Vector3 to transform
  5714. * @param transformation defines the transformation matrix
  5715. * @param result defines the Vector3 where to store the result
  5716. */
  5717. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  5718. Vector3.TransformCoordinatesFromFloatsToRef(vector.x, vector.y, vector.z, transformation, result);
  5719. };
  5720. /**
  5721. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given floats (x, y, z)
  5722. * This method computes tranformed coordinates only, not transformed direction vectors
  5723. * @param x define the x coordinate of the source vector
  5724. * @param y define the y coordinate of the source vector
  5725. * @param z define the z coordinate of the source vector
  5726. * @param transformation defines the transformation matrix
  5727. * @param result defines the Vector3 where to store the result
  5728. */
  5729. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  5730. var m = transformation.m;
  5731. var rx = x * m[0] + y * m[4] + z * m[8] + m[12];
  5732. var ry = x * m[1] + y * m[5] + z * m[9] + m[13];
  5733. var rz = x * m[2] + y * m[6] + z * m[10] + m[14];
  5734. var rw = 1 / (x * m[3] + y * m[7] + z * m[11] + m[15]);
  5735. result.x = rx * rw;
  5736. result.y = ry * rw;
  5737. result.z = rz * rw;
  5738. };
  5739. /**
  5740. * Returns a new Vector3 set with the result of the normal transformation by the given matrix of the given vector
  5741. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  5742. * @param vector defines the Vector3 to transform
  5743. * @param transformation defines the transformation matrix
  5744. * @returns the new Vector3
  5745. */
  5746. Vector3.TransformNormal = function (vector, transformation) {
  5747. var result = Vector3.Zero();
  5748. Vector3.TransformNormalToRef(vector, transformation, result);
  5749. return result;
  5750. };
  5751. /**
  5752. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector
  5753. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  5754. * @param vector defines the Vector3 to transform
  5755. * @param transformation defines the transformation matrix
  5756. * @param result defines the Vector3 where to store the result
  5757. */
  5758. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  5759. this.TransformNormalFromFloatsToRef(vector.x, vector.y, vector.z, transformation, result);
  5760. };
  5761. /**
  5762. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z)
  5763. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  5764. * @param x define the x coordinate of the source vector
  5765. * @param y define the y coordinate of the source vector
  5766. * @param z define the z coordinate of the source vector
  5767. * @param transformation defines the transformation matrix
  5768. * @param result defines the Vector3 where to store the result
  5769. */
  5770. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  5771. var m = transformation.m;
  5772. result.x = x * m[0] + y * m[4] + z * m[8];
  5773. result.y = x * m[1] + y * m[5] + z * m[9];
  5774. result.z = x * m[2] + y * m[6] + z * m[10];
  5775. };
  5776. /**
  5777. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  5778. * @param value1 defines the first control point
  5779. * @param value2 defines the second control point
  5780. * @param value3 defines the third control point
  5781. * @param value4 defines the fourth control point
  5782. * @param amount defines the amount on the spline to use
  5783. * @returns the new Vector3
  5784. */
  5785. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  5786. var squared = amount * amount;
  5787. var cubed = amount * squared;
  5788. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  5789. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  5790. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  5791. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  5792. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  5793. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  5794. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  5795. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  5796. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  5797. return new Vector3(x, y, z);
  5798. };
  5799. /**
  5800. * 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"
  5801. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  5802. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  5803. * @param value defines the current value
  5804. * @param min defines the lower range value
  5805. * @param max defines the upper range value
  5806. * @returns the new Vector3
  5807. */
  5808. Vector3.Clamp = function (value, min, max) {
  5809. var v = new Vector3();
  5810. Vector3.ClampToRef(value, min, max, v);
  5811. return v;
  5812. };
  5813. /**
  5814. * Sets the given vector "result" with the coordinates of "value", if the vector "value" is in the cube defined by the vectors "min" and "max"
  5815. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  5816. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  5817. * @param value defines the current value
  5818. * @param min defines the lower range value
  5819. * @param max defines the upper range value
  5820. * @param result defines the Vector3 where to store the result
  5821. */
  5822. Vector3.ClampToRef = function (value, min, max, result) {
  5823. var x = value.x;
  5824. x = (x > max.x) ? max.x : x;
  5825. x = (x < min.x) ? min.x : x;
  5826. var y = value.y;
  5827. y = (y > max.y) ? max.y : y;
  5828. y = (y < min.y) ? min.y : y;
  5829. var z = value.z;
  5830. z = (z > max.z) ? max.z : z;
  5831. z = (z < min.z) ? min.z : z;
  5832. result.copyFromFloats(x, y, z);
  5833. };
  5834. /**
  5835. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  5836. * @param value1 defines the first control point
  5837. * @param tangent1 defines the first tangent vector
  5838. * @param value2 defines the second control point
  5839. * @param tangent2 defines the second tangent vector
  5840. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  5841. * @returns the new Vector3
  5842. */
  5843. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  5844. var squared = amount * amount;
  5845. var cubed = amount * squared;
  5846. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  5847. var part2 = (-2.0 * cubed) + (3.0 * squared);
  5848. var part3 = (cubed - (2.0 * squared)) + amount;
  5849. var part4 = cubed - squared;
  5850. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  5851. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  5852. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  5853. return new Vector3(x, y, z);
  5854. };
  5855. /**
  5856. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  5857. * @param start defines the start value
  5858. * @param end defines the end value
  5859. * @param amount max defines amount between both (between 0 and 1)
  5860. * @returns the new Vector3
  5861. */
  5862. Vector3.Lerp = function (start, end, amount) {
  5863. var result = new Vector3(0, 0, 0);
  5864. Vector3.LerpToRef(start, end, amount, result);
  5865. return result;
  5866. };
  5867. /**
  5868. * Sets the given vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  5869. * @param start defines the start value
  5870. * @param end defines the end value
  5871. * @param amount max defines amount between both (between 0 and 1)
  5872. * @param result defines the Vector3 where to store the result
  5873. */
  5874. Vector3.LerpToRef = function (start, end, amount, result) {
  5875. result.x = start.x + ((end.x - start.x) * amount);
  5876. result.y = start.y + ((end.y - start.y) * amount);
  5877. result.z = start.z + ((end.z - start.z) * amount);
  5878. };
  5879. /**
  5880. * Returns the dot product (float) between the vectors "left" and "right"
  5881. * @param left defines the left operand
  5882. * @param right defines the right operand
  5883. * @returns the dot product
  5884. */
  5885. Vector3.Dot = function (left, right) {
  5886. return (left.x * right.x + left.y * right.y + left.z * right.z);
  5887. };
  5888. /**
  5889. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  5890. * The cross product is then orthogonal to both "left" and "right"
  5891. * @param left defines the left operand
  5892. * @param right defines the right operand
  5893. * @returns the cross product
  5894. */
  5895. Vector3.Cross = function (left, right) {
  5896. var result = Vector3.Zero();
  5897. Vector3.CrossToRef(left, right, result);
  5898. return result;
  5899. };
  5900. /**
  5901. * Sets the given vector "result" with the cross product of "left" and "right"
  5902. * The cross product is then orthogonal to both "left" and "right"
  5903. * @param left defines the left operand
  5904. * @param right defines the right operand
  5905. * @param result defines the Vector3 where to store the result
  5906. */
  5907. Vector3.CrossToRef = function (left, right, result) {
  5908. var x = left.y * right.z - left.z * right.y;
  5909. var y = left.z * right.x - left.x * right.z;
  5910. var z = left.x * right.y - left.y * right.x;
  5911. result.copyFromFloats(x, y, z);
  5912. };
  5913. /**
  5914. * Returns a new Vector3 as the normalization of the given vector
  5915. * @param vector defines the Vector3 to normalize
  5916. * @returns the new Vector3
  5917. */
  5918. Vector3.Normalize = function (vector) {
  5919. var result = Vector3.Zero();
  5920. Vector3.NormalizeToRef(vector, result);
  5921. return result;
  5922. };
  5923. /**
  5924. * Sets the given vector "result" with the normalization of the given first vector
  5925. * @param vector defines the Vector3 to normalize
  5926. * @param result defines the Vector3 where to store the result
  5927. */
  5928. Vector3.NormalizeToRef = function (vector, result) {
  5929. vector.normalizeToRef(result);
  5930. };
  5931. /**
  5932. * Project a Vector3 onto screen space
  5933. * @param vector defines the Vector3 to project
  5934. * @param world defines the world matrix to use
  5935. * @param transform defines the transform (view x projection) matrix to use
  5936. * @param viewport defines the screen viewport to use
  5937. * @returns the new Vector3
  5938. */
  5939. Vector3.Project = function (vector, world, transform, viewport) {
  5940. var cw = viewport.width;
  5941. var ch = viewport.height;
  5942. var cx = viewport.x;
  5943. var cy = viewport.y;
  5944. var viewportMatrix = MathTmp.Matrix[1];
  5945. 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);
  5946. var matrix = MathTmp.Matrix[0];
  5947. world.multiplyToRef(transform, matrix);
  5948. matrix.multiplyToRef(viewportMatrix, matrix);
  5949. return Vector3.TransformCoordinates(vector, matrix);
  5950. };
  5951. /** @hidden */
  5952. Vector3.UnprojectFromInvertedMatrixToRef = function (source, matrix, result) {
  5953. Vector3.TransformCoordinatesToRef(source, matrix, result);
  5954. var m = matrix.m;
  5955. var num = source.x * m[3] + source.y * m[7] + source.z * m[11] + m[15];
  5956. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  5957. result.scaleInPlace(1.0 / num);
  5958. }
  5959. };
  5960. /**
  5961. * Unproject from screen space to object space
  5962. * @param source defines the screen space Vector3 to use
  5963. * @param viewportWidth defines the current width of the viewport
  5964. * @param viewportHeight defines the current height of the viewport
  5965. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  5966. * @param transform defines the transform (view x projection) matrix to use
  5967. * @returns the new Vector3
  5968. */
  5969. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  5970. var matrix = MathTmp.Matrix[0];
  5971. world.multiplyToRef(transform, matrix);
  5972. matrix.invert();
  5973. source.x = source.x / viewportWidth * 2 - 1;
  5974. source.y = -(source.y / viewportHeight * 2 - 1);
  5975. var vector = new Vector3();
  5976. Vector3.UnprojectFromInvertedMatrixToRef(source, matrix, vector);
  5977. return vector;
  5978. };
  5979. /**
  5980. * Unproject from screen space to object space
  5981. * @param source defines the screen space Vector3 to use
  5982. * @param viewportWidth defines the current width of the viewport
  5983. * @param viewportHeight defines the current height of the viewport
  5984. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  5985. * @param view defines the view matrix to use
  5986. * @param projection defines the projection matrix to use
  5987. * @returns the new Vector3
  5988. */
  5989. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  5990. var result = Vector3.Zero();
  5991. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  5992. return result;
  5993. };
  5994. /**
  5995. * Unproject from screen space to object space
  5996. * @param source defines the screen space Vector3 to use
  5997. * @param viewportWidth defines the current width of the viewport
  5998. * @param viewportHeight defines the current height of the viewport
  5999. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  6000. * @param view defines the view matrix to use
  6001. * @param projection defines the projection matrix to use
  6002. * @param result defines the Vector3 where to store the result
  6003. */
  6004. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  6005. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  6006. };
  6007. /**
  6008. * Unproject from screen space to object space
  6009. * @param sourceX defines the screen space x coordinate to use
  6010. * @param sourceY defines the screen space y coordinate to use
  6011. * @param sourceZ defines the screen space z coordinate to use
  6012. * @param viewportWidth defines the current width of the viewport
  6013. * @param viewportHeight defines the current height of the viewport
  6014. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  6015. * @param view defines the view matrix to use
  6016. * @param projection defines the projection matrix to use
  6017. * @param result defines the Vector3 where to store the result
  6018. */
  6019. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  6020. var matrix = MathTmp.Matrix[0];
  6021. world.multiplyToRef(view, matrix);
  6022. matrix.multiplyToRef(projection, matrix);
  6023. matrix.invert();
  6024. var screenSource = MathTmp.Vector3[0];
  6025. screenSource.x = sourceX / viewportWidth * 2 - 1;
  6026. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  6027. screenSource.z = 2 * sourceZ - 1.0;
  6028. Vector3.UnprojectFromInvertedMatrixToRef(screenSource, matrix, result);
  6029. };
  6030. /**
  6031. * Unproject a ray from screen space to object space
  6032. * @param sourceX defines the screen space x coordinate to use
  6033. * @param sourceY defines the screen space y coordinate to use
  6034. * @param viewportWidth defines the current width of the viewport
  6035. * @param viewportHeight defines the current height of the viewport
  6036. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  6037. * @param view defines the view matrix to use
  6038. * @param projection defines the projection matrix to use
  6039. * @param ray defines the Ray where to store the result
  6040. */
  6041. Vector3.UnprojectRayToRef = function (sourceX, sourceY, viewportWidth, viewportHeight, world, view, projection, ray) {
  6042. var matrix = MathTmp.Matrix[0];
  6043. world.multiplyToRef(view, matrix);
  6044. matrix.multiplyToRef(projection, matrix);
  6045. matrix.invert();
  6046. var nearScreenSource = MathTmp.Vector3[0];
  6047. nearScreenSource.x = sourceX / viewportWidth * 2 - 1;
  6048. nearScreenSource.y = -(sourceY / viewportHeight * 2 - 1);
  6049. nearScreenSource.z = -1.0;
  6050. var farScreenSource = MathTmp.Vector3[1].copyFromFloats(nearScreenSource.x, nearScreenSource.y, 1.0);
  6051. var nearVec3 = MathTmp.Vector3[2];
  6052. var farVec3 = MathTmp.Vector3[3];
  6053. Vector3.UnprojectFromInvertedMatrixToRef(nearScreenSource, matrix, nearVec3);
  6054. Vector3.UnprojectFromInvertedMatrixToRef(farScreenSource, matrix, farVec3);
  6055. ray.origin.copyFrom(nearVec3);
  6056. farVec3.subtractToRef(nearVec3, ray.direction);
  6057. ray.direction.normalize();
  6058. };
  6059. /**
  6060. * Gets the minimal coordinate values between two Vector3
  6061. * @param left defines the first operand
  6062. * @param right defines the second operand
  6063. * @returns the new Vector3
  6064. */
  6065. Vector3.Minimize = function (left, right) {
  6066. var min = left.clone();
  6067. min.minimizeInPlace(right);
  6068. return min;
  6069. };
  6070. /**
  6071. * Gets the maximal coordinate values between two Vector3
  6072. * @param left defines the first operand
  6073. * @param right defines the second operand
  6074. * @returns the new Vector3
  6075. */
  6076. Vector3.Maximize = function (left, right) {
  6077. var max = left.clone();
  6078. max.maximizeInPlace(right);
  6079. return max;
  6080. };
  6081. /**
  6082. * Returns the distance between the vectors "value1" and "value2"
  6083. * @param value1 defines the first operand
  6084. * @param value2 defines the second operand
  6085. * @returns the distance
  6086. */
  6087. Vector3.Distance = function (value1, value2) {
  6088. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  6089. };
  6090. /**
  6091. * Returns the squared distance between the vectors "value1" and "value2"
  6092. * @param value1 defines the first operand
  6093. * @param value2 defines the second operand
  6094. * @returns the squared distance
  6095. */
  6096. Vector3.DistanceSquared = function (value1, value2) {
  6097. var x = value1.x - value2.x;
  6098. var y = value1.y - value2.y;
  6099. var z = value1.z - value2.z;
  6100. return (x * x) + (y * y) + (z * z);
  6101. };
  6102. /**
  6103. * Returns a new Vector3 located at the center between "value1" and "value2"
  6104. * @param value1 defines the first operand
  6105. * @param value2 defines the second operand
  6106. * @returns the new Vector3
  6107. */
  6108. Vector3.Center = function (value1, value2) {
  6109. var center = value1.add(value2);
  6110. center.scaleInPlace(0.5);
  6111. return center;
  6112. };
  6113. /**
  6114. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  6115. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  6116. * to something in order to rotate it from its local system to the given target system
  6117. * Note: axis1, axis2 and axis3 are normalized during this operation
  6118. * @param axis1 defines the first axis
  6119. * @param axis2 defines the second axis
  6120. * @param axis3 defines the third axis
  6121. * @returns a new Vector3
  6122. */
  6123. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  6124. var rotation = Vector3.Zero();
  6125. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  6126. return rotation;
  6127. };
  6128. /**
  6129. * The same than RotationFromAxis but updates the given ref Vector3 parameter instead of returning a new Vector3
  6130. * @param axis1 defines the first axis
  6131. * @param axis2 defines the second axis
  6132. * @param axis3 defines the third axis
  6133. * @param ref defines the Vector3 where to store the result
  6134. */
  6135. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  6136. var quat = MathTmp.Quaternion[0];
  6137. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  6138. quat.toEulerAnglesToRef(ref);
  6139. };
  6140. Vector3._UpReadOnly = Vector3.Up();
  6141. return Vector3;
  6142. }());
  6143. BABYLON.Vector3 = Vector3;
  6144. /**
  6145. * Vector4 class created for EulerAngle class conversion to Quaternion
  6146. */
  6147. var Vector4 = /** @class */ (function () {
  6148. /**
  6149. * Creates a Vector4 object from the given floats.
  6150. * @param x x value of the vector
  6151. * @param y y value of the vector
  6152. * @param z z value of the vector
  6153. * @param w w value of the vector
  6154. */
  6155. function Vector4(
  6156. /** x value of the vector */
  6157. x,
  6158. /** y value of the vector */
  6159. y,
  6160. /** z value of the vector */
  6161. z,
  6162. /** w value of the vector */
  6163. w) {
  6164. this.x = x;
  6165. this.y = y;
  6166. this.z = z;
  6167. this.w = w;
  6168. }
  6169. /**
  6170. * Returns the string with the Vector4 coordinates.
  6171. * @returns a string containing all the vector values
  6172. */
  6173. Vector4.prototype.toString = function () {
  6174. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  6175. };
  6176. /**
  6177. * Returns the string "Vector4".
  6178. * @returns "Vector4"
  6179. */
  6180. Vector4.prototype.getClassName = function () {
  6181. return "Vector4";
  6182. };
  6183. /**
  6184. * Returns the Vector4 hash code.
  6185. * @returns a unique hash code
  6186. */
  6187. Vector4.prototype.getHashCode = function () {
  6188. var hash = this.x || 0;
  6189. hash = (hash * 397) ^ (this.y || 0);
  6190. hash = (hash * 397) ^ (this.z || 0);
  6191. hash = (hash * 397) ^ (this.w || 0);
  6192. return hash;
  6193. };
  6194. // Operators
  6195. /**
  6196. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  6197. * @returns the resulting array
  6198. */
  6199. Vector4.prototype.asArray = function () {
  6200. var result = new Array();
  6201. this.toArray(result, 0);
  6202. return result;
  6203. };
  6204. /**
  6205. * Populates the given array from the given index with the Vector4 coordinates.
  6206. * @param array array to populate
  6207. * @param index index of the array to start at (default: 0)
  6208. * @returns the Vector4.
  6209. */
  6210. Vector4.prototype.toArray = function (array, index) {
  6211. if (index === undefined) {
  6212. index = 0;
  6213. }
  6214. array[index] = this.x;
  6215. array[index + 1] = this.y;
  6216. array[index + 2] = this.z;
  6217. array[index + 3] = this.w;
  6218. return this;
  6219. };
  6220. /**
  6221. * Adds the given vector to the current Vector4.
  6222. * @param otherVector the vector to add
  6223. * @returns the updated Vector4.
  6224. */
  6225. Vector4.prototype.addInPlace = function (otherVector) {
  6226. this.x += otherVector.x;
  6227. this.y += otherVector.y;
  6228. this.z += otherVector.z;
  6229. this.w += otherVector.w;
  6230. return this;
  6231. };
  6232. /**
  6233. * Returns a new Vector4 as the result of the addition of the current Vector4 and the given one.
  6234. * @param otherVector the vector to add
  6235. * @returns the resulting vector
  6236. */
  6237. Vector4.prototype.add = function (otherVector) {
  6238. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  6239. };
  6240. /**
  6241. * Updates the given vector "result" with the result of the addition of the current Vector4 and the given one.
  6242. * @param otherVector the vector to add
  6243. * @param result the vector to store the result
  6244. * @returns the current Vector4.
  6245. */
  6246. Vector4.prototype.addToRef = function (otherVector, result) {
  6247. result.x = this.x + otherVector.x;
  6248. result.y = this.y + otherVector.y;
  6249. result.z = this.z + otherVector.z;
  6250. result.w = this.w + otherVector.w;
  6251. return this;
  6252. };
  6253. /**
  6254. * Subtract in place the given vector from the current Vector4.
  6255. * @param otherVector the vector to subtract
  6256. * @returns the updated Vector4.
  6257. */
  6258. Vector4.prototype.subtractInPlace = function (otherVector) {
  6259. this.x -= otherVector.x;
  6260. this.y -= otherVector.y;
  6261. this.z -= otherVector.z;
  6262. this.w -= otherVector.w;
  6263. return this;
  6264. };
  6265. /**
  6266. * Returns a new Vector4 with the result of the subtraction of the given vector from the current Vector4.
  6267. * @param otherVector the vector to add
  6268. * @returns the new vector with the result
  6269. */
  6270. Vector4.prototype.subtract = function (otherVector) {
  6271. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  6272. };
  6273. /**
  6274. * Sets the given vector "result" with the result of the subtraction of the given vector from the current Vector4.
  6275. * @param otherVector the vector to subtract
  6276. * @param result the vector to store the result
  6277. * @returns the current Vector4.
  6278. */
  6279. Vector4.prototype.subtractToRef = function (otherVector, result) {
  6280. result.x = this.x - otherVector.x;
  6281. result.y = this.y - otherVector.y;
  6282. result.z = this.z - otherVector.z;
  6283. result.w = this.w - otherVector.w;
  6284. return this;
  6285. };
  6286. /**
  6287. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  6288. */
  6289. /**
  6290. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  6291. * @param x value to subtract
  6292. * @param y value to subtract
  6293. * @param z value to subtract
  6294. * @param w value to subtract
  6295. * @returns new vector containing the result
  6296. */
  6297. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  6298. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  6299. };
  6300. /**
  6301. * Sets the given vector "result" set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  6302. * @param x value to subtract
  6303. * @param y value to subtract
  6304. * @param z value to subtract
  6305. * @param w value to subtract
  6306. * @param result the vector to store the result in
  6307. * @returns the current Vector4.
  6308. */
  6309. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  6310. result.x = this.x - x;
  6311. result.y = this.y - y;
  6312. result.z = this.z - z;
  6313. result.w = this.w - w;
  6314. return this;
  6315. };
  6316. /**
  6317. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  6318. * @returns a new vector with the negated values
  6319. */
  6320. Vector4.prototype.negate = function () {
  6321. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  6322. };
  6323. /**
  6324. * Multiplies the current Vector4 coordinates by scale (float).
  6325. * @param scale the number to scale with
  6326. * @returns the updated Vector4.
  6327. */
  6328. Vector4.prototype.scaleInPlace = function (scale) {
  6329. this.x *= scale;
  6330. this.y *= scale;
  6331. this.z *= scale;
  6332. this.w *= scale;
  6333. return this;
  6334. };
  6335. /**
  6336. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  6337. * @param scale the number to scale with
  6338. * @returns a new vector with the result
  6339. */
  6340. Vector4.prototype.scale = function (scale) {
  6341. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  6342. };
  6343. /**
  6344. * Sets the given vector "result" with the current Vector4 coordinates multiplied by scale (float).
  6345. * @param scale the number to scale with
  6346. * @param result a vector to store the result in
  6347. * @returns the current Vector4.
  6348. */
  6349. Vector4.prototype.scaleToRef = function (scale, result) {
  6350. result.x = this.x * scale;
  6351. result.y = this.y * scale;
  6352. result.z = this.z * scale;
  6353. result.w = this.w * scale;
  6354. return this;
  6355. };
  6356. /**
  6357. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  6358. * @param scale defines the scale factor
  6359. * @param result defines the Vector4 object where to store the result
  6360. * @returns the unmodified current Vector4
  6361. */
  6362. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  6363. result.x += this.x * scale;
  6364. result.y += this.y * scale;
  6365. result.z += this.z * scale;
  6366. result.w += this.w * scale;
  6367. return this;
  6368. };
  6369. /**
  6370. * Boolean : True if the current Vector4 coordinates are stricly equal to the given ones.
  6371. * @param otherVector the vector to compare against
  6372. * @returns true if they are equal
  6373. */
  6374. Vector4.prototype.equals = function (otherVector) {
  6375. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  6376. };
  6377. /**
  6378. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the given vector ones.
  6379. * @param otherVector vector to compare against
  6380. * @param epsilon (Default: very small number)
  6381. * @returns true if they are equal
  6382. */
  6383. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  6384. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  6385. return otherVector
  6386. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  6387. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  6388. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  6389. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  6390. };
  6391. /**
  6392. * Boolean : True if the given floats are strictly equal to the current Vector4 coordinates.
  6393. * @param x x value to compare against
  6394. * @param y y value to compare against
  6395. * @param z z value to compare against
  6396. * @param w w value to compare against
  6397. * @returns true if equal
  6398. */
  6399. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  6400. return this.x === x && this.y === y && this.z === z && this.w === w;
  6401. };
  6402. /**
  6403. * Multiplies in place the current Vector4 by the given one.
  6404. * @param otherVector vector to multiple with
  6405. * @returns the updated Vector4.
  6406. */
  6407. Vector4.prototype.multiplyInPlace = function (otherVector) {
  6408. this.x *= otherVector.x;
  6409. this.y *= otherVector.y;
  6410. this.z *= otherVector.z;
  6411. this.w *= otherVector.w;
  6412. return this;
  6413. };
  6414. /**
  6415. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the given one.
  6416. * @param otherVector vector to multiple with
  6417. * @returns resulting new vector
  6418. */
  6419. Vector4.prototype.multiply = function (otherVector) {
  6420. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  6421. };
  6422. /**
  6423. * Updates the given vector "result" with the multiplication result of the current Vector4 and the given one.
  6424. * @param otherVector vector to multiple with
  6425. * @param result vector to store the result
  6426. * @returns the current Vector4.
  6427. */
  6428. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  6429. result.x = this.x * otherVector.x;
  6430. result.y = this.y * otherVector.y;
  6431. result.z = this.z * otherVector.z;
  6432. result.w = this.w * otherVector.w;
  6433. return this;
  6434. };
  6435. /**
  6436. * Returns a new Vector4 set with the multiplication result of the given floats and the current Vector4 coordinates.
  6437. * @param x x value multiply with
  6438. * @param y y value multiply with
  6439. * @param z z value multiply with
  6440. * @param w w value multiply with
  6441. * @returns resulting new vector
  6442. */
  6443. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  6444. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  6445. };
  6446. /**
  6447. * Returns a new Vector4 set with the division result of the current Vector4 by the given one.
  6448. * @param otherVector vector to devide with
  6449. * @returns resulting new vector
  6450. */
  6451. Vector4.prototype.divide = function (otherVector) {
  6452. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  6453. };
  6454. /**
  6455. * Updates the given vector "result" with the division result of the current Vector4 by the given one.
  6456. * @param otherVector vector to devide with
  6457. * @param result vector to store the result
  6458. * @returns the current Vector4.
  6459. */
  6460. Vector4.prototype.divideToRef = function (otherVector, result) {
  6461. result.x = this.x / otherVector.x;
  6462. result.y = this.y / otherVector.y;
  6463. result.z = this.z / otherVector.z;
  6464. result.w = this.w / otherVector.w;
  6465. return this;
  6466. };
  6467. /**
  6468. * Divides the current Vector3 coordinates by the given ones.
  6469. * @param otherVector vector to devide with
  6470. * @returns the updated Vector3.
  6471. */
  6472. Vector4.prototype.divideInPlace = function (otherVector) {
  6473. return this.divideToRef(otherVector, this);
  6474. };
  6475. /**
  6476. * Updates the Vector4 coordinates with the minimum values between its own and the given vector ones
  6477. * @param other defines the second operand
  6478. * @returns the current updated Vector4
  6479. */
  6480. Vector4.prototype.minimizeInPlace = function (other) {
  6481. if (other.x < this.x) {
  6482. this.x = other.x;
  6483. }
  6484. if (other.y < this.y) {
  6485. this.y = other.y;
  6486. }
  6487. if (other.z < this.z) {
  6488. this.z = other.z;
  6489. }
  6490. if (other.w < this.w) {
  6491. this.w = other.w;
  6492. }
  6493. return this;
  6494. };
  6495. /**
  6496. * Updates the Vector4 coordinates with the maximum values between its own and the given vector ones
  6497. * @param other defines the second operand
  6498. * @returns the current updated Vector4
  6499. */
  6500. Vector4.prototype.maximizeInPlace = function (other) {
  6501. if (other.x > this.x) {
  6502. this.x = other.x;
  6503. }
  6504. if (other.y > this.y) {
  6505. this.y = other.y;
  6506. }
  6507. if (other.z > this.z) {
  6508. this.z = other.z;
  6509. }
  6510. if (other.w > this.w) {
  6511. this.w = other.w;
  6512. }
  6513. return this;
  6514. };
  6515. /**
  6516. * Gets a new Vector4 from current Vector4 floored values
  6517. * @returns a new Vector4
  6518. */
  6519. Vector4.prototype.floor = function () {
  6520. return new Vector4(Math.floor(this.x), Math.floor(this.y), Math.floor(this.z), Math.floor(this.w));
  6521. };
  6522. /**
  6523. * Gets a new Vector4 from current Vector3 floored values
  6524. * @returns a new Vector4
  6525. */
  6526. Vector4.prototype.fract = function () {
  6527. 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));
  6528. };
  6529. // Properties
  6530. /**
  6531. * Returns the Vector4 length (float).
  6532. * @returns the length
  6533. */
  6534. Vector4.prototype.length = function () {
  6535. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  6536. };
  6537. /**
  6538. * Returns the Vector4 squared length (float).
  6539. * @returns the length squared
  6540. */
  6541. Vector4.prototype.lengthSquared = function () {
  6542. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  6543. };
  6544. // Methods
  6545. /**
  6546. * Normalizes in place the Vector4.
  6547. * @returns the updated Vector4.
  6548. */
  6549. Vector4.prototype.normalize = function () {
  6550. var len = this.length();
  6551. if (len === 0) {
  6552. return this;
  6553. }
  6554. return this.scaleInPlace(1.0 / len);
  6555. };
  6556. /**
  6557. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  6558. * @returns this converted to a new vector3
  6559. */
  6560. Vector4.prototype.toVector3 = function () {
  6561. return new Vector3(this.x, this.y, this.z);
  6562. };
  6563. /**
  6564. * Returns a new Vector4 copied from the current one.
  6565. * @returns the new cloned vector
  6566. */
  6567. Vector4.prototype.clone = function () {
  6568. return new Vector4(this.x, this.y, this.z, this.w);
  6569. };
  6570. /**
  6571. * Updates the current Vector4 with the given one coordinates.
  6572. * @param source the source vector to copy from
  6573. * @returns the updated Vector4.
  6574. */
  6575. Vector4.prototype.copyFrom = function (source) {
  6576. this.x = source.x;
  6577. this.y = source.y;
  6578. this.z = source.z;
  6579. this.w = source.w;
  6580. return this;
  6581. };
  6582. /**
  6583. * Updates the current Vector4 coordinates with the given floats.
  6584. * @param x float to copy from
  6585. * @param y float to copy from
  6586. * @param z float to copy from
  6587. * @param w float to copy from
  6588. * @returns the updated Vector4.
  6589. */
  6590. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  6591. this.x = x;
  6592. this.y = y;
  6593. this.z = z;
  6594. this.w = w;
  6595. return this;
  6596. };
  6597. /**
  6598. * Updates the current Vector4 coordinates with the given floats.
  6599. * @param x float to set from
  6600. * @param y float to set from
  6601. * @param z float to set from
  6602. * @param w float to set from
  6603. * @returns the updated Vector4.
  6604. */
  6605. Vector4.prototype.set = function (x, y, z, w) {
  6606. return this.copyFromFloats(x, y, z, w);
  6607. };
  6608. /**
  6609. * Copies the given float to the current Vector3 coordinates
  6610. * @param v defines the x, y, z and w coordinates of the operand
  6611. * @returns the current updated Vector3
  6612. */
  6613. Vector4.prototype.setAll = function (v) {
  6614. this.x = this.y = this.z = this.w = v;
  6615. return this;
  6616. };
  6617. // Statics
  6618. /**
  6619. * Returns a new Vector4 set from the starting index of the given array.
  6620. * @param array the array to pull values from
  6621. * @param offset the offset into the array to start at
  6622. * @returns the new vector
  6623. */
  6624. Vector4.FromArray = function (array, offset) {
  6625. if (!offset) {
  6626. offset = 0;
  6627. }
  6628. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  6629. };
  6630. /**
  6631. * Updates the given vector "result" from the starting index of the given array.
  6632. * @param array the array to pull values from
  6633. * @param offset the offset into the array to start at
  6634. * @param result the vector to store the result in
  6635. */
  6636. Vector4.FromArrayToRef = function (array, offset, result) {
  6637. result.x = array[offset];
  6638. result.y = array[offset + 1];
  6639. result.z = array[offset + 2];
  6640. result.w = array[offset + 3];
  6641. };
  6642. /**
  6643. * Updates the given vector "result" from the starting index of the given Float32Array.
  6644. * @param array the array to pull values from
  6645. * @param offset the offset into the array to start at
  6646. * @param result the vector to store the result in
  6647. */
  6648. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  6649. Vector4.FromArrayToRef(array, offset, result);
  6650. };
  6651. /**
  6652. * Updates the given vector "result" coordinates from the given floats.
  6653. * @param x float to set from
  6654. * @param y float to set from
  6655. * @param z float to set from
  6656. * @param w float to set from
  6657. * @param result the vector to the floats in
  6658. */
  6659. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  6660. result.x = x;
  6661. result.y = y;
  6662. result.z = z;
  6663. result.w = w;
  6664. };
  6665. /**
  6666. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  6667. * @returns the new vector
  6668. */
  6669. Vector4.Zero = function () {
  6670. return new Vector4(0.0, 0.0, 0.0, 0.0);
  6671. };
  6672. /**
  6673. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  6674. * @returns the new vector
  6675. */
  6676. Vector4.One = function () {
  6677. return new Vector4(1.0, 1.0, 1.0, 1.0);
  6678. };
  6679. /**
  6680. * Returns a new normalized Vector4 from the given one.
  6681. * @param vector the vector to normalize
  6682. * @returns the vector
  6683. */
  6684. Vector4.Normalize = function (vector) {
  6685. var result = Vector4.Zero();
  6686. Vector4.NormalizeToRef(vector, result);
  6687. return result;
  6688. };
  6689. /**
  6690. * Updates the given vector "result" from the normalization of the given one.
  6691. * @param vector the vector to normalize
  6692. * @param result the vector to store the result in
  6693. */
  6694. Vector4.NormalizeToRef = function (vector, result) {
  6695. result.copyFrom(vector);
  6696. result.normalize();
  6697. };
  6698. /**
  6699. * Returns a vector with the minimum values from the left and right vectors
  6700. * @param left left vector to minimize
  6701. * @param right right vector to minimize
  6702. * @returns a new vector with the minimum of the left and right vector values
  6703. */
  6704. Vector4.Minimize = function (left, right) {
  6705. var min = left.clone();
  6706. min.minimizeInPlace(right);
  6707. return min;
  6708. };
  6709. /**
  6710. * Returns a vector with the maximum values from the left and right vectors
  6711. * @param left left vector to maximize
  6712. * @param right right vector to maximize
  6713. * @returns a new vector with the maximum of the left and right vector values
  6714. */
  6715. Vector4.Maximize = function (left, right) {
  6716. var max = left.clone();
  6717. max.maximizeInPlace(right);
  6718. return max;
  6719. };
  6720. /**
  6721. * Returns the distance (float) between the vectors "value1" and "value2".
  6722. * @param value1 value to calulate the distance between
  6723. * @param value2 value to calulate the distance between
  6724. * @return the distance between the two vectors
  6725. */
  6726. Vector4.Distance = function (value1, value2) {
  6727. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  6728. };
  6729. /**
  6730. * Returns the squared distance (float) between the vectors "value1" and "value2".
  6731. * @param value1 value to calulate the distance between
  6732. * @param value2 value to calulate the distance between
  6733. * @return the distance between the two vectors squared
  6734. */
  6735. Vector4.DistanceSquared = function (value1, value2) {
  6736. var x = value1.x - value2.x;
  6737. var y = value1.y - value2.y;
  6738. var z = value1.z - value2.z;
  6739. var w = value1.w - value2.w;
  6740. return (x * x) + (y * y) + (z * z) + (w * w);
  6741. };
  6742. /**
  6743. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  6744. * @param value1 value to calulate the center between
  6745. * @param value2 value to calulate the center between
  6746. * @return the center between the two vectors
  6747. */
  6748. Vector4.Center = function (value1, value2) {
  6749. var center = value1.add(value2);
  6750. center.scaleInPlace(0.5);
  6751. return center;
  6752. };
  6753. /**
  6754. * Returns a new Vector4 set with the result of the normal transformation by the given matrix of the given vector.
  6755. * This methods computes transformed normalized direction vectors only.
  6756. * @param vector the vector to transform
  6757. * @param transformation the transformation matrix to apply
  6758. * @returns the new vector
  6759. */
  6760. Vector4.TransformNormal = function (vector, transformation) {
  6761. var result = Vector4.Zero();
  6762. Vector4.TransformNormalToRef(vector, transformation, result);
  6763. return result;
  6764. };
  6765. /**
  6766. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector.
  6767. * This methods computes transformed normalized direction vectors only.
  6768. * @param vector the vector to transform
  6769. * @param transformation the transformation matrix to apply
  6770. * @param result the vector to store the result in
  6771. */
  6772. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  6773. var m = transformation.m;
  6774. var x = (vector.x * m[0]) + (vector.y * m[4]) + (vector.z * m[8]);
  6775. var y = (vector.x * m[1]) + (vector.y * m[5]) + (vector.z * m[9]);
  6776. var z = (vector.x * m[2]) + (vector.y * m[6]) + (vector.z * m[10]);
  6777. result.x = x;
  6778. result.y = y;
  6779. result.z = z;
  6780. result.w = vector.w;
  6781. };
  6782. /**
  6783. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z, w).
  6784. * This methods computes transformed normalized direction vectors only.
  6785. * @param x value to transform
  6786. * @param y value to transform
  6787. * @param z value to transform
  6788. * @param w value to transform
  6789. * @param transformation the transformation matrix to apply
  6790. * @param result the vector to store the results in
  6791. */
  6792. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  6793. var m = transformation.m;
  6794. result.x = (x * m[0]) + (y * m[4]) + (z * m[8]);
  6795. result.y = (x * m[1]) + (y * m[5]) + (z * m[9]);
  6796. result.z = (x * m[2]) + (y * m[6]) + (z * m[10]);
  6797. result.w = w;
  6798. };
  6799. /**
  6800. * Creates a new Vector4 from a Vector3
  6801. * @param source defines the source data
  6802. * @param w defines the 4th component (default is 0)
  6803. * @returns a new Vector4
  6804. */
  6805. Vector4.FromVector3 = function (source, w) {
  6806. if (w === void 0) { w = 0; }
  6807. return new Vector4(source.x, source.y, source.z, w);
  6808. };
  6809. return Vector4;
  6810. }());
  6811. BABYLON.Vector4 = Vector4;
  6812. /**
  6813. * Size containing widht and height
  6814. */
  6815. var Size = /** @class */ (function () {
  6816. /**
  6817. * Creates a Size object from the given width and height (floats).
  6818. * @param width width of the new size
  6819. * @param height height of the new size
  6820. */
  6821. function Size(width, height) {
  6822. this.width = width;
  6823. this.height = height;
  6824. }
  6825. /**
  6826. * Returns a string with the Size width and height
  6827. * @returns a string with the Size width and height
  6828. */
  6829. Size.prototype.toString = function () {
  6830. return "{W: " + this.width + ", H: " + this.height + "}";
  6831. };
  6832. /**
  6833. * "Size"
  6834. * @returns the string "Size"
  6835. */
  6836. Size.prototype.getClassName = function () {
  6837. return "Size";
  6838. };
  6839. /**
  6840. * Returns the Size hash code.
  6841. * @returns a hash code for a unique width and height
  6842. */
  6843. Size.prototype.getHashCode = function () {
  6844. var hash = this.width || 0;
  6845. hash = (hash * 397) ^ (this.height || 0);
  6846. return hash;
  6847. };
  6848. /**
  6849. * Updates the current size from the given one.
  6850. * @param src the given size
  6851. */
  6852. Size.prototype.copyFrom = function (src) {
  6853. this.width = src.width;
  6854. this.height = src.height;
  6855. };
  6856. /**
  6857. * Updates in place the current Size from the given floats.
  6858. * @param width width of the new size
  6859. * @param height height of the new size
  6860. * @returns the updated Size.
  6861. */
  6862. Size.prototype.copyFromFloats = function (width, height) {
  6863. this.width = width;
  6864. this.height = height;
  6865. return this;
  6866. };
  6867. /**
  6868. * Updates in place the current Size from the given floats.
  6869. * @param width width to set
  6870. * @param height height to set
  6871. * @returns the updated Size.
  6872. */
  6873. Size.prototype.set = function (width, height) {
  6874. return this.copyFromFloats(width, height);
  6875. };
  6876. /**
  6877. * Multiplies the width and height by numbers
  6878. * @param w factor to multiple the width by
  6879. * @param h factor to multiple the height by
  6880. * @returns a new Size set with the multiplication result of the current Size and the given floats.
  6881. */
  6882. Size.prototype.multiplyByFloats = function (w, h) {
  6883. return new Size(this.width * w, this.height * h);
  6884. };
  6885. /**
  6886. * Clones the size
  6887. * @returns a new Size copied from the given one.
  6888. */
  6889. Size.prototype.clone = function () {
  6890. return new Size(this.width, this.height);
  6891. };
  6892. /**
  6893. * True if the current Size and the given one width and height are strictly equal.
  6894. * @param other the other size to compare against
  6895. * @returns True if the current Size and the given one width and height are strictly equal.
  6896. */
  6897. Size.prototype.equals = function (other) {
  6898. if (!other) {
  6899. return false;
  6900. }
  6901. return (this.width === other.width) && (this.height === other.height);
  6902. };
  6903. Object.defineProperty(Size.prototype, "surface", {
  6904. /**
  6905. * The surface of the Size : width * height (float).
  6906. */
  6907. get: function () {
  6908. return this.width * this.height;
  6909. },
  6910. enumerable: true,
  6911. configurable: true
  6912. });
  6913. /**
  6914. * Create a new size of zero
  6915. * @returns a new Size set to (0.0, 0.0)
  6916. */
  6917. Size.Zero = function () {
  6918. return new Size(0.0, 0.0);
  6919. };
  6920. /**
  6921. * Sums the width and height of two sizes
  6922. * @param otherSize size to add to this size
  6923. * @returns a new Size set as the addition result of the current Size and the given one.
  6924. */
  6925. Size.prototype.add = function (otherSize) {
  6926. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  6927. return r;
  6928. };
  6929. /**
  6930. * Subtracts the width and height of two
  6931. * @param otherSize size to subtract to this size
  6932. * @returns a new Size set as the subtraction result of the given one from the current Size.
  6933. */
  6934. Size.prototype.subtract = function (otherSize) {
  6935. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  6936. return r;
  6937. };
  6938. /**
  6939. * Creates a new Size set at the linear interpolation "amount" between "start" and "end"
  6940. * @param start starting size to lerp between
  6941. * @param end end size to lerp between
  6942. * @param amount amount to lerp between the start and end values
  6943. * @returns a new Size set at the linear interpolation "amount" between "start" and "end"
  6944. */
  6945. Size.Lerp = function (start, end, amount) {
  6946. var w = start.width + ((end.width - start.width) * amount);
  6947. var h = start.height + ((end.height - start.height) * amount);
  6948. return new Size(w, h);
  6949. };
  6950. return Size;
  6951. }());
  6952. BABYLON.Size = Size;
  6953. /**
  6954. * Class used to store quaternion data
  6955. * @see https://en.wikipedia.org/wiki/Quaternion
  6956. * @see http://doc.babylonjs.com/features/position,_rotation,_scaling
  6957. */
  6958. var Quaternion = /** @class */ (function () {
  6959. /**
  6960. * Creates a new Quaternion from the given floats
  6961. * @param x defines the first component (0 by default)
  6962. * @param y defines the second component (0 by default)
  6963. * @param z defines the third component (0 by default)
  6964. * @param w defines the fourth component (1.0 by default)
  6965. */
  6966. function Quaternion(
  6967. /** defines the first component (0 by default) */
  6968. x,
  6969. /** defines the second component (0 by default) */
  6970. y,
  6971. /** defines the third component (0 by default) */
  6972. z,
  6973. /** defines the fourth component (1.0 by default) */
  6974. w) {
  6975. if (x === void 0) { x = 0.0; }
  6976. if (y === void 0) { y = 0.0; }
  6977. if (z === void 0) { z = 0.0; }
  6978. if (w === void 0) { w = 1.0; }
  6979. this.x = x;
  6980. this.y = y;
  6981. this.z = z;
  6982. this.w = w;
  6983. }
  6984. /**
  6985. * Gets a string representation for the current quaternion
  6986. * @returns a string with the Quaternion coordinates
  6987. */
  6988. Quaternion.prototype.toString = function () {
  6989. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  6990. };
  6991. /**
  6992. * Gets the class name of the quaternion
  6993. * @returns the string "Quaternion"
  6994. */
  6995. Quaternion.prototype.getClassName = function () {
  6996. return "Quaternion";
  6997. };
  6998. /**
  6999. * Gets a hash code for this quaternion
  7000. * @returns the quaternion hash code
  7001. */
  7002. Quaternion.prototype.getHashCode = function () {
  7003. var hash = this.x || 0;
  7004. hash = (hash * 397) ^ (this.y || 0);
  7005. hash = (hash * 397) ^ (this.z || 0);
  7006. hash = (hash * 397) ^ (this.w || 0);
  7007. return hash;
  7008. };
  7009. /**
  7010. * Copy the quaternion to an array
  7011. * @returns a new array populated with 4 elements from the quaternion coordinates
  7012. */
  7013. Quaternion.prototype.asArray = function () {
  7014. return [this.x, this.y, this.z, this.w];
  7015. };
  7016. /**
  7017. * Check if two quaternions are equals
  7018. * @param otherQuaternion defines the second operand
  7019. * @return true if the current quaternion and the given one coordinates are strictly equals
  7020. */
  7021. Quaternion.prototype.equals = function (otherQuaternion) {
  7022. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  7023. };
  7024. /**
  7025. * Clone the current quaternion
  7026. * @returns a new quaternion copied from the current one
  7027. */
  7028. Quaternion.prototype.clone = function () {
  7029. return new Quaternion(this.x, this.y, this.z, this.w);
  7030. };
  7031. /**
  7032. * Copy a quaternion to the current one
  7033. * @param other defines the other quaternion
  7034. * @returns the updated current quaternion
  7035. */
  7036. Quaternion.prototype.copyFrom = function (other) {
  7037. this.x = other.x;
  7038. this.y = other.y;
  7039. this.z = other.z;
  7040. this.w = other.w;
  7041. return this;
  7042. };
  7043. /**
  7044. * Updates the current quaternion with the given float coordinates
  7045. * @param x defines the x coordinate
  7046. * @param y defines the y coordinate
  7047. * @param z defines the z coordinate
  7048. * @param w defines the w coordinate
  7049. * @returns the updated current quaternion
  7050. */
  7051. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  7052. this.x = x;
  7053. this.y = y;
  7054. this.z = z;
  7055. this.w = w;
  7056. return this;
  7057. };
  7058. /**
  7059. * Updates the current quaternion from the given float coordinates
  7060. * @param x defines the x coordinate
  7061. * @param y defines the y coordinate
  7062. * @param z defines the z coordinate
  7063. * @param w defines the w coordinate
  7064. * @returns the updated current quaternion
  7065. */
  7066. Quaternion.prototype.set = function (x, y, z, w) {
  7067. return this.copyFromFloats(x, y, z, w);
  7068. };
  7069. /**
  7070. * Adds two quaternions
  7071. * @param other defines the second operand
  7072. * @returns a new quaternion as the addition result of the given one and the current quaternion
  7073. */
  7074. Quaternion.prototype.add = function (other) {
  7075. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  7076. };
  7077. /**
  7078. * Add a quaternion to the current one
  7079. * @param other defines the quaternion to add
  7080. * @returns the current quaternion
  7081. */
  7082. Quaternion.prototype.addInPlace = function (other) {
  7083. this.x += other.x;
  7084. this.y += other.y;
  7085. this.z += other.z;
  7086. this.w += other.w;
  7087. return this;
  7088. };
  7089. /**
  7090. * Subtract two quaternions
  7091. * @param other defines the second operand
  7092. * @returns a new quaternion as the subtraction result of the given one from the current one
  7093. */
  7094. Quaternion.prototype.subtract = function (other) {
  7095. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  7096. };
  7097. /**
  7098. * Multiplies the current quaternion by a scale factor
  7099. * @param value defines the scale factor
  7100. * @returns a new quaternion set by multiplying the current quaternion coordinates by the float "scale"
  7101. */
  7102. Quaternion.prototype.scale = function (value) {
  7103. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  7104. };
  7105. /**
  7106. * Scale the current quaternion values by a factor and stores the result to a given quaternion
  7107. * @param scale defines the scale factor
  7108. * @param result defines the Quaternion object where to store the result
  7109. * @returns the unmodified current quaternion
  7110. */
  7111. Quaternion.prototype.scaleToRef = function (scale, result) {
  7112. result.x = this.x * scale;
  7113. result.y = this.y * scale;
  7114. result.z = this.z * scale;
  7115. result.w = this.w * scale;
  7116. return this;
  7117. };
  7118. /**
  7119. * Multiplies in place the current quaternion by a scale factor
  7120. * @param value defines the scale factor
  7121. * @returns the current modified quaternion
  7122. */
  7123. Quaternion.prototype.scaleInPlace = function (value) {
  7124. this.x *= value;
  7125. this.y *= value;
  7126. this.z *= value;
  7127. this.w *= value;
  7128. return this;
  7129. };
  7130. /**
  7131. * Scale the current quaternion values by a factor and add the result to a given quaternion
  7132. * @param scale defines the scale factor
  7133. * @param result defines the Quaternion object where to store the result
  7134. * @returns the unmodified current quaternion
  7135. */
  7136. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  7137. result.x += this.x * scale;
  7138. result.y += this.y * scale;
  7139. result.z += this.z * scale;
  7140. result.w += this.w * scale;
  7141. return this;
  7142. };
  7143. /**
  7144. * Multiplies two quaternions
  7145. * @param q1 defines the second operand
  7146. * @returns a new quaternion set as the multiplication result of the current one with the given one "q1"
  7147. */
  7148. Quaternion.prototype.multiply = function (q1) {
  7149. var result = new Quaternion(0, 0, 0, 1.0);
  7150. this.multiplyToRef(q1, result);
  7151. return result;
  7152. };
  7153. /**
  7154. * Sets the given "result" as the the multiplication result of the current one with the given one "q1"
  7155. * @param q1 defines the second operand
  7156. * @param result defines the target quaternion
  7157. * @returns the current quaternion
  7158. */
  7159. Quaternion.prototype.multiplyToRef = function (q1, result) {
  7160. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  7161. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  7162. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  7163. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  7164. result.copyFromFloats(x, y, z, w);
  7165. return this;
  7166. };
  7167. /**
  7168. * Updates the current quaternion with the multiplication of itself with the given one "q1"
  7169. * @param q1 defines the second operand
  7170. * @returns the currentupdated quaternion
  7171. */
  7172. Quaternion.prototype.multiplyInPlace = function (q1) {
  7173. this.multiplyToRef(q1, this);
  7174. return this;
  7175. };
  7176. /**
  7177. * Conjugates (1-q) the current quaternion and stores the result in the given quaternion
  7178. * @param ref defines the target quaternion
  7179. * @returns the current quaternion
  7180. */
  7181. Quaternion.prototype.conjugateToRef = function (ref) {
  7182. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  7183. return this;
  7184. };
  7185. /**
  7186. * Conjugates in place (1-q) the current quaternion
  7187. * @returns the current updated quaternion
  7188. */
  7189. Quaternion.prototype.conjugateInPlace = function () {
  7190. this.x *= -1;
  7191. this.y *= -1;
  7192. this.z *= -1;
  7193. return this;
  7194. };
  7195. /**
  7196. * Conjugates in place (1-q) the current quaternion
  7197. * @returns a new quaternion
  7198. */
  7199. Quaternion.prototype.conjugate = function () {
  7200. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  7201. return result;
  7202. };
  7203. /**
  7204. * Gets length of current quaternion
  7205. * @returns the quaternion length (float)
  7206. */
  7207. Quaternion.prototype.length = function () {
  7208. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  7209. };
  7210. /**
  7211. * Normalize in place the current quaternion
  7212. * @returns the current updated quaternion
  7213. */
  7214. Quaternion.prototype.normalize = function () {
  7215. var length = 1.0 / this.length();
  7216. this.x *= length;
  7217. this.y *= length;
  7218. this.z *= length;
  7219. this.w *= length;
  7220. return this;
  7221. };
  7222. /**
  7223. * Returns a new Vector3 set with the Euler angles translated from the current quaternion
  7224. * @param order is a reserved parameter and is ignore for now
  7225. * @returns a new Vector3 containing the Euler angles
  7226. */
  7227. Quaternion.prototype.toEulerAngles = function (order) {
  7228. if (order === void 0) { order = "YZX"; }
  7229. var result = Vector3.Zero();
  7230. this.toEulerAnglesToRef(result, order);
  7231. return result;
  7232. };
  7233. /**
  7234. * Sets the given vector3 "result" with the Euler angles translated from the current quaternion
  7235. * @param result defines the vector which will be filled with the Euler angles
  7236. * @param order is a reserved parameter and is ignore for now
  7237. * @returns the current unchanged quaternion
  7238. */
  7239. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  7240. if (order === void 0) { order = "YZX"; }
  7241. var qz = this.z;
  7242. var qx = this.x;
  7243. var qy = this.y;
  7244. var qw = this.w;
  7245. var sqw = qw * qw;
  7246. var sqz = qz * qz;
  7247. var sqx = qx * qx;
  7248. var sqy = qy * qy;
  7249. var zAxisY = qy * qz - qx * qw;
  7250. var limit = .4999999;
  7251. if (zAxisY < -limit) {
  7252. result.y = 2 * Math.atan2(qy, qw);
  7253. result.x = Math.PI / 2;
  7254. result.z = 0;
  7255. }
  7256. else if (zAxisY > limit) {
  7257. result.y = 2 * Math.atan2(qy, qw);
  7258. result.x = -Math.PI / 2;
  7259. result.z = 0;
  7260. }
  7261. else {
  7262. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  7263. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  7264. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  7265. }
  7266. return this;
  7267. };
  7268. /**
  7269. * Updates the given rotation matrix with the current quaternion values
  7270. * @param result defines the target matrix
  7271. * @returns the current unchanged quaternion
  7272. */
  7273. Quaternion.prototype.toRotationMatrix = function (result) {
  7274. Matrix.FromQuaternionToRef(this, result);
  7275. return this;
  7276. };
  7277. /**
  7278. * Updates the current quaternion from the given rotation matrix values
  7279. * @param matrix defines the source matrix
  7280. * @returns the current updated quaternion
  7281. */
  7282. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  7283. Quaternion.FromRotationMatrixToRef(matrix, this);
  7284. return this;
  7285. };
  7286. // Statics
  7287. /**
  7288. * Creates a new quaternion from a rotation matrix
  7289. * @param matrix defines the source matrix
  7290. * @returns a new quaternion created from the given rotation matrix values
  7291. */
  7292. Quaternion.FromRotationMatrix = function (matrix) {
  7293. var result = new Quaternion();
  7294. Quaternion.FromRotationMatrixToRef(matrix, result);
  7295. return result;
  7296. };
  7297. /**
  7298. * Updates the given quaternion with the given rotation matrix values
  7299. * @param matrix defines the source matrix
  7300. * @param result defines the target quaternion
  7301. */
  7302. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  7303. var data = matrix.m;
  7304. var m11 = data[0], m12 = data[4], m13 = data[8];
  7305. var m21 = data[1], m22 = data[5], m23 = data[9];
  7306. var m31 = data[2], m32 = data[6], m33 = data[10];
  7307. var trace = m11 + m22 + m33;
  7308. var s;
  7309. if (trace > 0) {
  7310. s = 0.5 / Math.sqrt(trace + 1.0);
  7311. result.w = 0.25 / s;
  7312. result.x = (m32 - m23) * s;
  7313. result.y = (m13 - m31) * s;
  7314. result.z = (m21 - m12) * s;
  7315. }
  7316. else if (m11 > m22 && m11 > m33) {
  7317. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  7318. result.w = (m32 - m23) / s;
  7319. result.x = 0.25 * s;
  7320. result.y = (m12 + m21) / s;
  7321. result.z = (m13 + m31) / s;
  7322. }
  7323. else if (m22 > m33) {
  7324. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  7325. result.w = (m13 - m31) / s;
  7326. result.x = (m12 + m21) / s;
  7327. result.y = 0.25 * s;
  7328. result.z = (m23 + m32) / s;
  7329. }
  7330. else {
  7331. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  7332. result.w = (m21 - m12) / s;
  7333. result.x = (m13 + m31) / s;
  7334. result.y = (m23 + m32) / s;
  7335. result.z = 0.25 * s;
  7336. }
  7337. };
  7338. /**
  7339. * Returns the dot product (float) between the quaternions "left" and "right"
  7340. * @param left defines the left operand
  7341. * @param right defines the right operand
  7342. * @returns the dot product
  7343. */
  7344. Quaternion.Dot = function (left, right) {
  7345. return (left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w);
  7346. };
  7347. /**
  7348. * Checks if the two quaternions are close to each other
  7349. * @param quat0 defines the first quaternion to check
  7350. * @param quat1 defines the second quaternion to check
  7351. * @returns true if the two quaternions are close to each other
  7352. */
  7353. Quaternion.AreClose = function (quat0, quat1) {
  7354. var dot = Quaternion.Dot(quat0, quat1);
  7355. return dot >= 0;
  7356. };
  7357. /**
  7358. * Creates an empty quaternion
  7359. * @returns a new quaternion set to (0.0, 0.0, 0.0)
  7360. */
  7361. Quaternion.Zero = function () {
  7362. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  7363. };
  7364. /**
  7365. * Inverse a given quaternion
  7366. * @param q defines the source quaternion
  7367. * @returns a new quaternion as the inverted current quaternion
  7368. */
  7369. Quaternion.Inverse = function (q) {
  7370. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  7371. };
  7372. /**
  7373. * Inverse a given quaternion
  7374. * @param q defines the source quaternion
  7375. * @param result the quaternion the result will be stored in
  7376. * @returns the result quaternion
  7377. */
  7378. Quaternion.InverseToRef = function (q, result) {
  7379. result.set(-q.x, -q.y, -q.z, q.w);
  7380. return result;
  7381. };
  7382. /**
  7383. * Creates an identity quaternion
  7384. * @returns the identity quaternion
  7385. */
  7386. Quaternion.Identity = function () {
  7387. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  7388. };
  7389. /**
  7390. * Gets a boolean indicating if the given quaternion is identity
  7391. * @param quaternion defines the quaternion to check
  7392. * @returns true if the quaternion is identity
  7393. */
  7394. Quaternion.IsIdentity = function (quaternion) {
  7395. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  7396. };
  7397. /**
  7398. * Creates a quaternion from a rotation around an axis
  7399. * @param axis defines the axis to use
  7400. * @param angle defines the angle to use
  7401. * @returns a new quaternion created from the given axis (Vector3) and angle in radians (float)
  7402. */
  7403. Quaternion.RotationAxis = function (axis, angle) {
  7404. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  7405. };
  7406. /**
  7407. * Creates a rotation around an axis and stores it into the given quaternion
  7408. * @param axis defines the axis to use
  7409. * @param angle defines the angle to use
  7410. * @param result defines the target quaternion
  7411. * @returns the target quaternion
  7412. */
  7413. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  7414. var sin = Math.sin(angle / 2);
  7415. axis.normalize();
  7416. result.w = Math.cos(angle / 2);
  7417. result.x = axis.x * sin;
  7418. result.y = axis.y * sin;
  7419. result.z = axis.z * sin;
  7420. return result;
  7421. };
  7422. /**
  7423. * Creates a new quaternion from data stored into an array
  7424. * @param array defines the data source
  7425. * @param offset defines the offset in the source array where the data starts
  7426. * @returns a new quaternion
  7427. */
  7428. Quaternion.FromArray = function (array, offset) {
  7429. if (!offset) {
  7430. offset = 0;
  7431. }
  7432. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  7433. };
  7434. /**
  7435. * Create a quaternion from Euler rotation angles
  7436. * @param x Pitch
  7437. * @param y Yaw
  7438. * @param z Roll
  7439. * @returns the new Quaternion
  7440. */
  7441. Quaternion.FromEulerAngles = function (x, y, z) {
  7442. var q = new Quaternion();
  7443. Quaternion.RotationYawPitchRollToRef(y, x, z, q);
  7444. return q;
  7445. };
  7446. /**
  7447. * Updates a quaternion from Euler rotation angles
  7448. * @param x Pitch
  7449. * @param y Yaw
  7450. * @param z Roll
  7451. * @param result the quaternion to store the result
  7452. * @returns the updated quaternion
  7453. */
  7454. Quaternion.FromEulerAnglesToRef = function (x, y, z, result) {
  7455. Quaternion.RotationYawPitchRollToRef(y, x, z, result);
  7456. return result;
  7457. };
  7458. /**
  7459. * Create a quaternion from Euler rotation vector
  7460. * @param vec the Euler vector (x Pitch, y Yaw, z Roll)
  7461. * @returns the new Quaternion
  7462. */
  7463. Quaternion.FromEulerVector = function (vec) {
  7464. var q = new Quaternion();
  7465. Quaternion.RotationYawPitchRollToRef(vec.y, vec.x, vec.z, q);
  7466. return q;
  7467. };
  7468. /**
  7469. * Updates a quaternion from Euler rotation vector
  7470. * @param vec the Euler vector (x Pitch, y Yaw, z Roll)
  7471. * @param result the quaternion to store the result
  7472. * @returns the updated quaternion
  7473. */
  7474. Quaternion.FromEulerVectorToRef = function (vec, result) {
  7475. Quaternion.RotationYawPitchRollToRef(vec.y, vec.x, vec.z, result);
  7476. return result;
  7477. };
  7478. /**
  7479. * Creates a new quaternion from the given Euler float angles (y, x, z)
  7480. * @param yaw defines the rotation around Y axis
  7481. * @param pitch defines the rotation around X axis
  7482. * @param roll defines the rotation around Z axis
  7483. * @returns the new quaternion
  7484. */
  7485. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  7486. var q = new Quaternion();
  7487. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  7488. return q;
  7489. };
  7490. /**
  7491. * Creates a new rotation from the given Euler float angles (y, x, z) and stores it in the target quaternion
  7492. * @param yaw defines the rotation around Y axis
  7493. * @param pitch defines the rotation around X axis
  7494. * @param roll defines the rotation around Z axis
  7495. * @param result defines the target quaternion
  7496. */
  7497. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  7498. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  7499. var halfRoll = roll * 0.5;
  7500. var halfPitch = pitch * 0.5;
  7501. var halfYaw = yaw * 0.5;
  7502. var sinRoll = Math.sin(halfRoll);
  7503. var cosRoll = Math.cos(halfRoll);
  7504. var sinPitch = Math.sin(halfPitch);
  7505. var cosPitch = Math.cos(halfPitch);
  7506. var sinYaw = Math.sin(halfYaw);
  7507. var cosYaw = Math.cos(halfYaw);
  7508. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  7509. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  7510. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  7511. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  7512. };
  7513. /**
  7514. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation
  7515. * @param alpha defines the rotation around first axis
  7516. * @param beta defines the rotation around second axis
  7517. * @param gamma defines the rotation around third axis
  7518. * @returns the new quaternion
  7519. */
  7520. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  7521. var result = new Quaternion();
  7522. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  7523. return result;
  7524. };
  7525. /**
  7526. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation and stores it in the target quaternion
  7527. * @param alpha defines the rotation around first axis
  7528. * @param beta defines the rotation around second axis
  7529. * @param gamma defines the rotation around third axis
  7530. * @param result defines the target quaternion
  7531. */
  7532. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  7533. // Produces a quaternion from Euler angles in the z-x-z orientation
  7534. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  7535. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  7536. var halfBeta = beta * 0.5;
  7537. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  7538. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  7539. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  7540. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  7541. };
  7542. /**
  7543. * 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)
  7544. * @param axis1 defines the first axis
  7545. * @param axis2 defines the second axis
  7546. * @param axis3 defines the third axis
  7547. * @returns the new quaternion
  7548. */
  7549. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3) {
  7550. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  7551. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  7552. return quat;
  7553. };
  7554. /**
  7555. * 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
  7556. * @param axis1 defines the first axis
  7557. * @param axis2 defines the second axis
  7558. * @param axis3 defines the third axis
  7559. * @param ref defines the target quaternion
  7560. */
  7561. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  7562. var rotMat = MathTmp.Matrix[0];
  7563. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  7564. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  7565. };
  7566. /**
  7567. * Interpolates between two quaternions
  7568. * @param left defines first quaternion
  7569. * @param right defines second quaternion
  7570. * @param amount defines the gradient to use
  7571. * @returns the new interpolated quaternion
  7572. */
  7573. Quaternion.Slerp = function (left, right, amount) {
  7574. var result = Quaternion.Identity();
  7575. Quaternion.SlerpToRef(left, right, amount, result);
  7576. return result;
  7577. };
  7578. /**
  7579. * Interpolates between two quaternions and stores it into a target quaternion
  7580. * @param left defines first quaternion
  7581. * @param right defines second quaternion
  7582. * @param amount defines the gradient to use
  7583. * @param result defines the target quaternion
  7584. */
  7585. Quaternion.SlerpToRef = function (left, right, amount, result) {
  7586. var num2;
  7587. var num3;
  7588. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  7589. var flag = false;
  7590. if (num4 < 0) {
  7591. flag = true;
  7592. num4 = -num4;
  7593. }
  7594. if (num4 > 0.999999) {
  7595. num3 = 1 - amount;
  7596. num2 = flag ? -amount : amount;
  7597. }
  7598. else {
  7599. var num5 = Math.acos(num4);
  7600. var num6 = (1.0 / Math.sin(num5));
  7601. num3 = (Math.sin((1.0 - amount) * num5)) * num6;
  7602. num2 = flag ? ((-Math.sin(amount * num5)) * num6) : ((Math.sin(amount * num5)) * num6);
  7603. }
  7604. result.x = (num3 * left.x) + (num2 * right.x);
  7605. result.y = (num3 * left.y) + (num2 * right.y);
  7606. result.z = (num3 * left.z) + (num2 * right.z);
  7607. result.w = (num3 * left.w) + (num2 * right.w);
  7608. };
  7609. /**
  7610. * Interpolate between two quaternions using Hermite interpolation
  7611. * @param value1 defines first quaternion
  7612. * @param tangent1 defines the incoming tangent
  7613. * @param value2 defines second quaternion
  7614. * @param tangent2 defines the outgoing tangent
  7615. * @param amount defines the target quaternion
  7616. * @returns the new interpolated quaternion
  7617. */
  7618. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  7619. var squared = amount * amount;
  7620. var cubed = amount * squared;
  7621. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  7622. var part2 = (-2.0 * cubed) + (3.0 * squared);
  7623. var part3 = (cubed - (2.0 * squared)) + amount;
  7624. var part4 = cubed - squared;
  7625. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  7626. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  7627. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  7628. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  7629. return new Quaternion(x, y, z, w);
  7630. };
  7631. return Quaternion;
  7632. }());
  7633. BABYLON.Quaternion = Quaternion;
  7634. /**
  7635. * Class used to store matrix data (4x4)
  7636. */
  7637. var Matrix = /** @class */ (function () {
  7638. /**
  7639. * Creates an empty matrix (filled with zeros)
  7640. */
  7641. function Matrix() {
  7642. this._isIdentity = false;
  7643. this._isIdentityDirty = true;
  7644. this._isIdentity3x2 = true;
  7645. this._isIdentity3x2Dirty = true;
  7646. this._m = new Float32Array(16);
  7647. this._updateIdentityStatus(false);
  7648. }
  7649. Object.defineProperty(Matrix.prototype, "m", {
  7650. /**
  7651. * Gets the internal data of the matrix
  7652. */
  7653. get: function () { return this._m; },
  7654. enumerable: true,
  7655. configurable: true
  7656. });
  7657. /** @hidden */
  7658. Matrix.prototype._markAsUpdated = function () {
  7659. this.updateFlag = Matrix._updateFlagSeed++;
  7660. this._isIdentity = false;
  7661. this._isIdentity3x2 = false;
  7662. this._isIdentityDirty = true;
  7663. this._isIdentity3x2Dirty = true;
  7664. };
  7665. /** @hidden */
  7666. Matrix.prototype._updateIdentityStatus = function (isIdentity, isIdentityDirty, isIdentity3x2, isIdentity3x2Dirty) {
  7667. if (isIdentityDirty === void 0) { isIdentityDirty = false; }
  7668. if (isIdentity3x2 === void 0) { isIdentity3x2 = false; }
  7669. if (isIdentity3x2Dirty === void 0) { isIdentity3x2Dirty = true; }
  7670. this.updateFlag = Matrix._updateFlagSeed++;
  7671. this._isIdentity = isIdentity;
  7672. this._isIdentity3x2 = isIdentity || isIdentity3x2;
  7673. this._isIdentityDirty = this._isIdentity ? false : isIdentityDirty;
  7674. this._isIdentity3x2Dirty = this._isIdentity3x2 ? false : isIdentity3x2Dirty;
  7675. };
  7676. // Properties
  7677. /**
  7678. * Check if the current matrix is identity
  7679. * @returns true is the matrix is the identity matrix
  7680. */
  7681. Matrix.prototype.isIdentity = function () {
  7682. if (this._isIdentityDirty) {
  7683. this._isIdentityDirty = false;
  7684. var m = this._m;
  7685. this._isIdentity = (m[0] === 1.0 && m[1] === 0.0 && m[2] === 0.0 && m[3] === 0.0 &&
  7686. m[4] === 0.0 && m[5] === 1.0 && m[6] === 0.0 && m[7] === 0.0 &&
  7687. m[8] === 0.0 && m[9] === 0.0 && m[10] === 1.0 && m[11] === 0.0 &&
  7688. m[12] === 0.0 && m[13] === 0.0 && m[14] === 0.0 && m[15] === 1.0);
  7689. }
  7690. return this._isIdentity;
  7691. };
  7692. /**
  7693. * Check if the current matrix is identity as a texture matrix (3x2 store in 4x4)
  7694. * @returns true is the matrix is the identity matrix
  7695. */
  7696. Matrix.prototype.isIdentityAs3x2 = function () {
  7697. if (this._isIdentity3x2Dirty) {
  7698. this._isIdentity3x2Dirty = false;
  7699. if (this._m[0] !== 1.0 || this._m[5] !== 1.0 || this._m[15] !== 1.0) {
  7700. this._isIdentity3x2 = false;
  7701. }
  7702. else if (this._m[1] !== 0.0 || this._m[2] !== 0.0 || this._m[3] !== 0.0 ||
  7703. this._m[4] !== 0.0 || this._m[6] !== 0.0 || this._m[7] !== 0.0 ||
  7704. this._m[8] !== 0.0 || this._m[9] !== 0.0 || this._m[10] !== 0.0 || this._m[11] !== 0.0 ||
  7705. this._m[12] !== 0.0 || this._m[13] !== 0.0 || this._m[14] !== 0.0) {
  7706. this._isIdentity3x2 = false;
  7707. }
  7708. else {
  7709. this._isIdentity3x2 = true;
  7710. }
  7711. }
  7712. return this._isIdentity3x2;
  7713. };
  7714. /**
  7715. * Gets the determinant of the matrix
  7716. * @returns the matrix determinant
  7717. */
  7718. Matrix.prototype.determinant = function () {
  7719. if (this._isIdentity === true) {
  7720. return 1;
  7721. }
  7722. var m = this._m;
  7723. var m00 = m[0], m01 = m[1], m02 = m[2], m03 = m[3];
  7724. var m10 = m[4], m11 = m[5], m12 = m[6], m13 = m[7];
  7725. var m20 = m[8], m21 = m[9], m22 = m[10], m23 = m[11];
  7726. var m30 = m[12], m31 = m[13], m32 = m[14], m33 = m[15];
  7727. // https://en.wikipedia.org/wiki/Laplace_expansion
  7728. // to compute the deterrminant of a 4x4 Matrix we compute the cofactors of any row or column,
  7729. // then we multiply each Cofactor by its corresponding matrix value and sum them all to get the determinant
  7730. // Cofactor(i, j) = sign(i,j) * det(Minor(i, j))
  7731. // where
  7732. // - sign(i,j) = (i+j) % 2 === 0 ? 1 : -1
  7733. // - Minor(i, j) is the 3x3 matrix we get by removing row i and column j from current Matrix
  7734. //
  7735. // Here we do that for the 1st row.
  7736. var det_22_33 = m22 * m33 - m32 * m23;
  7737. var det_21_33 = m21 * m33 - m31 * m23;
  7738. var det_21_32 = m21 * m32 - m31 * m22;
  7739. var det_20_33 = m20 * m33 - m30 * m23;
  7740. var det_20_32 = m20 * m32 - m22 * m30;
  7741. var det_20_31 = m20 * m31 - m30 * m21;
  7742. var cofact_00 = +(m11 * det_22_33 - m12 * det_21_33 + m13 * det_21_32);
  7743. var cofact_01 = -(m10 * det_22_33 - m12 * det_20_33 + m13 * det_20_32);
  7744. var cofact_02 = +(m10 * det_21_33 - m11 * det_20_33 + m13 * det_20_31);
  7745. var cofact_03 = -(m10 * det_21_32 - m11 * det_20_32 + m12 * det_20_31);
  7746. return m00 * cofact_00 + m01 * cofact_01 + m02 * cofact_02 + m03 * cofact_03;
  7747. };
  7748. // Methods
  7749. /**
  7750. * Returns the matrix as a Float32Array
  7751. * @returns the matrix underlying array
  7752. */
  7753. Matrix.prototype.toArray = function () {
  7754. return this._m;
  7755. };
  7756. /**
  7757. * Returns the matrix as a Float32Array
  7758. * @returns the matrix underlying array.
  7759. */
  7760. Matrix.prototype.asArray = function () {
  7761. return this._m;
  7762. };
  7763. /**
  7764. * Inverts the current matrix in place
  7765. * @returns the current inverted matrix
  7766. */
  7767. Matrix.prototype.invert = function () {
  7768. this.invertToRef(this);
  7769. return this;
  7770. };
  7771. /**
  7772. * Sets all the matrix elements to zero
  7773. * @returns the current matrix
  7774. */
  7775. Matrix.prototype.reset = function () {
  7776. Matrix.FromValuesToRef(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, this);
  7777. this._updateIdentityStatus(false);
  7778. return this;
  7779. };
  7780. /**
  7781. * Adds the current matrix with a second one
  7782. * @param other defines the matrix to add
  7783. * @returns a new matrix as the addition of the current matrix and the given one
  7784. */
  7785. Matrix.prototype.add = function (other) {
  7786. var result = new Matrix();
  7787. this.addToRef(other, result);
  7788. return result;
  7789. };
  7790. /**
  7791. * Sets the given matrix "result" to the addition of the current matrix and the given one
  7792. * @param other defines the matrix to add
  7793. * @param result defines the target matrix
  7794. * @returns the current matrix
  7795. */
  7796. Matrix.prototype.addToRef = function (other, result) {
  7797. var m = this._m;
  7798. var resultM = result._m;
  7799. var otherM = other.m;
  7800. for (var index = 0; index < 16; index++) {
  7801. resultM[index] = m[index] + otherM[index];
  7802. }
  7803. result._markAsUpdated();
  7804. return this;
  7805. };
  7806. /**
  7807. * Adds in place the given matrix to the current matrix
  7808. * @param other defines the second operand
  7809. * @returns the current updated matrix
  7810. */
  7811. Matrix.prototype.addToSelf = function (other) {
  7812. var m = this._m;
  7813. var otherM = other.m;
  7814. for (var index = 0; index < 16; index++) {
  7815. m[index] += otherM[index];
  7816. }
  7817. this._markAsUpdated();
  7818. return this;
  7819. };
  7820. /**
  7821. * Sets the given matrix to the current inverted Matrix
  7822. * @param other defines the target matrix
  7823. * @returns the unmodified current matrix
  7824. */
  7825. Matrix.prototype.invertToRef = function (other) {
  7826. if (this._isIdentity === true) {
  7827. Matrix.IdentityToRef(other);
  7828. return this;
  7829. }
  7830. // the inverse of a Matrix is the transpose of cofactor matrix divided by the determinant
  7831. var m = this._m;
  7832. var m00 = m[0], m01 = m[1], m02 = m[2], m03 = m[3];
  7833. var m10 = m[4], m11 = m[5], m12 = m[6], m13 = m[7];
  7834. var m20 = m[8], m21 = m[9], m22 = m[10], m23 = m[11];
  7835. var m30 = m[12], m31 = m[13], m32 = m[14], m33 = m[15];
  7836. var det_22_33 = m22 * m33 - m32 * m23;
  7837. var det_21_33 = m21 * m33 - m31 * m23;
  7838. var det_21_32 = m21 * m32 - m31 * m22;
  7839. var det_20_33 = m20 * m33 - m30 * m23;
  7840. var det_20_32 = m20 * m32 - m22 * m30;
  7841. var det_20_31 = m20 * m31 - m30 * m21;
  7842. var cofact_00 = +(m11 * det_22_33 - m12 * det_21_33 + m13 * det_21_32);
  7843. var cofact_01 = -(m10 * det_22_33 - m12 * det_20_33 + m13 * det_20_32);
  7844. var cofact_02 = +(m10 * det_21_33 - m11 * det_20_33 + m13 * det_20_31);
  7845. var cofact_03 = -(m10 * det_21_32 - m11 * det_20_32 + m12 * det_20_31);
  7846. var det = m00 * cofact_00 + m01 * cofact_01 + m02 * cofact_02 + m03 * cofact_03;
  7847. if (det === 0) {
  7848. // not invertible
  7849. other.copyFrom(this);
  7850. return this;
  7851. }
  7852. var detInv = 1 / det;
  7853. var det_12_33 = m12 * m33 - m32 * m13;
  7854. var det_11_33 = m11 * m33 - m31 * m13;
  7855. var det_11_32 = m11 * m32 - m31 * m12;
  7856. var det_10_33 = m10 * m33 - m30 * m13;
  7857. var det_10_32 = m10 * m32 - m30 * m12;
  7858. var det_10_31 = m10 * m31 - m30 * m11;
  7859. var det_12_23 = m12 * m23 - m22 * m13;
  7860. var det_11_23 = m11 * m23 - m21 * m13;
  7861. var det_11_22 = m11 * m22 - m21 * m12;
  7862. var det_10_23 = m10 * m23 - m20 * m13;
  7863. var det_10_22 = m10 * m22 - m20 * m12;
  7864. var det_10_21 = m10 * m21 - m20 * m11;
  7865. var cofact_10 = -(m01 * det_22_33 - m02 * det_21_33 + m03 * det_21_32);
  7866. var cofact_11 = +(m00 * det_22_33 - m02 * det_20_33 + m03 * det_20_32);
  7867. var cofact_12 = -(m00 * det_21_33 - m01 * det_20_33 + m03 * det_20_31);
  7868. var cofact_13 = +(m00 * det_21_32 - m01 * det_20_32 + m02 * det_20_31);
  7869. var cofact_20 = +(m01 * det_12_33 - m02 * det_11_33 + m03 * det_11_32);
  7870. var cofact_21 = -(m00 * det_12_33 - m02 * det_10_33 + m03 * det_10_32);
  7871. var cofact_22 = +(m00 * det_11_33 - m01 * det_10_33 + m03 * det_10_31);
  7872. var cofact_23 = -(m00 * det_11_32 - m01 * det_10_32 + m02 * det_10_31);
  7873. var cofact_30 = -(m01 * det_12_23 - m02 * det_11_23 + m03 * det_11_22);
  7874. var cofact_31 = +(m00 * det_12_23 - m02 * det_10_23 + m03 * det_10_22);
  7875. var cofact_32 = -(m00 * det_11_23 - m01 * det_10_23 + m03 * det_10_21);
  7876. var cofact_33 = +(m00 * det_11_22 - m01 * det_10_22 + m02 * det_10_21);
  7877. Matrix.FromValuesToRef(cofact_00 * detInv, cofact_10 * detInv, cofact_20 * detInv, cofact_30 * detInv, cofact_01 * detInv, cofact_11 * detInv, cofact_21 * detInv, cofact_31 * detInv, cofact_02 * detInv, cofact_12 * detInv, cofact_22 * detInv, cofact_32 * detInv, cofact_03 * detInv, cofact_13 * detInv, cofact_23 * detInv, cofact_33 * detInv, other);
  7878. return this;
  7879. };
  7880. /**
  7881. * add a value at the specified position in the current Matrix
  7882. * @param index the index of the value within the matrix. between 0 and 15.
  7883. * @param value the value to be added
  7884. * @returns the current updated matrix
  7885. */
  7886. Matrix.prototype.addAtIndex = function (index, value) {
  7887. this._m[index] += value;
  7888. this._markAsUpdated();
  7889. return this;
  7890. };
  7891. /**
  7892. * mutiply the specified position in the current Matrix by a value
  7893. * @param index the index of the value within the matrix. between 0 and 15.
  7894. * @param value the value to be added
  7895. * @returns the current updated matrix
  7896. */
  7897. Matrix.prototype.multiplyAtIndex = function (index, value) {
  7898. this._m[index] *= value;
  7899. this._markAsUpdated();
  7900. return this;
  7901. };
  7902. /**
  7903. * Inserts the translation vector (using 3 floats) in the current matrix
  7904. * @param x defines the 1st component of the translation
  7905. * @param y defines the 2nd component of the translation
  7906. * @param z defines the 3rd component of the translation
  7907. * @returns the current updated matrix
  7908. */
  7909. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  7910. this._m[12] = x;
  7911. this._m[13] = y;
  7912. this._m[14] = z;
  7913. this._markAsUpdated();
  7914. return this;
  7915. };
  7916. /**
  7917. * Inserts the translation vector in the current matrix
  7918. * @param vector3 defines the translation to insert
  7919. * @returns the current updated matrix
  7920. */
  7921. Matrix.prototype.setTranslation = function (vector3) {
  7922. return this.setTranslationFromFloats(vector3.x, vector3.y, vector3.z);
  7923. };
  7924. /**
  7925. * Gets the translation value of the current matrix
  7926. * @returns a new Vector3 as the extracted translation from the matrix
  7927. */
  7928. Matrix.prototype.getTranslation = function () {
  7929. return new Vector3(this._m[12], this._m[13], this._m[14]);
  7930. };
  7931. /**
  7932. * Fill a Vector3 with the extracted translation from the matrix
  7933. * @param result defines the Vector3 where to store the translation
  7934. * @returns the current matrix
  7935. */
  7936. Matrix.prototype.getTranslationToRef = function (result) {
  7937. result.x = this._m[12];
  7938. result.y = this._m[13];
  7939. result.z = this._m[14];
  7940. return this;
  7941. };
  7942. /**
  7943. * Remove rotation and scaling part from the matrix
  7944. * @returns the updated matrix
  7945. */
  7946. Matrix.prototype.removeRotationAndScaling = function () {
  7947. var m = this.m;
  7948. 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, m[12], m[13], m[14], m[15], this);
  7949. this._updateIdentityStatus(m[12] === 0 && m[13] === 0 && m[14] === 0 && m[15] === 1);
  7950. return this;
  7951. };
  7952. /**
  7953. * Multiply two matrices
  7954. * @param other defines the second operand
  7955. * @returns a new matrix set with the multiplication result of the current Matrix and the given one
  7956. */
  7957. Matrix.prototype.multiply = function (other) {
  7958. var result = new Matrix();
  7959. this.multiplyToRef(other, result);
  7960. return result;
  7961. };
  7962. /**
  7963. * Copy the current matrix from the given one
  7964. * @param other defines the source matrix
  7965. * @returns the current updated matrix
  7966. */
  7967. Matrix.prototype.copyFrom = function (other) {
  7968. other.copyToArray(this._m);
  7969. var o = other;
  7970. this._updateIdentityStatus(o._isIdentity, o._isIdentityDirty, o._isIdentity3x2, o._isIdentity3x2Dirty);
  7971. return this;
  7972. };
  7973. /**
  7974. * Populates the given array from the starting index with the current matrix values
  7975. * @param array defines the target array
  7976. * @param offset defines the offset in the target array where to start storing values
  7977. * @returns the current matrix
  7978. */
  7979. Matrix.prototype.copyToArray = function (array, offset) {
  7980. if (offset === void 0) { offset = 0; }
  7981. for (var index = 0; index < 16; index++) {
  7982. array[offset + index] = this._m[index];
  7983. }
  7984. return this;
  7985. };
  7986. /**
  7987. * Sets the given matrix "result" with the multiplication result of the current Matrix and the given one
  7988. * @param other defines the second operand
  7989. * @param result defines the matrix where to store the multiplication
  7990. * @returns the current matrix
  7991. */
  7992. Matrix.prototype.multiplyToRef = function (other, result) {
  7993. if (this._isIdentity) {
  7994. result.copyFrom(other);
  7995. return this;
  7996. }
  7997. if (other._isIdentity) {
  7998. result.copyFrom(this);
  7999. return this;
  8000. }
  8001. this.multiplyToArray(other, result._m, 0);
  8002. result._markAsUpdated();
  8003. return this;
  8004. };
  8005. /**
  8006. * Sets the Float32Array "result" from the given index "offset" with the multiplication of the current matrix and the given one
  8007. * @param other defines the second operand
  8008. * @param result defines the array where to store the multiplication
  8009. * @param offset defines the offset in the target array where to start storing values
  8010. * @returns the current matrix
  8011. */
  8012. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  8013. var m = this._m;
  8014. var otherM = other.m;
  8015. var tm0 = m[0], tm1 = m[1], tm2 = m[2], tm3 = m[3];
  8016. var tm4 = m[4], tm5 = m[5], tm6 = m[6], tm7 = m[7];
  8017. var tm8 = m[8], tm9 = m[9], tm10 = m[10], tm11 = m[11];
  8018. var tm12 = m[12], tm13 = m[13], tm14 = m[14], tm15 = m[15];
  8019. var om0 = otherM[0], om1 = otherM[1], om2 = otherM[2], om3 = otherM[3];
  8020. var om4 = otherM[4], om5 = otherM[5], om6 = otherM[6], om7 = otherM[7];
  8021. var om8 = otherM[8], om9 = otherM[9], om10 = otherM[10], om11 = otherM[11];
  8022. var om12 = otherM[12], om13 = otherM[13], om14 = otherM[14], om15 = otherM[15];
  8023. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  8024. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  8025. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  8026. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  8027. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  8028. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  8029. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  8030. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  8031. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  8032. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  8033. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  8034. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  8035. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  8036. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  8037. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  8038. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  8039. return this;
  8040. };
  8041. /**
  8042. * Check equality between this matrix and a second one
  8043. * @param value defines the second matrix to compare
  8044. * @returns true is the current matrix and the given one values are strictly equal
  8045. */
  8046. Matrix.prototype.equals = function (value) {
  8047. var other = value;
  8048. if (!other) {
  8049. return false;
  8050. }
  8051. if (this._isIdentity || other._isIdentity) {
  8052. if (!this._isIdentityDirty && !other._isIdentityDirty) {
  8053. return this._isIdentity && other._isIdentity;
  8054. }
  8055. }
  8056. var m = this.m;
  8057. var om = other.m;
  8058. return (m[0] === om[0] && m[1] === om[1] && m[2] === om[2] && m[3] === om[3] &&
  8059. m[4] === om[4] && m[5] === om[5] && m[6] === om[6] && m[7] === om[7] &&
  8060. m[8] === om[8] && m[9] === om[9] && m[10] === om[10] && m[11] === om[11] &&
  8061. m[12] === om[12] && m[13] === om[13] && m[14] === om[14] && m[15] === om[15]);
  8062. };
  8063. /**
  8064. * Clone the current matrix
  8065. * @returns a new matrix from the current matrix
  8066. */
  8067. Matrix.prototype.clone = function () {
  8068. var matrix = new Matrix();
  8069. matrix.copyFrom(this);
  8070. return matrix;
  8071. };
  8072. /**
  8073. * Returns the name of the current matrix class
  8074. * @returns the string "Matrix"
  8075. */
  8076. Matrix.prototype.getClassName = function () {
  8077. return "Matrix";
  8078. };
  8079. /**
  8080. * Gets the hash code of the current matrix
  8081. * @returns the hash code
  8082. */
  8083. Matrix.prototype.getHashCode = function () {
  8084. var hash = this._m[0] || 0;
  8085. for (var i = 1; i < 16; i++) {
  8086. hash = (hash * 397) ^ (this._m[i] || 0);
  8087. }
  8088. return hash;
  8089. };
  8090. /**
  8091. * Decomposes the current Matrix into a translation, rotation and scaling components
  8092. * @param scale defines the scale vector3 given as a reference to update
  8093. * @param rotation defines the rotation quaternion given as a reference to update
  8094. * @param translation defines the translation vector3 given as a reference to update
  8095. * @returns true if operation was successful
  8096. */
  8097. Matrix.prototype.decompose = function (scale, rotation, translation) {
  8098. if (this._isIdentity) {
  8099. if (translation) {
  8100. translation.setAll(0);
  8101. }
  8102. if (scale) {
  8103. scale.setAll(1);
  8104. }
  8105. if (rotation) {
  8106. rotation.copyFromFloats(0, 0, 0, 1);
  8107. }
  8108. return true;
  8109. }
  8110. var m = this._m;
  8111. if (translation) {
  8112. translation.copyFromFloats(m[12], m[13], m[14]);
  8113. }
  8114. scale = scale || MathTmp.Vector3[0];
  8115. scale.x = Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  8116. scale.y = Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  8117. scale.z = Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  8118. if (this.determinant() <= 0) {
  8119. scale.y *= -1;
  8120. }
  8121. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  8122. if (rotation) {
  8123. rotation.copyFromFloats(0.0, 0.0, 0.0, 1.0);
  8124. }
  8125. return false;
  8126. }
  8127. if (rotation) {
  8128. var sx = 1 / scale.x, sy = 1 / scale.y, sz = 1 / scale.z;
  8129. Matrix.FromValuesToRef(m[0] * sx, m[1] * sx, m[2] * sx, 0.0, m[4] * sy, m[5] * sy, m[6] * sy, 0.0, m[8] * sz, m[9] * sz, m[10] * sz, 0.0, 0.0, 0.0, 0.0, 1.0, MathTmp.Matrix[0]);
  8130. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  8131. }
  8132. return true;
  8133. };
  8134. /**
  8135. * Gets specific row of the matrix
  8136. * @param index defines the number of the row to get
  8137. * @returns the index-th row of the current matrix as a new Vector4
  8138. */
  8139. Matrix.prototype.getRow = function (index) {
  8140. if (index < 0 || index > 3) {
  8141. return null;
  8142. }
  8143. var i = index * 4;
  8144. return new Vector4(this._m[i + 0], this._m[i + 1], this._m[i + 2], this._m[i + 3]);
  8145. };
  8146. /**
  8147. * Sets the index-th row of the current matrix to the vector4 values
  8148. * @param index defines the number of the row to set
  8149. * @param row defines the target vector4
  8150. * @returns the updated current matrix
  8151. */
  8152. Matrix.prototype.setRow = function (index, row) {
  8153. return this.setRowFromFloats(index, row.x, row.y, row.z, row.w);
  8154. };
  8155. /**
  8156. * Compute the transpose of the matrix
  8157. * @returns the new transposed matrix
  8158. */
  8159. Matrix.prototype.transpose = function () {
  8160. return Matrix.Transpose(this);
  8161. };
  8162. /**
  8163. * Compute the transpose of the matrix and store it in a given matrix
  8164. * @param result defines the target matrix
  8165. * @returns the current matrix
  8166. */
  8167. Matrix.prototype.transposeToRef = function (result) {
  8168. Matrix.TransposeToRef(this, result);
  8169. return this;
  8170. };
  8171. /**
  8172. * Sets the index-th row of the current matrix with the given 4 x float values
  8173. * @param index defines the row index
  8174. * @param x defines the x component to set
  8175. * @param y defines the y component to set
  8176. * @param z defines the z component to set
  8177. * @param w defines the w component to set
  8178. * @returns the updated current matrix
  8179. */
  8180. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  8181. if (index < 0 || index > 3) {
  8182. return this;
  8183. }
  8184. var i = index * 4;
  8185. this._m[i + 0] = x;
  8186. this._m[i + 1] = y;
  8187. this._m[i + 2] = z;
  8188. this._m[i + 3] = w;
  8189. this._markAsUpdated();
  8190. return this;
  8191. };
  8192. /**
  8193. * Compute a new matrix set with the current matrix values multiplied by scale (float)
  8194. * @param scale defines the scale factor
  8195. * @returns a new matrix
  8196. */
  8197. Matrix.prototype.scale = function (scale) {
  8198. var result = new Matrix();
  8199. this.scaleToRef(scale, result);
  8200. return result;
  8201. };
  8202. /**
  8203. * Scale the current matrix values by a factor to a given result matrix
  8204. * @param scale defines the scale factor
  8205. * @param result defines the matrix to store the result
  8206. * @returns the current matrix
  8207. */
  8208. Matrix.prototype.scaleToRef = function (scale, result) {
  8209. for (var index = 0; index < 16; index++) {
  8210. result._m[index] = this._m[index] * scale;
  8211. }
  8212. result._markAsUpdated();
  8213. return this;
  8214. };
  8215. /**
  8216. * Scale the current matrix values by a factor and add the result to a given matrix
  8217. * @param scale defines the scale factor
  8218. * @param result defines the Matrix to store the result
  8219. * @returns the current matrix
  8220. */
  8221. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  8222. for (var index = 0; index < 16; index++) {
  8223. result._m[index] += this._m[index] * scale;
  8224. }
  8225. result._markAsUpdated();
  8226. return this;
  8227. };
  8228. /**
  8229. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  8230. * @param ref matrix to store the result
  8231. */
  8232. Matrix.prototype.toNormalMatrix = function (ref) {
  8233. var tmp = MathTmp.Matrix[0];
  8234. this.invertToRef(tmp);
  8235. tmp.transposeToRef(ref);
  8236. var m = ref._m;
  8237. Matrix.FromValuesToRef(m[0], m[1], m[2], 0.0, m[4], m[5], m[6], 0.0, m[8], m[9], m[10], 0.0, 0.0, 0.0, 0.0, 1.0, ref);
  8238. };
  8239. /**
  8240. * Gets only rotation part of the current matrix
  8241. * @returns a new matrix sets to the extracted rotation matrix from the current one
  8242. */
  8243. Matrix.prototype.getRotationMatrix = function () {
  8244. var result = new Matrix();
  8245. this.getRotationMatrixToRef(result);
  8246. return result;
  8247. };
  8248. /**
  8249. * Extracts the rotation matrix from the current one and sets it as the given "result"
  8250. * @param result defines the target matrix to store data to
  8251. * @returns the current matrix
  8252. */
  8253. Matrix.prototype.getRotationMatrixToRef = function (result) {
  8254. var scale = MathTmp.Vector3[0];
  8255. if (!this.decompose(scale)) {
  8256. Matrix.IdentityToRef(result);
  8257. return this;
  8258. }
  8259. var m = this._m;
  8260. var sx = 1 / scale.x, sy = 1 / scale.y, sz = 1 / scale.z;
  8261. Matrix.FromValuesToRef(m[0] * sx, m[1] * sx, m[2] * sx, 0.0, m[4] * sy, m[5] * sy, m[6] * sy, 0.0, m[8] * sz, m[9] * sz, m[10] * sz, 0.0, 0.0, 0.0, 0.0, 1.0, result);
  8262. return this;
  8263. };
  8264. /**
  8265. * Toggles model matrix from being right handed to left handed in place and vice versa
  8266. */
  8267. Matrix.prototype.toggleModelMatrixHandInPlace = function () {
  8268. var m = this._m;
  8269. m[2] *= -1;
  8270. m[6] *= -1;
  8271. m[8] *= -1;
  8272. m[9] *= -1;
  8273. m[14] *= -1;
  8274. this._markAsUpdated();
  8275. };
  8276. /**
  8277. * Toggles projection matrix from being right handed to left handed in place and vice versa
  8278. */
  8279. Matrix.prototype.toggleProjectionMatrixHandInPlace = function () {
  8280. var m = this._m;
  8281. m[8] *= -1;
  8282. m[9] *= -1;
  8283. m[10] *= -1;
  8284. m[11] *= -1;
  8285. this._markAsUpdated();
  8286. };
  8287. // Statics
  8288. /**
  8289. * Creates a matrix from an array
  8290. * @param array defines the source array
  8291. * @param offset defines an offset in the source array
  8292. * @returns a new Matrix set from the starting index of the given array
  8293. */
  8294. Matrix.FromArray = function (array, offset) {
  8295. if (offset === void 0) { offset = 0; }
  8296. var result = new Matrix();
  8297. Matrix.FromArrayToRef(array, offset, result);
  8298. return result;
  8299. };
  8300. /**
  8301. * Copy the content of an array into a given matrix
  8302. * @param array defines the source array
  8303. * @param offset defines an offset in the source array
  8304. * @param result defines the target matrix
  8305. */
  8306. Matrix.FromArrayToRef = function (array, offset, result) {
  8307. for (var index = 0; index < 16; index++) {
  8308. result._m[index] = array[index + offset];
  8309. }
  8310. result._markAsUpdated();
  8311. };
  8312. /**
  8313. * Stores an array into a matrix after having multiplied each component by a given factor
  8314. * @param array defines the source array
  8315. * @param offset defines the offset in the source array
  8316. * @param scale defines the scaling factor
  8317. * @param result defines the target matrix
  8318. */
  8319. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  8320. for (var index = 0; index < 16; index++) {
  8321. result._m[index] = array[index + offset] * scale;
  8322. }
  8323. result._markAsUpdated();
  8324. };
  8325. Object.defineProperty(Matrix, "IdentityReadOnly", {
  8326. /**
  8327. * Gets an identity matrix that must not be updated
  8328. */
  8329. get: function () {
  8330. return Matrix._identityReadOnly;
  8331. },
  8332. enumerable: true,
  8333. configurable: true
  8334. });
  8335. /**
  8336. * Stores a list of values (16) inside a given matrix
  8337. * @param initialM11 defines 1st value of 1st row
  8338. * @param initialM12 defines 2nd value of 1st row
  8339. * @param initialM13 defines 3rd value of 1st row
  8340. * @param initialM14 defines 4th value of 1st row
  8341. * @param initialM21 defines 1st value of 2nd row
  8342. * @param initialM22 defines 2nd value of 2nd row
  8343. * @param initialM23 defines 3rd value of 2nd row
  8344. * @param initialM24 defines 4th value of 2nd row
  8345. * @param initialM31 defines 1st value of 3rd row
  8346. * @param initialM32 defines 2nd value of 3rd row
  8347. * @param initialM33 defines 3rd value of 3rd row
  8348. * @param initialM34 defines 4th value of 3rd row
  8349. * @param initialM41 defines 1st value of 4th row
  8350. * @param initialM42 defines 2nd value of 4th row
  8351. * @param initialM43 defines 3rd value of 4th row
  8352. * @param initialM44 defines 4th value of 4th row
  8353. * @param result defines the target matrix
  8354. */
  8355. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  8356. var m = result._m;
  8357. m[0] = initialM11;
  8358. m[1] = initialM12;
  8359. m[2] = initialM13;
  8360. m[3] = initialM14;
  8361. m[4] = initialM21;
  8362. m[5] = initialM22;
  8363. m[6] = initialM23;
  8364. m[7] = initialM24;
  8365. m[8] = initialM31;
  8366. m[9] = initialM32;
  8367. m[10] = initialM33;
  8368. m[11] = initialM34;
  8369. m[12] = initialM41;
  8370. m[13] = initialM42;
  8371. m[14] = initialM43;
  8372. m[15] = initialM44;
  8373. result._markAsUpdated();
  8374. };
  8375. /**
  8376. * Creates new matrix from a list of values (16)
  8377. * @param initialM11 defines 1st value of 1st row
  8378. * @param initialM12 defines 2nd value of 1st row
  8379. * @param initialM13 defines 3rd value of 1st row
  8380. * @param initialM14 defines 4th value of 1st row
  8381. * @param initialM21 defines 1st value of 2nd row
  8382. * @param initialM22 defines 2nd value of 2nd row
  8383. * @param initialM23 defines 3rd value of 2nd row
  8384. * @param initialM24 defines 4th value of 2nd row
  8385. * @param initialM31 defines 1st value of 3rd row
  8386. * @param initialM32 defines 2nd value of 3rd row
  8387. * @param initialM33 defines 3rd value of 3rd row
  8388. * @param initialM34 defines 4th value of 3rd row
  8389. * @param initialM41 defines 1st value of 4th row
  8390. * @param initialM42 defines 2nd value of 4th row
  8391. * @param initialM43 defines 3rd value of 4th row
  8392. * @param initialM44 defines 4th value of 4th row
  8393. * @returns the new matrix
  8394. */
  8395. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  8396. var result = new Matrix();
  8397. var m = result._m;
  8398. m[0] = initialM11;
  8399. m[1] = initialM12;
  8400. m[2] = initialM13;
  8401. m[3] = initialM14;
  8402. m[4] = initialM21;
  8403. m[5] = initialM22;
  8404. m[6] = initialM23;
  8405. m[7] = initialM24;
  8406. m[8] = initialM31;
  8407. m[9] = initialM32;
  8408. m[10] = initialM33;
  8409. m[11] = initialM34;
  8410. m[12] = initialM41;
  8411. m[13] = initialM42;
  8412. m[14] = initialM43;
  8413. m[15] = initialM44;
  8414. result._markAsUpdated();
  8415. return result;
  8416. };
  8417. /**
  8418. * Creates a new matrix composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  8419. * @param scale defines the scale vector3
  8420. * @param rotation defines the rotation quaternion
  8421. * @param translation defines the translation vector3
  8422. * @returns a new matrix
  8423. */
  8424. Matrix.Compose = function (scale, rotation, translation) {
  8425. var result = new Matrix();
  8426. Matrix.ComposeToRef(scale, rotation, translation, result);
  8427. return result;
  8428. };
  8429. /**
  8430. * Sets a matrix to a value composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  8431. * @param scale defines the scale vector3
  8432. * @param rotation defines the rotation quaternion
  8433. * @param translation defines the translation vector3
  8434. * @param result defines the target matrix
  8435. */
  8436. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  8437. Matrix.ScalingToRef(scale.x, scale.y, scale.z, MathTmp.Matrix[1]);
  8438. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  8439. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  8440. result.setTranslation(translation);
  8441. };
  8442. /**
  8443. * Creates a new identity matrix
  8444. * @returns a new identity matrix
  8445. */
  8446. Matrix.Identity = function () {
  8447. var identity = 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);
  8448. identity._updateIdentityStatus(true);
  8449. return identity;
  8450. };
  8451. /**
  8452. * Creates a new identity matrix and stores the result in a given matrix
  8453. * @param result defines the target matrix
  8454. */
  8455. Matrix.IdentityToRef = function (result) {
  8456. 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);
  8457. result._updateIdentityStatus(true);
  8458. };
  8459. /**
  8460. * Creates a new zero matrix
  8461. * @returns a new zero matrix
  8462. */
  8463. Matrix.Zero = function () {
  8464. var zero = 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);
  8465. zero._updateIdentityStatus(false);
  8466. return zero;
  8467. };
  8468. /**
  8469. * Creates a new rotation matrix for "angle" radians around the X axis
  8470. * @param angle defines the angle (in radians) to use
  8471. * @return the new matrix
  8472. */
  8473. Matrix.RotationX = function (angle) {
  8474. var result = new Matrix();
  8475. Matrix.RotationXToRef(angle, result);
  8476. return result;
  8477. };
  8478. /**
  8479. * Creates a new matrix as the invert of a given matrix
  8480. * @param source defines the source matrix
  8481. * @returns the new matrix
  8482. */
  8483. Matrix.Invert = function (source) {
  8484. var result = new Matrix();
  8485. source.invertToRef(result);
  8486. return result;
  8487. };
  8488. /**
  8489. * Creates a new rotation matrix for "angle" radians around the X axis and stores it in a given matrix
  8490. * @param angle defines the angle (in radians) to use
  8491. * @param result defines the target matrix
  8492. */
  8493. Matrix.RotationXToRef = function (angle, result) {
  8494. var s = Math.sin(angle);
  8495. var c = Math.cos(angle);
  8496. Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, c, s, 0.0, 0.0, -s, c, 0.0, 0.0, 0.0, 0.0, 1.0, result);
  8497. result._updateIdentityStatus(c === 1 && s === 0);
  8498. };
  8499. /**
  8500. * Creates a new rotation matrix for "angle" radians around the Y axis
  8501. * @param angle defines the angle (in radians) to use
  8502. * @return the new matrix
  8503. */
  8504. Matrix.RotationY = function (angle) {
  8505. var result = new Matrix();
  8506. Matrix.RotationYToRef(angle, result);
  8507. return result;
  8508. };
  8509. /**
  8510. * Creates a new rotation matrix for "angle" radians around the Y axis and stores it in a given matrix
  8511. * @param angle defines the angle (in radians) to use
  8512. * @param result defines the target matrix
  8513. */
  8514. Matrix.RotationYToRef = function (angle, result) {
  8515. var s = Math.sin(angle);
  8516. var c = Math.cos(angle);
  8517. Matrix.FromValuesToRef(c, 0.0, -s, 0.0, 0.0, 1.0, 0.0, 0.0, s, 0.0, c, 0.0, 0.0, 0.0, 0.0, 1.0, result);
  8518. result._updateIdentityStatus(c === 1 && s === 0);
  8519. };
  8520. /**
  8521. * Creates a new rotation matrix for "angle" radians around the Z axis
  8522. * @param angle defines the angle (in radians) to use
  8523. * @return the new matrix
  8524. */
  8525. Matrix.RotationZ = function (angle) {
  8526. var result = new Matrix();
  8527. Matrix.RotationZToRef(angle, result);
  8528. return result;
  8529. };
  8530. /**
  8531. * Creates a new rotation matrix for "angle" radians around the Z axis and stores it in a given matrix
  8532. * @param angle defines the angle (in radians) to use
  8533. * @param result defines the target matrix
  8534. */
  8535. Matrix.RotationZToRef = function (angle, result) {
  8536. var s = Math.sin(angle);
  8537. var c = Math.cos(angle);
  8538. Matrix.FromValuesToRef(c, s, 0.0, 0.0, -s, c, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, result);
  8539. result._updateIdentityStatus(c === 1 && s === 0);
  8540. };
  8541. /**
  8542. * Creates a new rotation matrix for "angle" radians around the given axis
  8543. * @param axis defines the axis to use
  8544. * @param angle defines the angle (in radians) to use
  8545. * @return the new matrix
  8546. */
  8547. Matrix.RotationAxis = function (axis, angle) {
  8548. var result = new Matrix();
  8549. Matrix.RotationAxisToRef(axis, angle, result);
  8550. return result;
  8551. };
  8552. /**
  8553. * Creates a new rotation matrix for "angle" radians around the given axis and stores it in a given matrix
  8554. * @param axis defines the axis to use
  8555. * @param angle defines the angle (in radians) to use
  8556. * @param result defines the target matrix
  8557. */
  8558. Matrix.RotationAxisToRef = function (axis, angle, result) {
  8559. var s = Math.sin(-angle);
  8560. var c = Math.cos(-angle);
  8561. var c1 = 1 - c;
  8562. axis.normalize();
  8563. var m = result._m;
  8564. m[0] = (axis.x * axis.x) * c1 + c;
  8565. m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  8566. m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  8567. m[3] = 0.0;
  8568. m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  8569. m[5] = (axis.y * axis.y) * c1 + c;
  8570. m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  8571. m[7] = 0.0;
  8572. m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  8573. m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  8574. m[10] = (axis.z * axis.z) * c1 + c;
  8575. m[11] = 0.0;
  8576. m[12] = 0.0;
  8577. m[13] = 0.0;
  8578. m[14] = 0.0;
  8579. m[15] = 1.0;
  8580. result._markAsUpdated();
  8581. };
  8582. /**
  8583. * Creates a rotation matrix
  8584. * @param yaw defines the yaw angle in radians (Y axis)
  8585. * @param pitch defines the pitch angle in radians (X axis)
  8586. * @param roll defines the roll angle in radians (X axis)
  8587. * @returns the new rotation matrix
  8588. */
  8589. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  8590. var result = new Matrix();
  8591. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  8592. return result;
  8593. };
  8594. /**
  8595. * Creates a rotation matrix and stores it in a given matrix
  8596. * @param yaw defines the yaw angle in radians (Y axis)
  8597. * @param pitch defines the pitch angle in radians (X axis)
  8598. * @param roll defines the roll angle in radians (X axis)
  8599. * @param result defines the target matrix
  8600. */
  8601. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  8602. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, MathTmp.Quaternion[0]);
  8603. MathTmp.Quaternion[0].toRotationMatrix(result);
  8604. };
  8605. /**
  8606. * Creates a scaling matrix
  8607. * @param x defines the scale factor on X axis
  8608. * @param y defines the scale factor on Y axis
  8609. * @param z defines the scale factor on Z axis
  8610. * @returns the new matrix
  8611. */
  8612. Matrix.Scaling = function (x, y, z) {
  8613. var result = new Matrix();
  8614. Matrix.ScalingToRef(x, y, z, result);
  8615. return result;
  8616. };
  8617. /**
  8618. * Creates a scaling matrix and stores it in a given matrix
  8619. * @param x defines the scale factor on X axis
  8620. * @param y defines the scale factor on Y axis
  8621. * @param z defines the scale factor on Z axis
  8622. * @param result defines the target matrix
  8623. */
  8624. Matrix.ScalingToRef = function (x, y, z, result) {
  8625. Matrix.FromValuesToRef(x, 0.0, 0.0, 0.0, 0.0, y, 0.0, 0.0, 0.0, 0.0, z, 0.0, 0.0, 0.0, 0.0, 1.0, result);
  8626. result._updateIdentityStatus(x === 1 && y === 1 && z === 1);
  8627. };
  8628. /**
  8629. * Creates a translation matrix
  8630. * @param x defines the translation on X axis
  8631. * @param y defines the translation on Y axis
  8632. * @param z defines the translationon Z axis
  8633. * @returns the new matrix
  8634. */
  8635. Matrix.Translation = function (x, y, z) {
  8636. var result = new Matrix();
  8637. Matrix.TranslationToRef(x, y, z, result);
  8638. return result;
  8639. };
  8640. /**
  8641. * Creates a translation matrix and stores it in a given matrix
  8642. * @param x defines the translation on X axis
  8643. * @param y defines the translation on Y axis
  8644. * @param z defines the translationon Z axis
  8645. * @param result defines the target matrix
  8646. */
  8647. Matrix.TranslationToRef = function (x, y, z, result) {
  8648. 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);
  8649. result._updateIdentityStatus(x === 0 && y === 0 && z === 0);
  8650. };
  8651. /**
  8652. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  8653. * @param startValue defines the start value
  8654. * @param endValue defines the end value
  8655. * @param gradient defines the gradient factor
  8656. * @returns the new matrix
  8657. */
  8658. Matrix.Lerp = function (startValue, endValue, gradient) {
  8659. var result = new Matrix();
  8660. Matrix.LerpToRef(startValue, endValue, gradient, result);
  8661. return result;
  8662. };
  8663. /**
  8664. * Set the given matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  8665. * @param startValue defines the start value
  8666. * @param endValue defines the end value
  8667. * @param gradient defines the gradient factor
  8668. * @param result defines the Matrix object where to store data
  8669. */
  8670. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  8671. var resultM = result._m;
  8672. var startM = startValue.m;
  8673. var endM = endValue.m;
  8674. for (var index = 0; index < 16; index++) {
  8675. resultM[index] = startM[index] * (1.0 - gradient) + endM[index] * gradient;
  8676. }
  8677. result._markAsUpdated();
  8678. };
  8679. /**
  8680. * Builds a new matrix whose values are computed by:
  8681. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  8682. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  8683. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  8684. * @param startValue defines the first matrix
  8685. * @param endValue defines the second matrix
  8686. * @param gradient defines the gradient between the two matrices
  8687. * @returns the new matrix
  8688. */
  8689. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  8690. var result = new Matrix();
  8691. Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  8692. return result;
  8693. };
  8694. /**
  8695. * Update a matrix to values which are computed by:
  8696. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  8697. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  8698. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  8699. * @param startValue defines the first matrix
  8700. * @param endValue defines the second matrix
  8701. * @param gradient defines the gradient between the two matrices
  8702. * @param result defines the target matrix
  8703. */
  8704. Matrix.DecomposeLerpToRef = function (startValue, endValue, gradient, result) {
  8705. var startScale = MathTmp.Vector3[0];
  8706. var startRotation = MathTmp.Quaternion[0];
  8707. var startTranslation = MathTmp.Vector3[1];
  8708. startValue.decompose(startScale, startRotation, startTranslation);
  8709. var endScale = MathTmp.Vector3[2];
  8710. var endRotation = MathTmp.Quaternion[1];
  8711. var endTranslation = MathTmp.Vector3[3];
  8712. endValue.decompose(endScale, endRotation, endTranslation);
  8713. var resultScale = MathTmp.Vector3[4];
  8714. Vector3.LerpToRef(startScale, endScale, gradient, resultScale);
  8715. var resultRotation = MathTmp.Quaternion[2];
  8716. Quaternion.SlerpToRef(startRotation, endRotation, gradient, resultRotation);
  8717. var resultTranslation = MathTmp.Vector3[5];
  8718. Vector3.LerpToRef(startTranslation, endTranslation, gradient, resultTranslation);
  8719. Matrix.ComposeToRef(resultScale, resultRotation, resultTranslation, result);
  8720. };
  8721. /**
  8722. * 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"
  8723. * This function works in left handed mode
  8724. * @param eye defines the final position of the entity
  8725. * @param target defines where the entity should look at
  8726. * @param up defines the up vector for the entity
  8727. * @returns the new matrix
  8728. */
  8729. Matrix.LookAtLH = function (eye, target, up) {
  8730. var result = new Matrix();
  8731. Matrix.LookAtLHToRef(eye, target, up, result);
  8732. return result;
  8733. };
  8734. /**
  8735. * 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".
  8736. * This function works in left handed mode
  8737. * @param eye defines the final position of the entity
  8738. * @param target defines where the entity should look at
  8739. * @param up defines the up vector for the entity
  8740. * @param result defines the target matrix
  8741. */
  8742. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  8743. var xAxis = MathTmp.Vector3[0];
  8744. var yAxis = MathTmp.Vector3[1];
  8745. var zAxis = MathTmp.Vector3[2];
  8746. // Z axis
  8747. target.subtractToRef(eye, zAxis);
  8748. zAxis.normalize();
  8749. // X axis
  8750. Vector3.CrossToRef(up, zAxis, xAxis);
  8751. var xSquareLength = xAxis.lengthSquared();
  8752. if (xSquareLength === 0) {
  8753. xAxis.x = 1.0;
  8754. }
  8755. else {
  8756. xAxis.normalizeFromLength(Math.sqrt(xSquareLength));
  8757. }
  8758. // Y axis
  8759. Vector3.CrossToRef(zAxis, xAxis, yAxis);
  8760. yAxis.normalize();
  8761. // Eye angles
  8762. var ex = -Vector3.Dot(xAxis, eye);
  8763. var ey = -Vector3.Dot(yAxis, eye);
  8764. var ez = -Vector3.Dot(zAxis, eye);
  8765. Matrix.FromValuesToRef(xAxis.x, yAxis.x, zAxis.x, 0.0, xAxis.y, yAxis.y, zAxis.y, 0.0, xAxis.z, yAxis.z, zAxis.z, 0.0, ex, ey, ez, 1.0, result);
  8766. };
  8767. /**
  8768. * 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"
  8769. * This function works in right handed mode
  8770. * @param eye defines the final position of the entity
  8771. * @param target defines where the entity should look at
  8772. * @param up defines the up vector for the entity
  8773. * @returns the new matrix
  8774. */
  8775. Matrix.LookAtRH = function (eye, target, up) {
  8776. var result = new Matrix();
  8777. Matrix.LookAtRHToRef(eye, target, up, result);
  8778. return result;
  8779. };
  8780. /**
  8781. * 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".
  8782. * This function works in right handed mode
  8783. * @param eye defines the final position of the entity
  8784. * @param target defines where the entity should look at
  8785. * @param up defines the up vector for the entity
  8786. * @param result defines the target matrix
  8787. */
  8788. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  8789. var xAxis = MathTmp.Vector3[0];
  8790. var yAxis = MathTmp.Vector3[1];
  8791. var zAxis = MathTmp.Vector3[2];
  8792. // Z axis
  8793. eye.subtractToRef(target, zAxis);
  8794. zAxis.normalize();
  8795. // X axis
  8796. Vector3.CrossToRef(up, zAxis, xAxis);
  8797. var xSquareLength = xAxis.lengthSquared();
  8798. if (xSquareLength === 0) {
  8799. xAxis.x = 1.0;
  8800. }
  8801. else {
  8802. xAxis.normalizeFromLength(Math.sqrt(xSquareLength));
  8803. }
  8804. // Y axis
  8805. Vector3.CrossToRef(zAxis, xAxis, yAxis);
  8806. yAxis.normalize();
  8807. // Eye angles
  8808. var ex = -Vector3.Dot(xAxis, eye);
  8809. var ey = -Vector3.Dot(yAxis, eye);
  8810. var ez = -Vector3.Dot(zAxis, eye);
  8811. Matrix.FromValuesToRef(xAxis.x, yAxis.x, zAxis.x, 0.0, xAxis.y, yAxis.y, zAxis.y, 0.0, xAxis.z, yAxis.z, zAxis.z, 0.0, ex, ey, ez, 1.0, result);
  8812. };
  8813. /**
  8814. * Create a left-handed orthographic projection matrix
  8815. * @param width defines the viewport width
  8816. * @param height defines the viewport height
  8817. * @param znear defines the near clip plane
  8818. * @param zfar defines the far clip plane
  8819. * @returns a new matrix as a left-handed orthographic projection matrix
  8820. */
  8821. Matrix.OrthoLH = function (width, height, znear, zfar) {
  8822. var matrix = new Matrix();
  8823. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  8824. return matrix;
  8825. };
  8826. /**
  8827. * Store a left-handed orthographic projection to a given matrix
  8828. * @param width defines the viewport width
  8829. * @param height defines the viewport height
  8830. * @param znear defines the near clip plane
  8831. * @param zfar defines the far clip plane
  8832. * @param result defines the target matrix
  8833. */
  8834. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  8835. var n = znear;
  8836. var f = zfar;
  8837. var a = 2.0 / width;
  8838. var b = 2.0 / height;
  8839. var c = 2.0 / (f - n);
  8840. var d = -(f + n) / (f - n);
  8841. 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);
  8842. result._updateIdentityStatus(a === 1 && b === 1 && c === 1 && d === 0);
  8843. };
  8844. /**
  8845. * Create a left-handed orthographic projection matrix
  8846. * @param left defines the viewport left coordinate
  8847. * @param right defines the viewport right coordinate
  8848. * @param bottom defines the viewport bottom coordinate
  8849. * @param top defines the viewport top coordinate
  8850. * @param znear defines the near clip plane
  8851. * @param zfar defines the far clip plane
  8852. * @returns a new matrix as a left-handed orthographic projection matrix
  8853. */
  8854. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  8855. var matrix = new Matrix();
  8856. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  8857. return matrix;
  8858. };
  8859. /**
  8860. * Stores a left-handed orthographic projection into a given matrix
  8861. * @param left defines the viewport left coordinate
  8862. * @param right defines the viewport right coordinate
  8863. * @param bottom defines the viewport bottom coordinate
  8864. * @param top defines the viewport top coordinate
  8865. * @param znear defines the near clip plane
  8866. * @param zfar defines the far clip plane
  8867. * @param result defines the target matrix
  8868. */
  8869. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  8870. var n = znear;
  8871. var f = zfar;
  8872. var a = 2.0 / (right - left);
  8873. var b = 2.0 / (top - bottom);
  8874. var c = 2.0 / (f - n);
  8875. var d = -(f + n) / (f - n);
  8876. var i0 = (left + right) / (left - right);
  8877. var i1 = (top + bottom) / (bottom - top);
  8878. 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);
  8879. result._markAsUpdated();
  8880. };
  8881. /**
  8882. * Creates a right-handed orthographic projection matrix
  8883. * @param left defines the viewport left coordinate
  8884. * @param right defines the viewport right coordinate
  8885. * @param bottom defines the viewport bottom coordinate
  8886. * @param top defines the viewport top coordinate
  8887. * @param znear defines the near clip plane
  8888. * @param zfar defines the far clip plane
  8889. * @returns a new matrix as a right-handed orthographic projection matrix
  8890. */
  8891. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  8892. var matrix = new Matrix();
  8893. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  8894. return matrix;
  8895. };
  8896. /**
  8897. * Stores a right-handed orthographic projection into a given matrix
  8898. * @param left defines the viewport left coordinate
  8899. * @param right defines the viewport right coordinate
  8900. * @param bottom defines the viewport bottom coordinate
  8901. * @param top defines the viewport top coordinate
  8902. * @param znear defines the near clip plane
  8903. * @param zfar defines the far clip plane
  8904. * @param result defines the target matrix
  8905. */
  8906. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  8907. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  8908. result._m[10] *= -1; // No need to call _markAsUpdated as previous function already called it and let _isIdentityDirty to true
  8909. };
  8910. /**
  8911. * Creates a left-handed perspective projection matrix
  8912. * @param width defines the viewport width
  8913. * @param height defines the viewport height
  8914. * @param znear defines the near clip plane
  8915. * @param zfar defines the far clip plane
  8916. * @returns a new matrix as a left-handed perspective projection matrix
  8917. */
  8918. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  8919. var matrix = new Matrix();
  8920. var n = znear;
  8921. var f = zfar;
  8922. var a = 2.0 * n / width;
  8923. var b = 2.0 * n / height;
  8924. var c = (f + n) / (f - n);
  8925. var d = -2.0 * f * n / (f - n);
  8926. 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);
  8927. matrix._updateIdentityStatus(false);
  8928. return matrix;
  8929. };
  8930. /**
  8931. * Creates a left-handed perspective projection matrix
  8932. * @param fov defines the horizontal field of view
  8933. * @param aspect defines the aspect ratio
  8934. * @param znear defines the near clip plane
  8935. * @param zfar defines the far clip plane
  8936. * @returns a new matrix as a left-handed perspective projection matrix
  8937. */
  8938. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  8939. var matrix = new Matrix();
  8940. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  8941. return matrix;
  8942. };
  8943. /**
  8944. * Stores a left-handed perspective projection into a given matrix
  8945. * @param fov defines the horizontal field of view
  8946. * @param aspect defines the aspect ratio
  8947. * @param znear defines the near clip plane
  8948. * @param zfar defines the far clip plane
  8949. * @param result defines the target matrix
  8950. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  8951. */
  8952. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  8953. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  8954. var n = znear;
  8955. var f = zfar;
  8956. var t = 1.0 / (Math.tan(fov * 0.5));
  8957. var a = isVerticalFovFixed ? (t / aspect) : t;
  8958. var b = isVerticalFovFixed ? t : (t * aspect);
  8959. var c = (f + n) / (f - n);
  8960. var d = -2.0 * f * n / (f - n);
  8961. 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);
  8962. result._updateIdentityStatus(false);
  8963. };
  8964. /**
  8965. * Creates a right-handed perspective projection matrix
  8966. * @param fov defines the horizontal field of view
  8967. * @param aspect defines the aspect ratio
  8968. * @param znear defines the near clip plane
  8969. * @param zfar defines the far clip plane
  8970. * @returns a new matrix as a right-handed perspective projection matrix
  8971. */
  8972. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  8973. var matrix = new Matrix();
  8974. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  8975. return matrix;
  8976. };
  8977. /**
  8978. * Stores a right-handed perspective projection into a given matrix
  8979. * @param fov defines the horizontal field of view
  8980. * @param aspect defines the aspect ratio
  8981. * @param znear defines the near clip plane
  8982. * @param zfar defines the far clip plane
  8983. * @param result defines the target matrix
  8984. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  8985. */
  8986. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  8987. //alternatively this could be expressed as:
  8988. // m = PerspectiveFovLHToRef
  8989. // m[10] *= -1.0;
  8990. // m[11] *= -1.0;
  8991. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  8992. var n = znear;
  8993. var f = zfar;
  8994. var t = 1.0 / (Math.tan(fov * 0.5));
  8995. var a = isVerticalFovFixed ? (t / aspect) : t;
  8996. var b = isVerticalFovFixed ? t : (t * aspect);
  8997. var c = -(f + n) / (f - n);
  8998. var d = -2 * f * n / (f - n);
  8999. 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);
  9000. result._updateIdentityStatus(false);
  9001. };
  9002. /**
  9003. * Stores a perspective projection for WebVR info a given matrix
  9004. * @param fov defines the field of view
  9005. * @param znear defines the near clip plane
  9006. * @param zfar defines the far clip plane
  9007. * @param result defines the target matrix
  9008. * @param rightHanded defines if the matrix must be in right-handed mode (false by default)
  9009. */
  9010. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  9011. if (rightHanded === void 0) { rightHanded = false; }
  9012. var rightHandedFactor = rightHanded ? -1 : 1;
  9013. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  9014. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  9015. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  9016. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  9017. var xScale = 2.0 / (leftTan + rightTan);
  9018. var yScale = 2.0 / (upTan + downTan);
  9019. var m = result._m;
  9020. m[0] = xScale;
  9021. m[1] = m[2] = m[3] = m[4] = 0.0;
  9022. m[5] = yScale;
  9023. m[6] = m[7] = 0.0;
  9024. m[8] = ((leftTan - rightTan) * xScale * 0.5);
  9025. m[9] = -((upTan - downTan) * yScale * 0.5);
  9026. m[10] = -zfar / (znear - zfar);
  9027. m[11] = 1.0 * rightHandedFactor;
  9028. m[12] = m[13] = m[15] = 0.0;
  9029. m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  9030. result._markAsUpdated();
  9031. };
  9032. /**
  9033. * Computes a complete transformation matrix
  9034. * @param viewport defines the viewport to use
  9035. * @param world defines the world matrix
  9036. * @param view defines the view matrix
  9037. * @param projection defines the projection matrix
  9038. * @param zmin defines the near clip plane
  9039. * @param zmax defines the far clip plane
  9040. * @returns the transformation matrix
  9041. */
  9042. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  9043. var cw = viewport.width;
  9044. var ch = viewport.height;
  9045. var cx = viewport.x;
  9046. var cy = viewport.y;
  9047. 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.0);
  9048. var matrix = MathTmp.Matrix[0];
  9049. world.multiplyToRef(view, matrix);
  9050. matrix.multiplyToRef(projection, matrix);
  9051. return matrix.multiply(viewportMatrix);
  9052. };
  9053. /**
  9054. * Extracts a 2x2 matrix from a given matrix and store the result in a Float32Array
  9055. * @param matrix defines the matrix to use
  9056. * @returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the given matrix
  9057. */
  9058. Matrix.GetAsMatrix2x2 = function (matrix) {
  9059. var m = matrix.m;
  9060. return new Float32Array([m[0], m[1], m[4], m[5]]);
  9061. };
  9062. /**
  9063. * Extracts a 3x3 matrix from a given matrix and store the result in a Float32Array
  9064. * @param matrix defines the matrix to use
  9065. * @returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the given matrix
  9066. */
  9067. Matrix.GetAsMatrix3x3 = function (matrix) {
  9068. var m = matrix.m;
  9069. return new Float32Array([
  9070. m[0], m[1], m[2],
  9071. m[4], m[5], m[6],
  9072. m[8], m[9], m[10]
  9073. ]);
  9074. };
  9075. /**
  9076. * Compute the transpose of a given matrix
  9077. * @param matrix defines the matrix to transpose
  9078. * @returns the new matrix
  9079. */
  9080. Matrix.Transpose = function (matrix) {
  9081. var result = new Matrix();
  9082. Matrix.TransposeToRef(matrix, result);
  9083. return result;
  9084. };
  9085. /**
  9086. * Compute the transpose of a matrix and store it in a target matrix
  9087. * @param matrix defines the matrix to transpose
  9088. * @param result defines the target matrix
  9089. */
  9090. Matrix.TransposeToRef = function (matrix, result) {
  9091. var rm = result._m;
  9092. var mm = matrix.m;
  9093. rm[0] = mm[0];
  9094. rm[1] = mm[4];
  9095. rm[2] = mm[8];
  9096. rm[3] = mm[12];
  9097. rm[4] = mm[1];
  9098. rm[5] = mm[5];
  9099. rm[6] = mm[9];
  9100. rm[7] = mm[13];
  9101. rm[8] = mm[2];
  9102. rm[9] = mm[6];
  9103. rm[10] = mm[10];
  9104. rm[11] = mm[14];
  9105. rm[12] = mm[3];
  9106. rm[13] = mm[7];
  9107. rm[14] = mm[11];
  9108. rm[15] = mm[15];
  9109. // identity-ness does not change when transposing
  9110. result._updateIdentityStatus(matrix._isIdentity, matrix._isIdentityDirty);
  9111. };
  9112. /**
  9113. * Computes a reflection matrix from a plane
  9114. * @param plane defines the reflection plane
  9115. * @returns a new matrix
  9116. */
  9117. Matrix.Reflection = function (plane) {
  9118. var matrix = new Matrix();
  9119. Matrix.ReflectionToRef(plane, matrix);
  9120. return matrix;
  9121. };
  9122. /**
  9123. * Computes a reflection matrix from a plane
  9124. * @param plane defines the reflection plane
  9125. * @param result defines the target matrix
  9126. */
  9127. Matrix.ReflectionToRef = function (plane, result) {
  9128. plane.normalize();
  9129. var x = plane.normal.x;
  9130. var y = plane.normal.y;
  9131. var z = plane.normal.z;
  9132. var temp = -2 * x;
  9133. var temp2 = -2 * y;
  9134. var temp3 = -2 * z;
  9135. Matrix.FromValuesToRef(temp * x + 1, temp2 * x, temp3 * x, 0.0, temp * y, temp2 * y + 1, temp3 * y, 0.0, temp * z, temp2 * z, temp3 * z + 1, 0.0, temp * plane.d, temp2 * plane.d, temp3 * plane.d, 1.0, result);
  9136. };
  9137. /**
  9138. * Sets the given matrix as a rotation matrix composed from the 3 left handed axes
  9139. * @param xaxis defines the value of the 1st axis
  9140. * @param yaxis defines the value of the 2nd axis
  9141. * @param zaxis defines the value of the 3rd axis
  9142. * @param result defines the target matrix
  9143. */
  9144. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  9145. Matrix.FromValuesToRef(xaxis.x, xaxis.y, xaxis.z, 0.0, yaxis.x, yaxis.y, yaxis.z, 0.0, zaxis.x, zaxis.y, zaxis.z, 0.0, 0.0, 0.0, 0.0, 1.0, result);
  9146. };
  9147. /**
  9148. * Creates a rotation matrix from a quaternion and stores it in a target matrix
  9149. * @param quat defines the quaternion to use
  9150. * @param result defines the target matrix
  9151. */
  9152. Matrix.FromQuaternionToRef = function (quat, result) {
  9153. var xx = quat.x * quat.x;
  9154. var yy = quat.y * quat.y;
  9155. var zz = quat.z * quat.z;
  9156. var xy = quat.x * quat.y;
  9157. var zw = quat.z * quat.w;
  9158. var zx = quat.z * quat.x;
  9159. var yw = quat.y * quat.w;
  9160. var yz = quat.y * quat.z;
  9161. var xw = quat.x * quat.w;
  9162. result._m[0] = 1.0 - (2.0 * (yy + zz));
  9163. result._m[1] = 2.0 * (xy + zw);
  9164. result._m[2] = 2.0 * (zx - yw);
  9165. result._m[3] = 0.0;
  9166. result._m[4] = 2.0 * (xy - zw);
  9167. result._m[5] = 1.0 - (2.0 * (zz + xx));
  9168. result._m[6] = 2.0 * (yz + xw);
  9169. result._m[7] = 0.0;
  9170. result._m[8] = 2.0 * (zx + yw);
  9171. result._m[9] = 2.0 * (yz - xw);
  9172. result._m[10] = 1.0 - (2.0 * (yy + xx));
  9173. result._m[11] = 0.0;
  9174. result._m[12] = 0.0;
  9175. result._m[13] = 0.0;
  9176. result._m[14] = 0.0;
  9177. result._m[15] = 1.0;
  9178. result._markAsUpdated();
  9179. };
  9180. Matrix._updateFlagSeed = 0;
  9181. Matrix._identityReadOnly = Matrix.Identity();
  9182. return Matrix;
  9183. }());
  9184. BABYLON.Matrix = Matrix;
  9185. /**
  9186. * Represens a plane by the equation ax + by + cz + d = 0
  9187. */
  9188. var Plane = /** @class */ (function () {
  9189. /**
  9190. * Creates a Plane object according to the given floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  9191. * @param a a component of the plane
  9192. * @param b b component of the plane
  9193. * @param c c component of the plane
  9194. * @param d d component of the plane
  9195. */
  9196. function Plane(a, b, c, d) {
  9197. this.normal = new Vector3(a, b, c);
  9198. this.d = d;
  9199. }
  9200. /**
  9201. * @returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  9202. */
  9203. Plane.prototype.asArray = function () {
  9204. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  9205. };
  9206. // Methods
  9207. /**
  9208. * @returns a new plane copied from the current Plane.
  9209. */
  9210. Plane.prototype.clone = function () {
  9211. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  9212. };
  9213. /**
  9214. * @returns the string "Plane".
  9215. */
  9216. Plane.prototype.getClassName = function () {
  9217. return "Plane";
  9218. };
  9219. /**
  9220. * @returns the Plane hash code.
  9221. */
  9222. Plane.prototype.getHashCode = function () {
  9223. var hash = this.normal.getHashCode();
  9224. hash = (hash * 397) ^ (this.d || 0);
  9225. return hash;
  9226. };
  9227. /**
  9228. * Normalize the current Plane in place.
  9229. * @returns the updated Plane.
  9230. */
  9231. Plane.prototype.normalize = function () {
  9232. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  9233. var magnitude = 0.0;
  9234. if (norm !== 0) {
  9235. magnitude = 1.0 / norm;
  9236. }
  9237. this.normal.x *= magnitude;
  9238. this.normal.y *= magnitude;
  9239. this.normal.z *= magnitude;
  9240. this.d *= magnitude;
  9241. return this;
  9242. };
  9243. /**
  9244. * Applies a transformation the plane and returns the result
  9245. * @param transformation the transformation matrix to be applied to the plane
  9246. * @returns a new Plane as the result of the transformation of the current Plane by the given matrix.
  9247. */
  9248. Plane.prototype.transform = function (transformation) {
  9249. var transposedMatrix = MathTmp.Matrix[0];
  9250. Matrix.TransposeToRef(transformation, transposedMatrix);
  9251. var m = transposedMatrix.m;
  9252. var x = this.normal.x;
  9253. var y = this.normal.y;
  9254. var z = this.normal.z;
  9255. var d = this.d;
  9256. var normalX = x * m[0] + y * m[1] + z * m[2] + d * m[3];
  9257. var normalY = x * m[4] + y * m[5] + z * m[6] + d * m[7];
  9258. var normalZ = x * m[8] + y * m[9] + z * m[10] + d * m[11];
  9259. var finalD = x * m[12] + y * m[13] + z * m[14] + d * m[15];
  9260. return new Plane(normalX, normalY, normalZ, finalD);
  9261. };
  9262. /**
  9263. * Calcualtte the dot product between the point and the plane normal
  9264. * @param point point to calculate the dot product with
  9265. * @returns the dot product (float) of the point coordinates and the plane normal.
  9266. */
  9267. Plane.prototype.dotCoordinate = function (point) {
  9268. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  9269. };
  9270. /**
  9271. * Updates the current Plane from the plane defined by the three given points.
  9272. * @param point1 one of the points used to contruct the plane
  9273. * @param point2 one of the points used to contruct the plane
  9274. * @param point3 one of the points used to contruct the plane
  9275. * @returns the updated Plane.
  9276. */
  9277. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  9278. var x1 = point2.x - point1.x;
  9279. var y1 = point2.y - point1.y;
  9280. var z1 = point2.z - point1.z;
  9281. var x2 = point3.x - point1.x;
  9282. var y2 = point3.y - point1.y;
  9283. var z2 = point3.z - point1.z;
  9284. var yz = (y1 * z2) - (z1 * y2);
  9285. var xz = (z1 * x2) - (x1 * z2);
  9286. var xy = (x1 * y2) - (y1 * x2);
  9287. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  9288. var invPyth;
  9289. if (pyth !== 0) {
  9290. invPyth = 1.0 / pyth;
  9291. }
  9292. else {
  9293. invPyth = 0.0;
  9294. }
  9295. this.normal.x = yz * invPyth;
  9296. this.normal.y = xz * invPyth;
  9297. this.normal.z = xy * invPyth;
  9298. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  9299. return this;
  9300. };
  9301. /**
  9302. * Checks if the plane is facing a given direction
  9303. * @param direction the direction to check if the plane is facing
  9304. * @param epsilon value the dot product is compared against (returns true if dot <= epsilon)
  9305. * @returns True is the vector "direction" is the same side than the plane normal.
  9306. */
  9307. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  9308. var dot = Vector3.Dot(this.normal, direction);
  9309. return (dot <= epsilon);
  9310. };
  9311. /**
  9312. * Calculates the distance to a point
  9313. * @param point point to calculate distance to
  9314. * @returns the signed distance (float) from the given point to the Plane.
  9315. */
  9316. Plane.prototype.signedDistanceTo = function (point) {
  9317. return Vector3.Dot(point, this.normal) + this.d;
  9318. };
  9319. // Statics
  9320. /**
  9321. * Creates a plane from an array
  9322. * @param array the array to create a plane from
  9323. * @returns a new Plane from the given array.
  9324. */
  9325. Plane.FromArray = function (array) {
  9326. return new Plane(array[0], array[1], array[2], array[3]);
  9327. };
  9328. /**
  9329. * Creates a plane from three points
  9330. * @param point1 point used to create the plane
  9331. * @param point2 point used to create the plane
  9332. * @param point3 point used to create the plane
  9333. * @returns a new Plane defined by the three given points.
  9334. */
  9335. Plane.FromPoints = function (point1, point2, point3) {
  9336. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  9337. result.copyFromPoints(point1, point2, point3);
  9338. return result;
  9339. };
  9340. /**
  9341. * Creates a plane from an origin point and a normal
  9342. * @param origin origin of the plane to be constructed
  9343. * @param normal normal of the plane to be constructed
  9344. * @returns a new Plane the normal vector to this plane at the given origin point.
  9345. * Note : the vector "normal" is updated because normalized.
  9346. */
  9347. Plane.FromPositionAndNormal = function (origin, normal) {
  9348. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  9349. normal.normalize();
  9350. result.normal = normal;
  9351. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  9352. return result;
  9353. };
  9354. /**
  9355. * Calculates the distance from a plane and a point
  9356. * @param origin origin of the plane to be constructed
  9357. * @param normal normal of the plane to be constructed
  9358. * @param point point to calculate distance to
  9359. * @returns the signed distance between the plane defined by the normal vector at the "origin"" point and the given other point.
  9360. */
  9361. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  9362. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  9363. return Vector3.Dot(point, normal) + d;
  9364. };
  9365. return Plane;
  9366. }());
  9367. BABYLON.Plane = Plane;
  9368. /**
  9369. * Class used to represent a viewport on screen
  9370. */
  9371. var Viewport = /** @class */ (function () {
  9372. /**
  9373. * Creates a Viewport object located at (x, y) and sized (width, height)
  9374. * @param x defines viewport left coordinate
  9375. * @param y defines viewport top coordinate
  9376. * @param width defines the viewport width
  9377. * @param height defines the viewport height
  9378. */
  9379. function Viewport(
  9380. /** viewport left coordinate */
  9381. x,
  9382. /** viewport top coordinate */
  9383. y,
  9384. /**viewport width */
  9385. width,
  9386. /** viewport height */
  9387. height) {
  9388. this.x = x;
  9389. this.y = y;
  9390. this.width = width;
  9391. this.height = height;
  9392. }
  9393. /**
  9394. * Creates a new viewport using absolute sizing (from 0-> width, 0-> height instead of 0->1)
  9395. * @param renderWidthOrEngine defines either an engine or the rendering width
  9396. * @param renderHeight defines the rendering height
  9397. * @returns a new Viewport
  9398. */
  9399. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  9400. if (renderWidthOrEngine.getRenderWidth) {
  9401. var engine = renderWidthOrEngine;
  9402. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  9403. }
  9404. var renderWidth = renderWidthOrEngine;
  9405. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  9406. };
  9407. /**
  9408. * Returns a new Viewport copied from the current one
  9409. * @returns a new Viewport
  9410. */
  9411. Viewport.prototype.clone = function () {
  9412. return new Viewport(this.x, this.y, this.width, this.height);
  9413. };
  9414. return Viewport;
  9415. }());
  9416. BABYLON.Viewport = Viewport;
  9417. /**
  9418. * Reprasents a camera frustum
  9419. */
  9420. var Frustum = /** @class */ (function () {
  9421. function Frustum() {
  9422. }
  9423. /**
  9424. * Gets the planes representing the frustum
  9425. * @param transform matrix to be applied to the returned planes
  9426. * @returns a new array of 6 Frustum planes computed by the given transformation matrix.
  9427. */
  9428. Frustum.GetPlanes = function (transform) {
  9429. var frustumPlanes = [];
  9430. for (var index = 0; index < 6; index++) {
  9431. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  9432. }
  9433. Frustum.GetPlanesToRef(transform, frustumPlanes);
  9434. return frustumPlanes;
  9435. };
  9436. /**
  9437. * Gets the near frustum plane transformed by the transform matrix
  9438. * @param transform transformation matrix to be applied to the resulting frustum plane
  9439. * @param frustumPlane the resuling frustum plane
  9440. */
  9441. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  9442. var m = transform.m;
  9443. frustumPlane.normal.x = m[3] + m[2];
  9444. frustumPlane.normal.y = m[7] + m[6];
  9445. frustumPlane.normal.z = m[11] + m[10];
  9446. frustumPlane.d = m[15] + m[14];
  9447. frustumPlane.normalize();
  9448. };
  9449. /**
  9450. * Gets the far frustum plane transformed by the transform matrix
  9451. * @param transform transformation matrix to be applied to the resulting frustum plane
  9452. * @param frustumPlane the resuling frustum plane
  9453. */
  9454. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  9455. var m = transform.m;
  9456. frustumPlane.normal.x = m[3] - m[2];
  9457. frustumPlane.normal.y = m[7] - m[6];
  9458. frustumPlane.normal.z = m[11] - m[10];
  9459. frustumPlane.d = m[15] - m[14];
  9460. frustumPlane.normalize();
  9461. };
  9462. /**
  9463. * Gets the left frustum plane transformed by the transform matrix
  9464. * @param transform transformation matrix to be applied to the resulting frustum plane
  9465. * @param frustumPlane the resuling frustum plane
  9466. */
  9467. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  9468. var m = transform.m;
  9469. frustumPlane.normal.x = m[3] + m[0];
  9470. frustumPlane.normal.y = m[7] + m[4];
  9471. frustumPlane.normal.z = m[11] + m[8];
  9472. frustumPlane.d = m[15] + m[12];
  9473. frustumPlane.normalize();
  9474. };
  9475. /**
  9476. * Gets the right frustum plane transformed by the transform matrix
  9477. * @param transform transformation matrix to be applied to the resulting frustum plane
  9478. * @param frustumPlane the resuling frustum plane
  9479. */
  9480. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  9481. var m = transform.m;
  9482. frustumPlane.normal.x = m[3] - m[0];
  9483. frustumPlane.normal.y = m[7] - m[4];
  9484. frustumPlane.normal.z = m[11] - m[8];
  9485. frustumPlane.d = m[15] - m[12];
  9486. frustumPlane.normalize();
  9487. };
  9488. /**
  9489. * Gets the top frustum plane transformed by the transform matrix
  9490. * @param transform transformation matrix to be applied to the resulting frustum plane
  9491. * @param frustumPlane the resuling frustum plane
  9492. */
  9493. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  9494. var m = transform.m;
  9495. frustumPlane.normal.x = m[3] - m[1];
  9496. frustumPlane.normal.y = m[7] - m[5];
  9497. frustumPlane.normal.z = m[11] - m[9];
  9498. frustumPlane.d = m[15] - m[13];
  9499. frustumPlane.normalize();
  9500. };
  9501. /**
  9502. * Gets the bottom frustum plane transformed by the transform matrix
  9503. * @param transform transformation matrix to be applied to the resulting frustum plane
  9504. * @param frustumPlane the resuling frustum plane
  9505. */
  9506. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  9507. var m = transform.m;
  9508. frustumPlane.normal.x = m[3] + m[1];
  9509. frustumPlane.normal.y = m[7] + m[5];
  9510. frustumPlane.normal.z = m[11] + m[9];
  9511. frustumPlane.d = m[15] + m[13];
  9512. frustumPlane.normalize();
  9513. };
  9514. /**
  9515. * Sets the given array "frustumPlanes" with the 6 Frustum planes computed by the given transformation matrix.
  9516. * @param transform transformation matrix to be applied to the resulting frustum planes
  9517. * @param frustumPlanes the resuling frustum planes
  9518. */
  9519. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  9520. // Near
  9521. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  9522. // Far
  9523. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  9524. // Left
  9525. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  9526. // Right
  9527. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  9528. // Top
  9529. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  9530. // Bottom
  9531. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  9532. };
  9533. return Frustum;
  9534. }());
  9535. BABYLON.Frustum = Frustum;
  9536. /** Defines supported spaces */
  9537. var Space;
  9538. (function (Space) {
  9539. /** Local (object) space */
  9540. Space[Space["LOCAL"] = 0] = "LOCAL";
  9541. /** World space */
  9542. Space[Space["WORLD"] = 1] = "WORLD";
  9543. /** Bone space */
  9544. Space[Space["BONE"] = 2] = "BONE";
  9545. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  9546. /** Defines the 3 main axes */
  9547. var Axis = /** @class */ (function () {
  9548. function Axis() {
  9549. }
  9550. /** X axis */
  9551. Axis.X = new Vector3(1.0, 0.0, 0.0);
  9552. /** Y axis */
  9553. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  9554. /** Z axis */
  9555. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  9556. return Axis;
  9557. }());
  9558. BABYLON.Axis = Axis;
  9559. /** Class used to represent a Bezier curve */
  9560. var BezierCurve = /** @class */ (function () {
  9561. function BezierCurve() {
  9562. }
  9563. /**
  9564. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the given x1, y1, x2, y2 floats
  9565. * @param t defines the time
  9566. * @param x1 defines the left coordinate on X axis
  9567. * @param y1 defines the left coordinate on Y axis
  9568. * @param x2 defines the right coordinate on X axis
  9569. * @param y2 defines the right coordinate on Y axis
  9570. * @returns the interpolated value
  9571. */
  9572. BezierCurve.Interpolate = function (t, x1, y1, x2, y2) {
  9573. // Extract X (which is equal to time here)
  9574. var f0 = 1 - 3 * x2 + 3 * x1;
  9575. var f1 = 3 * x2 - 6 * x1;
  9576. var f2 = 3 * x1;
  9577. var refinedT = t;
  9578. for (var i = 0; i < 5; i++) {
  9579. var refinedT2 = refinedT * refinedT;
  9580. var refinedT3 = refinedT2 * refinedT;
  9581. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  9582. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  9583. refinedT -= (x - t) * slope;
  9584. refinedT = Math.min(1, Math.max(0, refinedT));
  9585. }
  9586. // Resolve cubic bezier for the given x
  9587. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  9588. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  9589. Math.pow(refinedT, 3);
  9590. };
  9591. return BezierCurve;
  9592. }());
  9593. BABYLON.BezierCurve = BezierCurve;
  9594. /**
  9595. * Defines potential orientation for back face culling
  9596. */
  9597. var Orientation;
  9598. (function (Orientation) {
  9599. /**
  9600. * Clockwise
  9601. */
  9602. Orientation[Orientation["CW"] = 0] = "CW";
  9603. /** Counter clockwise */
  9604. Orientation[Orientation["CCW"] = 1] = "CCW";
  9605. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  9606. /**
  9607. * Defines angle representation
  9608. */
  9609. var Angle = /** @class */ (function () {
  9610. /**
  9611. * Creates an Angle object of "radians" radians (float).
  9612. */
  9613. function Angle(radians) {
  9614. this._radians = radians;
  9615. if (this._radians < 0.0) {
  9616. this._radians += (2.0 * Math.PI);
  9617. }
  9618. }
  9619. /**
  9620. * Get value in degrees
  9621. * @returns the Angle value in degrees (float)
  9622. */
  9623. Angle.prototype.degrees = function () {
  9624. return this._radians * 180.0 / Math.PI;
  9625. };
  9626. /**
  9627. * Get value in radians
  9628. * @returns the Angle value in radians (float)
  9629. */
  9630. Angle.prototype.radians = function () {
  9631. return this._radians;
  9632. };
  9633. /**
  9634. * Gets a new Angle object valued with the angle value in radians between the two given vectors
  9635. * @param a defines first vector
  9636. * @param b defines second vector
  9637. * @returns a new Angle
  9638. */
  9639. Angle.BetweenTwoPoints = function (a, b) {
  9640. var delta = b.subtract(a);
  9641. var theta = Math.atan2(delta.y, delta.x);
  9642. return new Angle(theta);
  9643. };
  9644. /**
  9645. * Gets a new Angle object from the given float in radians
  9646. * @param radians defines the angle value in radians
  9647. * @returns a new Angle
  9648. */
  9649. Angle.FromRadians = function (radians) {
  9650. return new Angle(radians);
  9651. };
  9652. /**
  9653. * Gets a new Angle object from the given float in degrees
  9654. * @param degrees defines the angle value in degrees
  9655. * @returns a new Angle
  9656. */
  9657. Angle.FromDegrees = function (degrees) {
  9658. return new Angle(degrees * Math.PI / 180.0);
  9659. };
  9660. return Angle;
  9661. }());
  9662. BABYLON.Angle = Angle;
  9663. /**
  9664. * This represents an arc in a 2d space.
  9665. */
  9666. var Arc2 = /** @class */ (function () {
  9667. /**
  9668. * Creates an Arc object from the three given points : start, middle and end.
  9669. * @param startPoint Defines the start point of the arc
  9670. * @param midPoint Defines the midlle point of the arc
  9671. * @param endPoint Defines the end point of the arc
  9672. */
  9673. function Arc2(
  9674. /** Defines the start point of the arc */
  9675. startPoint,
  9676. /** Defines the mid point of the arc */
  9677. midPoint,
  9678. /** Defines the end point of the arc */
  9679. endPoint) {
  9680. this.startPoint = startPoint;
  9681. this.midPoint = midPoint;
  9682. this.endPoint = endPoint;
  9683. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  9684. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  9685. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  9686. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  9687. 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);
  9688. this.radius = this.centerPoint.subtract(this.startPoint).length();
  9689. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  9690. var a1 = this.startAngle.degrees();
  9691. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  9692. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  9693. // angles correction
  9694. if (a2 - a1 > +180.0) {
  9695. a2 -= 360.0;
  9696. }
  9697. if (a2 - a1 < -180.0) {
  9698. a2 += 360.0;
  9699. }
  9700. if (a3 - a2 > +180.0) {
  9701. a3 -= 360.0;
  9702. }
  9703. if (a3 - a2 < -180.0) {
  9704. a3 += 360.0;
  9705. }
  9706. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  9707. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  9708. }
  9709. return Arc2;
  9710. }());
  9711. BABYLON.Arc2 = Arc2;
  9712. /**
  9713. * Represents a 2D path made up of multiple 2D points
  9714. */
  9715. var Path2 = /** @class */ (function () {
  9716. /**
  9717. * Creates a Path2 object from the starting 2D coordinates x and y.
  9718. * @param x the starting points x value
  9719. * @param y the starting points y value
  9720. */
  9721. function Path2(x, y) {
  9722. this._points = new Array();
  9723. this._length = 0.0;
  9724. /**
  9725. * If the path start and end point are the same
  9726. */
  9727. this.closed = false;
  9728. this._points.push(new Vector2(x, y));
  9729. }
  9730. /**
  9731. * Adds a new segment until the given coordinates (x, y) to the current Path2.
  9732. * @param x the added points x value
  9733. * @param y the added points y value
  9734. * @returns the updated Path2.
  9735. */
  9736. Path2.prototype.addLineTo = function (x, y) {
  9737. if (this.closed) {
  9738. return this;
  9739. }
  9740. var newPoint = new Vector2(x, y);
  9741. var previousPoint = this._points[this._points.length - 1];
  9742. this._points.push(newPoint);
  9743. this._length += newPoint.subtract(previousPoint).length();
  9744. return this;
  9745. };
  9746. /**
  9747. * 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.
  9748. * @param midX middle point x value
  9749. * @param midY middle point y value
  9750. * @param endX end point x value
  9751. * @param endY end point y value
  9752. * @param numberOfSegments (default: 36)
  9753. * @returns the updated Path2.
  9754. */
  9755. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  9756. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  9757. if (this.closed) {
  9758. return this;
  9759. }
  9760. var startPoint = this._points[this._points.length - 1];
  9761. var midPoint = new Vector2(midX, midY);
  9762. var endPoint = new Vector2(endX, endY);
  9763. var arc = new Arc2(startPoint, midPoint, endPoint);
  9764. var increment = arc.angle.radians() / numberOfSegments;
  9765. if (arc.orientation === Orientation.CW) {
  9766. increment *= -1;
  9767. }
  9768. var currentAngle = arc.startAngle.radians() + increment;
  9769. for (var i = 0; i < numberOfSegments; i++) {
  9770. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  9771. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  9772. this.addLineTo(x, y);
  9773. currentAngle += increment;
  9774. }
  9775. return this;
  9776. };
  9777. /**
  9778. * Closes the Path2.
  9779. * @returns the Path2.
  9780. */
  9781. Path2.prototype.close = function () {
  9782. this.closed = true;
  9783. return this;
  9784. };
  9785. /**
  9786. * Gets the sum of the distance between each sequential point in the path
  9787. * @returns the Path2 total length (float).
  9788. */
  9789. Path2.prototype.length = function () {
  9790. var result = this._length;
  9791. if (!this.closed) {
  9792. var lastPoint = this._points[this._points.length - 1];
  9793. var firstPoint = this._points[0];
  9794. result += (firstPoint.subtract(lastPoint).length());
  9795. }
  9796. return result;
  9797. };
  9798. /**
  9799. * Gets the points which construct the path
  9800. * @returns the Path2 internal array of points.
  9801. */
  9802. Path2.prototype.getPoints = function () {
  9803. return this._points;
  9804. };
  9805. /**
  9806. * Retreives the point at the distance aways from the starting point
  9807. * @param normalizedLengthPosition the length along the path to retreive the point from
  9808. * @returns a new Vector2 located at a percentage of the Path2 total length on this path.
  9809. */
  9810. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  9811. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  9812. return Vector2.Zero();
  9813. }
  9814. var lengthPosition = normalizedLengthPosition * this.length();
  9815. var previousOffset = 0;
  9816. for (var i = 0; i < this._points.length; i++) {
  9817. var j = (i + 1) % this._points.length;
  9818. var a = this._points[i];
  9819. var b = this._points[j];
  9820. var bToA = b.subtract(a);
  9821. var nextOffset = (bToA.length() + previousOffset);
  9822. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  9823. var dir = bToA.normalize();
  9824. var localOffset = lengthPosition - previousOffset;
  9825. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  9826. }
  9827. previousOffset = nextOffset;
  9828. }
  9829. return Vector2.Zero();
  9830. };
  9831. /**
  9832. * Creates a new path starting from an x and y position
  9833. * @param x starting x value
  9834. * @param y starting y value
  9835. * @returns a new Path2 starting at the coordinates (x, y).
  9836. */
  9837. Path2.StartingAt = function (x, y) {
  9838. return new Path2(x, y);
  9839. };
  9840. return Path2;
  9841. }());
  9842. BABYLON.Path2 = Path2;
  9843. /**
  9844. * Represents a 3D path made up of multiple 3D points
  9845. */
  9846. var Path3D = /** @class */ (function () {
  9847. /**
  9848. * new Path3D(path, normal, raw)
  9849. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  9850. * please read the description in the tutorial : https://doc.babylonjs.com/how_to/how_to_use_path3d
  9851. * @param path an array of Vector3, the curve axis of the Path3D
  9852. * @param normal (options) Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  9853. * @param raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  9854. */
  9855. function Path3D(
  9856. /**
  9857. * an array of Vector3, the curve axis of the Path3D
  9858. */
  9859. path, firstNormal, raw) {
  9860. if (firstNormal === void 0) { firstNormal = null; }
  9861. this.path = path;
  9862. this._curve = new Array();
  9863. this._distances = new Array();
  9864. this._tangents = new Array();
  9865. this._normals = new Array();
  9866. this._binormals = new Array();
  9867. for (var p = 0; p < path.length; p++) {
  9868. this._curve[p] = path[p].clone(); // hard copy
  9869. }
  9870. this._raw = raw || false;
  9871. this._compute(firstNormal);
  9872. }
  9873. /**
  9874. * Returns the Path3D array of successive Vector3 designing its curve.
  9875. * @returns the Path3D array of successive Vector3 designing its curve.
  9876. */
  9877. Path3D.prototype.getCurve = function () {
  9878. return this._curve;
  9879. };
  9880. /**
  9881. * Returns an array populated with tangent vectors on each Path3D curve point.
  9882. * @returns an array populated with tangent vectors on each Path3D curve point.
  9883. */
  9884. Path3D.prototype.getTangents = function () {
  9885. return this._tangents;
  9886. };
  9887. /**
  9888. * Returns an array populated with normal vectors on each Path3D curve point.
  9889. * @returns an array populated with normal vectors on each Path3D curve point.
  9890. */
  9891. Path3D.prototype.getNormals = function () {
  9892. return this._normals;
  9893. };
  9894. /**
  9895. * Returns an array populated with binormal vectors on each Path3D curve point.
  9896. * @returns an array populated with binormal vectors on each Path3D curve point.
  9897. */
  9898. Path3D.prototype.getBinormals = function () {
  9899. return this._binormals;
  9900. };
  9901. /**
  9902. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  9903. * @returns an array populated with distances (float) of the i-th point from the first curve point.
  9904. */
  9905. Path3D.prototype.getDistances = function () {
  9906. return this._distances;
  9907. };
  9908. /**
  9909. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  9910. * @param path path which all values are copied into the curves points
  9911. * @param firstNormal which should be projected onto the curve
  9912. * @returns the same object updated.
  9913. */
  9914. Path3D.prototype.update = function (path, firstNormal) {
  9915. if (firstNormal === void 0) { firstNormal = null; }
  9916. for (var p = 0; p < path.length; p++) {
  9917. this._curve[p].x = path[p].x;
  9918. this._curve[p].y = path[p].y;
  9919. this._curve[p].z = path[p].z;
  9920. }
  9921. this._compute(firstNormal);
  9922. return this;
  9923. };
  9924. // private function compute() : computes tangents, normals and binormals
  9925. Path3D.prototype._compute = function (firstNormal) {
  9926. var l = this._curve.length;
  9927. // first and last tangents
  9928. this._tangents[0] = this._getFirstNonNullVector(0);
  9929. if (!this._raw) {
  9930. this._tangents[0].normalize();
  9931. }
  9932. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  9933. if (!this._raw) {
  9934. this._tangents[l - 1].normalize();
  9935. }
  9936. // normals and binormals at first point : arbitrary vector with _normalVector()
  9937. var tg0 = this._tangents[0];
  9938. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  9939. this._normals[0] = pp0;
  9940. if (!this._raw) {
  9941. this._normals[0].normalize();
  9942. }
  9943. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  9944. if (!this._raw) {
  9945. this._binormals[0].normalize();
  9946. }
  9947. this._distances[0] = 0.0;
  9948. // normals and binormals : next points
  9949. var prev; // previous vector (segment)
  9950. var cur; // current vector (segment)
  9951. var curTang; // current tangent
  9952. // previous normal
  9953. var prevBinor; // previous binormal
  9954. for (var i = 1; i < l; i++) {
  9955. // tangents
  9956. prev = this._getLastNonNullVector(i);
  9957. if (i < l - 1) {
  9958. cur = this._getFirstNonNullVector(i);
  9959. this._tangents[i] = prev.add(cur);
  9960. this._tangents[i].normalize();
  9961. }
  9962. this._distances[i] = this._distances[i - 1] + prev.length();
  9963. // normals and binormals
  9964. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  9965. curTang = this._tangents[i];
  9966. prevBinor = this._binormals[i - 1];
  9967. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  9968. if (!this._raw) {
  9969. this._normals[i].normalize();
  9970. }
  9971. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  9972. if (!this._raw) {
  9973. this._binormals[i].normalize();
  9974. }
  9975. }
  9976. };
  9977. // private function getFirstNonNullVector(index)
  9978. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  9979. Path3D.prototype._getFirstNonNullVector = function (index) {
  9980. var i = 1;
  9981. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  9982. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  9983. i++;
  9984. nNVector = this._curve[index + i].subtract(this._curve[index]);
  9985. }
  9986. return nNVector;
  9987. };
  9988. // private function getLastNonNullVector(index)
  9989. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  9990. Path3D.prototype._getLastNonNullVector = function (index) {
  9991. var i = 1;
  9992. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  9993. while (nLVector.length() === 0 && index > i + 1) {
  9994. i++;
  9995. nLVector = this._curve[index].subtract(this._curve[index - i]);
  9996. }
  9997. return nLVector;
  9998. };
  9999. // private function normalVector(v0, vt, va) :
  10000. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  10001. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  10002. Path3D.prototype._normalVector = function (v0, vt, va) {
  10003. var normal0;
  10004. var tgl = vt.length();
  10005. if (tgl === 0.0) {
  10006. tgl = 1.0;
  10007. }
  10008. if (va === undefined || va === null) {
  10009. var point;
  10010. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) { // search for a point in the plane
  10011. point = new Vector3(0.0, -1.0, 0.0);
  10012. }
  10013. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  10014. point = new Vector3(1.0, 0.0, 0.0);
  10015. }
  10016. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  10017. point = new Vector3(0.0, 0.0, 1.0);
  10018. }
  10019. else {
  10020. point = Vector3.Zero();
  10021. }
  10022. normal0 = Vector3.Cross(vt, point);
  10023. }
  10024. else {
  10025. normal0 = Vector3.Cross(vt, va);
  10026. Vector3.CrossToRef(normal0, vt, normal0);
  10027. }
  10028. normal0.normalize();
  10029. return normal0;
  10030. };
  10031. return Path3D;
  10032. }());
  10033. BABYLON.Path3D = Path3D;
  10034. /**
  10035. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  10036. * A Curve3 is designed from a series of successive Vector3.
  10037. * @see https://doc.babylonjs.com/how_to/how_to_use_curve3
  10038. */
  10039. var Curve3 = /** @class */ (function () {
  10040. /**
  10041. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  10042. * A Curve3 is designed from a series of successive Vector3.
  10043. * Tuto : https://doc.babylonjs.com/how_to/how_to_use_curve3#curve3-object
  10044. * @param points points which make up the curve
  10045. */
  10046. function Curve3(points) {
  10047. this._length = 0.0;
  10048. this._points = points;
  10049. this._length = this._computeLength(points);
  10050. }
  10051. /**
  10052. * Returns a Curve3 object along a Quadratic Bezier curve : https://doc.babylonjs.com/how_to/how_to_use_curve3#quadratic-bezier-curve
  10053. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  10054. * @param v1 (Vector3) the control point
  10055. * @param v2 (Vector3) the end point of the Quadratic Bezier
  10056. * @param nbPoints (integer) the wanted number of points in the curve
  10057. * @returns the created Curve3
  10058. */
  10059. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  10060. nbPoints = nbPoints > 2 ? nbPoints : 3;
  10061. var bez = new Array();
  10062. var equation = function (t, val0, val1, val2) {
  10063. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  10064. return res;
  10065. };
  10066. for (var i = 0; i <= nbPoints; i++) {
  10067. 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)));
  10068. }
  10069. return new Curve3(bez);
  10070. };
  10071. /**
  10072. * Returns a Curve3 object along a Cubic Bezier curve : https://doc.babylonjs.com/how_to/how_to_use_curve3#cubic-bezier-curve
  10073. * @param v0 (Vector3) the origin point of the Cubic Bezier
  10074. * @param v1 (Vector3) the first control point
  10075. * @param v2 (Vector3) the second control point
  10076. * @param v3 (Vector3) the end point of the Cubic Bezier
  10077. * @param nbPoints (integer) the wanted number of points in the curve
  10078. * @returns the created Curve3
  10079. */
  10080. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  10081. nbPoints = nbPoints > 3 ? nbPoints : 4;
  10082. var bez = new Array();
  10083. var equation = function (t, val0, val1, val2, val3) {
  10084. 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;
  10085. return res;
  10086. };
  10087. for (var i = 0; i <= nbPoints; i++) {
  10088. 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)));
  10089. }
  10090. return new Curve3(bez);
  10091. };
  10092. /**
  10093. * Returns a Curve3 object along a Hermite Spline curve : https://doc.babylonjs.com/how_to/how_to_use_curve3#hermite-spline
  10094. * @param p1 (Vector3) the origin point of the Hermite Spline
  10095. * @param t1 (Vector3) the tangent vector at the origin point
  10096. * @param p2 (Vector3) the end point of the Hermite Spline
  10097. * @param t2 (Vector3) the tangent vector at the end point
  10098. * @param nbPoints (integer) the wanted number of points in the curve
  10099. * @returns the created Curve3
  10100. */
  10101. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  10102. var hermite = new Array();
  10103. var step = 1.0 / nbPoints;
  10104. for (var i = 0; i <= nbPoints; i++) {
  10105. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  10106. }
  10107. return new Curve3(hermite);
  10108. };
  10109. /**
  10110. * Returns a Curve3 object along a CatmullRom Spline curve :
  10111. * @param points (array of Vector3) the points the spline must pass through. At least, four points required
  10112. * @param nbPoints (integer) the wanted number of points between each curve control points
  10113. * @param closed (boolean) optional with default false, when true forms a closed loop from the points
  10114. * @returns the created Curve3
  10115. */
  10116. Curve3.CreateCatmullRomSpline = function (points, nbPoints, closed) {
  10117. var catmullRom = new Array();
  10118. var step = 1.0 / nbPoints;
  10119. var amount = 0.0;
  10120. if (closed) {
  10121. var pointsCount = points.length;
  10122. for (var i = 0; i < pointsCount; i++) {
  10123. amount = 0;
  10124. for (var c = 0; c < nbPoints; c++) {
  10125. catmullRom.push(Vector3.CatmullRom(points[i % pointsCount], points[(i + 1) % pointsCount], points[(i + 2) % pointsCount], points[(i + 3) % pointsCount], amount));
  10126. amount += step;
  10127. }
  10128. }
  10129. catmullRom.push(catmullRom[0]);
  10130. }
  10131. else {
  10132. var totalPoints = new Array();
  10133. totalPoints.push(points[0].clone());
  10134. Array.prototype.push.apply(totalPoints, points);
  10135. totalPoints.push(points[points.length - 1].clone());
  10136. for (var i = 0; i < totalPoints.length - 3; i++) {
  10137. amount = 0;
  10138. for (var c = 0; c < nbPoints; c++) {
  10139. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  10140. amount += step;
  10141. }
  10142. }
  10143. i--;
  10144. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  10145. }
  10146. return new Curve3(catmullRom);
  10147. };
  10148. /**
  10149. * @returns the Curve3 stored array of successive Vector3
  10150. */
  10151. Curve3.prototype.getPoints = function () {
  10152. return this._points;
  10153. };
  10154. /**
  10155. * @returns the computed length (float) of the curve.
  10156. */
  10157. Curve3.prototype.length = function () {
  10158. return this._length;
  10159. };
  10160. /**
  10161. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  10162. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  10163. * curveA and curveB keep unchanged.
  10164. * @param curve the curve to continue from this curve
  10165. * @returns the newly constructed curve
  10166. */
  10167. Curve3.prototype.continue = function (curve) {
  10168. var lastPoint = this._points[this._points.length - 1];
  10169. var continuedPoints = this._points.slice();
  10170. var curvePoints = curve.getPoints();
  10171. for (var i = 1; i < curvePoints.length; i++) {
  10172. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  10173. }
  10174. var continuedCurve = new Curve3(continuedPoints);
  10175. return continuedCurve;
  10176. };
  10177. Curve3.prototype._computeLength = function (path) {
  10178. var l = 0;
  10179. for (var i = 1; i < path.length; i++) {
  10180. l += (path[i].subtract(path[i - 1])).length();
  10181. }
  10182. return l;
  10183. };
  10184. return Curve3;
  10185. }());
  10186. BABYLON.Curve3 = Curve3;
  10187. // Vertex formats
  10188. /**
  10189. * Contains position and normal vectors for a vertex
  10190. */
  10191. var PositionNormalVertex = /** @class */ (function () {
  10192. /**
  10193. * Creates a PositionNormalVertex
  10194. * @param position the position of the vertex (defaut: 0,0,0)
  10195. * @param normal the normal of the vertex (defaut: 0,1,0)
  10196. */
  10197. function PositionNormalVertex(
  10198. /** the position of the vertex (defaut: 0,0,0) */
  10199. position,
  10200. /** the normal of the vertex (defaut: 0,1,0) */
  10201. normal) {
  10202. if (position === void 0) { position = Vector3.Zero(); }
  10203. if (normal === void 0) { normal = Vector3.Up(); }
  10204. this.position = position;
  10205. this.normal = normal;
  10206. }
  10207. /**
  10208. * Clones the PositionNormalVertex
  10209. * @returns the cloned PositionNormalVertex
  10210. */
  10211. PositionNormalVertex.prototype.clone = function () {
  10212. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  10213. };
  10214. return PositionNormalVertex;
  10215. }());
  10216. BABYLON.PositionNormalVertex = PositionNormalVertex;
  10217. /**
  10218. * Contains position, normal and uv vectors for a vertex
  10219. */
  10220. var PositionNormalTextureVertex = /** @class */ (function () {
  10221. /**
  10222. * Creates a PositionNormalTextureVertex
  10223. * @param position the position of the vertex (defaut: 0,0,0)
  10224. * @param normal the normal of the vertex (defaut: 0,1,0)
  10225. * @param uv the uv of the vertex (default: 0,0)
  10226. */
  10227. function PositionNormalTextureVertex(
  10228. /** the position of the vertex (defaut: 0,0,0) */
  10229. position,
  10230. /** the normal of the vertex (defaut: 0,1,0) */
  10231. normal,
  10232. /** the uv of the vertex (default: 0,0) */
  10233. uv) {
  10234. if (position === void 0) { position = Vector3.Zero(); }
  10235. if (normal === void 0) { normal = Vector3.Up(); }
  10236. if (uv === void 0) { uv = Vector2.Zero(); }
  10237. this.position = position;
  10238. this.normal = normal;
  10239. this.uv = uv;
  10240. }
  10241. /**
  10242. * Clones the PositionNormalTextureVertex
  10243. * @returns the cloned PositionNormalTextureVertex
  10244. */
  10245. PositionNormalTextureVertex.prototype.clone = function () {
  10246. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  10247. };
  10248. return PositionNormalTextureVertex;
  10249. }());
  10250. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  10251. // Temporary pre-allocated objects for engine internal use
  10252. // usage in any internal function :
  10253. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  10254. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  10255. /**
  10256. * @hidden
  10257. */
  10258. var Tmp = /** @class */ (function () {
  10259. function Tmp() {
  10260. }
  10261. Tmp.Color3 = BABYLON.Tools.BuildArray(3, Color3.Black);
  10262. Tmp.Color4 = BABYLON.Tools.BuildArray(3, function () { return new Color4(0, 0, 0, 0); });
  10263. Tmp.Vector2 = BABYLON.Tools.BuildArray(3, Vector2.Zero); // 3 temp Vector2 at once should be enough
  10264. Tmp.Vector3 = BABYLON.Tools.BuildArray(13, Vector3.Zero); // 13 temp Vector3 at once should be enough
  10265. Tmp.Vector4 = BABYLON.Tools.BuildArray(3, Vector4.Zero); // 3 temp Vector4 at once should be enough
  10266. Tmp.Quaternion = BABYLON.Tools.BuildArray(2, Quaternion.Zero); // 2 temp Quaternion at once should be enough
  10267. Tmp.Matrix = BABYLON.Tools.BuildArray(8, Matrix.Identity); // 8 temp Matrices at once should be enough
  10268. return Tmp;
  10269. }());
  10270. BABYLON.Tmp = Tmp;
  10271. /**
  10272. * @hidden
  10273. * Same as Tmp but not exported to keep it only for math functions to avoid conflicts
  10274. */
  10275. var MathTmp = /** @class */ (function () {
  10276. function MathTmp() {
  10277. }
  10278. MathTmp.Vector3 = BABYLON.Tools.BuildArray(6, Vector3.Zero);
  10279. MathTmp.Matrix = BABYLON.Tools.BuildArray(2, Matrix.Identity);
  10280. MathTmp.Quaternion = BABYLON.Tools.BuildArray(3, Quaternion.Zero);
  10281. return MathTmp;
  10282. }());
  10283. })(BABYLON || (BABYLON = {}));
  10284. //# sourceMappingURL=babylon.math.js.map
  10285. var BABYLON;
  10286. (function (BABYLON) {
  10287. /**
  10288. * Scalar computation library
  10289. */
  10290. var Scalar = /** @class */ (function () {
  10291. function Scalar() {
  10292. }
  10293. /**
  10294. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  10295. * @param a number
  10296. * @param b number
  10297. * @param epsilon (default = 1.401298E-45)
  10298. * @returns true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  10299. */
  10300. Scalar.WithinEpsilon = function (a, b, epsilon) {
  10301. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  10302. var num = a - b;
  10303. return -epsilon <= num && num <= epsilon;
  10304. };
  10305. /**
  10306. * Returns a string : the upper case translation of the number i to hexadecimal.
  10307. * @param i number
  10308. * @returns the upper case translation of the number i to hexadecimal.
  10309. */
  10310. Scalar.ToHex = function (i) {
  10311. var str = i.toString(16);
  10312. if (i <= 15) {
  10313. return ("0" + str).toUpperCase();
  10314. }
  10315. return str.toUpperCase();
  10316. };
  10317. /**
  10318. * Returns -1 if value is negative and +1 is value is positive.
  10319. * @param value the value
  10320. * @returns the value itself if it's equal to zero.
  10321. */
  10322. Scalar.Sign = function (value) {
  10323. value = +value; // convert to a number
  10324. if (value === 0 || isNaN(value)) {
  10325. return value;
  10326. }
  10327. return value > 0 ? 1 : -1;
  10328. };
  10329. /**
  10330. * Returns the value itself if it's between min and max.
  10331. * Returns min if the value is lower than min.
  10332. * Returns max if the value is greater than max.
  10333. * @param value the value to clmap
  10334. * @param min the min value to clamp to (default: 0)
  10335. * @param max the max value to clamp to (default: 1)
  10336. * @returns the clamped value
  10337. */
  10338. Scalar.Clamp = function (value, min, max) {
  10339. if (min === void 0) { min = 0; }
  10340. if (max === void 0) { max = 1; }
  10341. return Math.min(max, Math.max(min, value));
  10342. };
  10343. /**
  10344. * the log2 of value.
  10345. * @param value the value to compute log2 of
  10346. * @returns the log2 of value.
  10347. */
  10348. Scalar.Log2 = function (value) {
  10349. return Math.log(value) * Math.LOG2E;
  10350. };
  10351. /**
  10352. * Loops the value, so that it is never larger than length and never smaller than 0.
  10353. *
  10354. * This is similar to the modulo operator but it works with floating point numbers.
  10355. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  10356. * With t = 5 and length = 2.5, the result would be 0.0.
  10357. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  10358. * @param value the value
  10359. * @param length the length
  10360. * @returns the looped value
  10361. */
  10362. Scalar.Repeat = function (value, length) {
  10363. return value - Math.floor(value / length) * length;
  10364. };
  10365. /**
  10366. * Normalize the value between 0.0 and 1.0 using min and max values
  10367. * @param value value to normalize
  10368. * @param min max to normalize between
  10369. * @param max min to normalize between
  10370. * @returns the normalized value
  10371. */
  10372. Scalar.Normalize = function (value, min, max) {
  10373. return (value - min) / (max - min);
  10374. };
  10375. /**
  10376. * Denormalize the value from 0.0 and 1.0 using min and max values
  10377. * @param normalized value to denormalize
  10378. * @param min max to denormalize between
  10379. * @param max min to denormalize between
  10380. * @returns the denormalized value
  10381. */
  10382. Scalar.Denormalize = function (normalized, min, max) {
  10383. return (normalized * (max - min) + min);
  10384. };
  10385. /**
  10386. * Calculates the shortest difference between two given angles given in degrees.
  10387. * @param current current angle in degrees
  10388. * @param target target angle in degrees
  10389. * @returns the delta
  10390. */
  10391. Scalar.DeltaAngle = function (current, target) {
  10392. var num = Scalar.Repeat(target - current, 360.0);
  10393. if (num > 180.0) {
  10394. num -= 360.0;
  10395. }
  10396. return num;
  10397. };
  10398. /**
  10399. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  10400. * @param tx value
  10401. * @param length length
  10402. * @returns The returned value will move back and forth between 0 and length
  10403. */
  10404. Scalar.PingPong = function (tx, length) {
  10405. var t = Scalar.Repeat(tx, length * 2.0);
  10406. return length - Math.abs(t - length);
  10407. };
  10408. /**
  10409. * Interpolates between min and max with smoothing at the limits.
  10410. *
  10411. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  10412. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  10413. * @param from from
  10414. * @param to to
  10415. * @param tx value
  10416. * @returns the smooth stepped value
  10417. */
  10418. Scalar.SmoothStep = function (from, to, tx) {
  10419. var t = Scalar.Clamp(tx);
  10420. t = -2.0 * t * t * t + 3.0 * t * t;
  10421. return to * t + from * (1.0 - t);
  10422. };
  10423. /**
  10424. * Moves a value current towards target.
  10425. *
  10426. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  10427. * Negative values of maxDelta pushes the value away from target.
  10428. * @param current current value
  10429. * @param target target value
  10430. * @param maxDelta max distance to move
  10431. * @returns resulting value
  10432. */
  10433. Scalar.MoveTowards = function (current, target, maxDelta) {
  10434. var result = 0;
  10435. if (Math.abs(target - current) <= maxDelta) {
  10436. result = target;
  10437. }
  10438. else {
  10439. result = current + Scalar.Sign(target - current) * maxDelta;
  10440. }
  10441. return result;
  10442. };
  10443. /**
  10444. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  10445. *
  10446. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  10447. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  10448. * @param current current value
  10449. * @param target target value
  10450. * @param maxDelta max distance to move
  10451. * @returns resulting angle
  10452. */
  10453. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  10454. var num = Scalar.DeltaAngle(current, target);
  10455. var result = 0;
  10456. if (-maxDelta < num && num < maxDelta) {
  10457. result = target;
  10458. }
  10459. else {
  10460. target = current + num;
  10461. result = Scalar.MoveTowards(current, target, maxDelta);
  10462. }
  10463. return result;
  10464. };
  10465. /**
  10466. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  10467. * @param start start value
  10468. * @param end target value
  10469. * @param amount amount to lerp between
  10470. * @returns the lerped value
  10471. */
  10472. Scalar.Lerp = function (start, end, amount) {
  10473. return start + ((end - start) * amount);
  10474. };
  10475. /**
  10476. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  10477. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  10478. * @param start start value
  10479. * @param end target value
  10480. * @param amount amount to lerp between
  10481. * @returns the lerped value
  10482. */
  10483. Scalar.LerpAngle = function (start, end, amount) {
  10484. var num = Scalar.Repeat(end - start, 360.0);
  10485. if (num > 180.0) {
  10486. num -= 360.0;
  10487. }
  10488. return start + num * Scalar.Clamp(amount);
  10489. };
  10490. /**
  10491. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  10492. * @param a start value
  10493. * @param b target value
  10494. * @param value value between a and b
  10495. * @returns the inverseLerp value
  10496. */
  10497. Scalar.InverseLerp = function (a, b, value) {
  10498. var result = 0;
  10499. if (a != b) {
  10500. result = Scalar.Clamp((value - a) / (b - a));
  10501. }
  10502. else {
  10503. result = 0.0;
  10504. }
  10505. return result;
  10506. };
  10507. /**
  10508. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  10509. * @see http://mathworld.wolfram.com/HermitePolynomial.html
  10510. * @param value1 spline value
  10511. * @param tangent1 spline value
  10512. * @param value2 spline value
  10513. * @param tangent2 spline value
  10514. * @param amount input value
  10515. * @returns hermite result
  10516. */
  10517. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  10518. var squared = amount * amount;
  10519. var cubed = amount * squared;
  10520. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  10521. var part2 = (-2.0 * cubed) + (3.0 * squared);
  10522. var part3 = (cubed - (2.0 * squared)) + amount;
  10523. var part4 = cubed - squared;
  10524. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  10525. };
  10526. /**
  10527. * Returns a random float number between and min and max values
  10528. * @param min min value of random
  10529. * @param max max value of random
  10530. * @returns random value
  10531. */
  10532. Scalar.RandomRange = function (min, max) {
  10533. if (min === max) {
  10534. return min;
  10535. }
  10536. return ((Math.random() * (max - min)) + min);
  10537. };
  10538. /**
  10539. * This function returns percentage of a number in a given range.
  10540. *
  10541. * RangeToPercent(40,20,60) will return 0.5 (50%)
  10542. * RangeToPercent(34,0,100) will return 0.34 (34%)
  10543. * @param number to convert to percentage
  10544. * @param min min range
  10545. * @param max max range
  10546. * @returns the percentage
  10547. */
  10548. Scalar.RangeToPercent = function (number, min, max) {
  10549. return ((number - min) / (max - min));
  10550. };
  10551. /**
  10552. * This function returns number that corresponds to the percentage in a given range.
  10553. *
  10554. * PercentToRange(0.34,0,100) will return 34.
  10555. * @param percent to convert to number
  10556. * @param min min range
  10557. * @param max max range
  10558. * @returns the number
  10559. */
  10560. Scalar.PercentToRange = function (percent, min, max) {
  10561. return ((max - min) * percent + min);
  10562. };
  10563. /**
  10564. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  10565. * @param angle The angle to normalize in radian.
  10566. * @return The converted angle.
  10567. */
  10568. Scalar.NormalizeRadians = function (angle) {
  10569. // More precise but slower version kept for reference.
  10570. // angle = angle % Tools.TwoPi;
  10571. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  10572. //if (angle > Math.PI) {
  10573. // angle -= Tools.TwoPi;
  10574. //}
  10575. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  10576. return angle;
  10577. };
  10578. /**
  10579. * Two pi constants convenient for computation.
  10580. */
  10581. Scalar.TwoPi = Math.PI * 2;
  10582. return Scalar;
  10583. }());
  10584. BABYLON.Scalar = Scalar;
  10585. })(BABYLON || (BABYLON = {}));
  10586. //# sourceMappingURL=babylon.math.scalar.js.map
  10587. //# sourceMappingURL=babylon.mixins.js.map
  10588. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  10589. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  10590. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  10591. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  10592. //# sourceMappingURL=babylon.webgl2.js.map
  10593. var BABYLON;
  10594. (function (BABYLON) {
  10595. var __decoratorInitialStore = {};
  10596. var __mergedStore = {};
  10597. var _copySource = function (creationFunction, source, instanciate) {
  10598. var destination = creationFunction();
  10599. // Tags
  10600. if (BABYLON.Tags) {
  10601. BABYLON.Tags.AddTagsTo(destination, source.tags);
  10602. }
  10603. var classStore = getMergedStore(destination);
  10604. // Properties
  10605. for (var property in classStore) {
  10606. var propertyDescriptor = classStore[property];
  10607. var sourceProperty = source[property];
  10608. var propertyType = propertyDescriptor.type;
  10609. if (sourceProperty !== undefined && sourceProperty !== null) {
  10610. switch (propertyType) {
  10611. case 0: // Value
  10612. case 6: // Mesh reference
  10613. case 11: // Camera reference
  10614. destination[property] = sourceProperty;
  10615. break;
  10616. case 1: // Texture
  10617. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  10618. break;
  10619. case 2: // Color3
  10620. case 3: // FresnelParameters
  10621. case 4: // Vector2
  10622. case 5: // Vector3
  10623. case 7: // Color Curves
  10624. case 10: // Quaternion
  10625. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  10626. break;
  10627. }
  10628. }
  10629. }
  10630. return destination;
  10631. };
  10632. function getDirectStore(target) {
  10633. var classKey = target.getClassName();
  10634. if (!__decoratorInitialStore[classKey]) {
  10635. __decoratorInitialStore[classKey] = {};
  10636. }
  10637. return __decoratorInitialStore[classKey];
  10638. }
  10639. /**
  10640. * Return the list of properties flagged as serializable
  10641. * @param target: host object
  10642. */
  10643. function getMergedStore(target) {
  10644. var classKey = target.getClassName();
  10645. if (__mergedStore[classKey]) {
  10646. return __mergedStore[classKey];
  10647. }
  10648. __mergedStore[classKey] = {};
  10649. var store = __mergedStore[classKey];
  10650. var currentTarget = target;
  10651. var currentKey = classKey;
  10652. while (currentKey) {
  10653. var initialStore = __decoratorInitialStore[currentKey];
  10654. for (var property in initialStore) {
  10655. store[property] = initialStore[property];
  10656. }
  10657. var parent_1 = void 0;
  10658. var done = false;
  10659. do {
  10660. parent_1 = Object.getPrototypeOf(currentTarget);
  10661. if (!parent_1.getClassName) {
  10662. done = true;
  10663. break;
  10664. }
  10665. if (parent_1.getClassName() !== currentKey) {
  10666. break;
  10667. }
  10668. currentTarget = parent_1;
  10669. } while (parent_1);
  10670. if (done) {
  10671. break;
  10672. }
  10673. currentKey = parent_1.getClassName();
  10674. currentTarget = parent_1;
  10675. }
  10676. return store;
  10677. }
  10678. function generateSerializableMember(type, sourceName) {
  10679. return function (target, propertyKey) {
  10680. var classStore = getDirectStore(target);
  10681. if (!classStore[propertyKey]) {
  10682. classStore[propertyKey] = { type: type, sourceName: sourceName };
  10683. }
  10684. };
  10685. }
  10686. function generateExpandMember(setCallback, targetKey) {
  10687. if (targetKey === void 0) { targetKey = null; }
  10688. return function (target, propertyKey) {
  10689. var key = targetKey || ("_" + propertyKey);
  10690. Object.defineProperty(target, propertyKey, {
  10691. get: function () {
  10692. return this[key];
  10693. },
  10694. set: function (value) {
  10695. if (this[key] === value) {
  10696. return;
  10697. }
  10698. this[key] = value;
  10699. target[setCallback].apply(this);
  10700. },
  10701. enumerable: true,
  10702. configurable: true
  10703. });
  10704. };
  10705. }
  10706. function expandToProperty(callback, targetKey) {
  10707. if (targetKey === void 0) { targetKey = null; }
  10708. return generateExpandMember(callback, targetKey);
  10709. }
  10710. BABYLON.expandToProperty = expandToProperty;
  10711. function serialize(sourceName) {
  10712. return generateSerializableMember(0, sourceName); // value member
  10713. }
  10714. BABYLON.serialize = serialize;
  10715. function serializeAsTexture(sourceName) {
  10716. return generateSerializableMember(1, sourceName); // texture member
  10717. }
  10718. BABYLON.serializeAsTexture = serializeAsTexture;
  10719. function serializeAsColor3(sourceName) {
  10720. return generateSerializableMember(2, sourceName); // color3 member
  10721. }
  10722. BABYLON.serializeAsColor3 = serializeAsColor3;
  10723. function serializeAsFresnelParameters(sourceName) {
  10724. return generateSerializableMember(3, sourceName); // fresnel parameters member
  10725. }
  10726. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  10727. function serializeAsVector2(sourceName) {
  10728. return generateSerializableMember(4, sourceName); // vector2 member
  10729. }
  10730. BABYLON.serializeAsVector2 = serializeAsVector2;
  10731. function serializeAsVector3(sourceName) {
  10732. return generateSerializableMember(5, sourceName); // vector3 member
  10733. }
  10734. BABYLON.serializeAsVector3 = serializeAsVector3;
  10735. function serializeAsMeshReference(sourceName) {
  10736. return generateSerializableMember(6, sourceName); // mesh reference member
  10737. }
  10738. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  10739. function serializeAsColorCurves(sourceName) {
  10740. return generateSerializableMember(7, sourceName); // color curves
  10741. }
  10742. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  10743. function serializeAsColor4(sourceName) {
  10744. return generateSerializableMember(8, sourceName); // color 4
  10745. }
  10746. BABYLON.serializeAsColor4 = serializeAsColor4;
  10747. function serializeAsImageProcessingConfiguration(sourceName) {
  10748. return generateSerializableMember(9, sourceName); // image processing
  10749. }
  10750. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  10751. function serializeAsQuaternion(sourceName) {
  10752. return generateSerializableMember(10, sourceName); // quaternion member
  10753. }
  10754. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  10755. /**
  10756. * Decorator used to define property that can be serialized as reference to a camera
  10757. * @param sourceName defines the name of the property to decorate
  10758. */
  10759. function serializeAsCameraReference(sourceName) {
  10760. return generateSerializableMember(11, sourceName); // camera reference member
  10761. }
  10762. BABYLON.serializeAsCameraReference = serializeAsCameraReference;
  10763. /**
  10764. * Class used to help serialization objects
  10765. */
  10766. var SerializationHelper = /** @class */ (function () {
  10767. function SerializationHelper() {
  10768. }
  10769. /**
  10770. * Static function used to serialized a specific entity
  10771. * @param entity defines the entity to serialize
  10772. * @param serializationObject defines the optional target obecjt where serialization data will be stored
  10773. * @returns a JSON compatible object representing the serialization of the entity
  10774. */
  10775. SerializationHelper.Serialize = function (entity, serializationObject) {
  10776. if (!serializationObject) {
  10777. serializationObject = {};
  10778. }
  10779. // Tags
  10780. if (BABYLON.Tags) {
  10781. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  10782. }
  10783. var serializedProperties = getMergedStore(entity);
  10784. // Properties
  10785. for (var property in serializedProperties) {
  10786. var propertyDescriptor = serializedProperties[property];
  10787. var targetPropertyName = propertyDescriptor.sourceName || property;
  10788. var propertyType = propertyDescriptor.type;
  10789. var sourceProperty = entity[property];
  10790. if (sourceProperty !== undefined && sourceProperty !== null) {
  10791. switch (propertyType) {
  10792. case 0: // Value
  10793. serializationObject[targetPropertyName] = sourceProperty;
  10794. break;
  10795. case 1: // Texture
  10796. serializationObject[targetPropertyName] = sourceProperty.serialize();
  10797. break;
  10798. case 2: // Color3
  10799. serializationObject[targetPropertyName] = sourceProperty.asArray();
  10800. break;
  10801. case 3: // FresnelParameters
  10802. serializationObject[targetPropertyName] = sourceProperty.serialize();
  10803. break;
  10804. case 4: // Vector2
  10805. serializationObject[targetPropertyName] = sourceProperty.asArray();
  10806. break;
  10807. case 5: // Vector3
  10808. serializationObject[targetPropertyName] = sourceProperty.asArray();
  10809. break;
  10810. case 6: // Mesh reference
  10811. serializationObject[targetPropertyName] = sourceProperty.id;
  10812. break;
  10813. case 7: // Color Curves
  10814. serializationObject[targetPropertyName] = sourceProperty.serialize();
  10815. break;
  10816. case 8: // Color 4
  10817. serializationObject[targetPropertyName] = sourceProperty.asArray();
  10818. break;
  10819. case 9: // Image Processing
  10820. serializationObject[targetPropertyName] = sourceProperty.serialize();
  10821. break;
  10822. case 10: // Quaternion
  10823. serializationObject[targetPropertyName] = sourceProperty.asArray();
  10824. break;
  10825. case 11: // Camera reference
  10826. serializationObject[targetPropertyName] = sourceProperty.id;
  10827. break;
  10828. }
  10829. }
  10830. }
  10831. return serializationObject;
  10832. };
  10833. /**
  10834. * Creates a new entity from a serialization data object
  10835. * @param creationFunction defines a function used to instanciated the new entity
  10836. * @param source defines the source serialization data
  10837. * @param scene defines the hosting scene
  10838. * @param rootUrl defines the root url for resources
  10839. * @returns a new entity
  10840. */
  10841. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  10842. if (rootUrl === void 0) { rootUrl = null; }
  10843. var destination = creationFunction();
  10844. if (!rootUrl) {
  10845. rootUrl = "";
  10846. }
  10847. // Tags
  10848. if (BABYLON.Tags) {
  10849. BABYLON.Tags.AddTagsTo(destination, source.tags);
  10850. }
  10851. var classStore = getMergedStore(destination);
  10852. // Properties
  10853. for (var property in classStore) {
  10854. var propertyDescriptor = classStore[property];
  10855. var sourceProperty = source[propertyDescriptor.sourceName || property];
  10856. var propertyType = propertyDescriptor.type;
  10857. if (sourceProperty !== undefined && sourceProperty !== null) {
  10858. var dest = destination;
  10859. switch (propertyType) {
  10860. case 0: // Value
  10861. dest[property] = sourceProperty;
  10862. break;
  10863. case 1: // Texture
  10864. if (scene) {
  10865. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  10866. }
  10867. break;
  10868. case 2: // Color3
  10869. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  10870. break;
  10871. case 3: // FresnelParameters
  10872. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  10873. break;
  10874. case 4: // Vector2
  10875. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  10876. break;
  10877. case 5: // Vector3
  10878. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  10879. break;
  10880. case 6: // Mesh reference
  10881. if (scene) {
  10882. dest[property] = scene.getLastMeshByID(sourceProperty);
  10883. }
  10884. break;
  10885. case 7: // Color Curves
  10886. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  10887. break;
  10888. case 8: // Color 4
  10889. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  10890. break;
  10891. case 9: // Image Processing
  10892. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  10893. break;
  10894. case 10: // Quaternion
  10895. dest[property] = BABYLON.Quaternion.FromArray(sourceProperty);
  10896. break;
  10897. case 11: // Camera reference
  10898. if (scene) {
  10899. dest[property] = scene.getCameraByID(sourceProperty);
  10900. }
  10901. break;
  10902. }
  10903. }
  10904. }
  10905. return destination;
  10906. };
  10907. /**
  10908. * Clones an object
  10909. * @param creationFunction defines the function used to instanciate the new object
  10910. * @param source defines the source object
  10911. * @returns the cloned object
  10912. */
  10913. SerializationHelper.Clone = function (creationFunction, source) {
  10914. return _copySource(creationFunction, source, false);
  10915. };
  10916. /**
  10917. * Instanciates a new object based on a source one (some data will be shared between both object)
  10918. * @param creationFunction defines the function used to instanciate the new object
  10919. * @param source defines the source object
  10920. * @returns the new object
  10921. */
  10922. SerializationHelper.Instanciate = function (creationFunction, source) {
  10923. return _copySource(creationFunction, source, true);
  10924. };
  10925. return SerializationHelper;
  10926. }());
  10927. BABYLON.SerializationHelper = SerializationHelper;
  10928. })(BABYLON || (BABYLON = {}));
  10929. //# sourceMappingURL=babylon.decorators.js.map
  10930. var BABYLON;
  10931. (function (BABYLON) {
  10932. /**
  10933. * Wrapper class for promise with external resolve and reject.
  10934. */
  10935. var Deferred = /** @class */ (function () {
  10936. /**
  10937. * Constructor for this deferred object.
  10938. */
  10939. function Deferred() {
  10940. var _this = this;
  10941. this.promise = new Promise(function (resolve, reject) {
  10942. _this._resolve = resolve;
  10943. _this._reject = reject;
  10944. });
  10945. }
  10946. Object.defineProperty(Deferred.prototype, "resolve", {
  10947. /**
  10948. * The resolve method of the promise associated with this deferred object.
  10949. */
  10950. get: function () {
  10951. return this._resolve;
  10952. },
  10953. enumerable: true,
  10954. configurable: true
  10955. });
  10956. Object.defineProperty(Deferred.prototype, "reject", {
  10957. /**
  10958. * The reject method of the promise associated with this deferred object.
  10959. */
  10960. get: function () {
  10961. return this._reject;
  10962. },
  10963. enumerable: true,
  10964. configurable: true
  10965. });
  10966. return Deferred;
  10967. }());
  10968. BABYLON.Deferred = Deferred;
  10969. })(BABYLON || (BABYLON = {}));
  10970. //# sourceMappingURL=babylon.deferred.js.map
  10971. var BABYLON;
  10972. (function (BABYLON) {
  10973. /**
  10974. * A class serves as a medium between the observable and its observers
  10975. */
  10976. var EventState = /** @class */ (function () {
  10977. /**
  10978. * Create a new EventState
  10979. * @param mask defines the mask associated with this state
  10980. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  10981. * @param target defines the original target of the state
  10982. * @param currentTarget defines the current target of the state
  10983. */
  10984. function EventState(mask, skipNextObservers, target, currentTarget) {
  10985. if (skipNextObservers === void 0) { skipNextObservers = false; }
  10986. this.initalize(mask, skipNextObservers, target, currentTarget);
  10987. }
  10988. /**
  10989. * Initialize the current event state
  10990. * @param mask defines the mask associated with this state
  10991. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  10992. * @param target defines the original target of the state
  10993. * @param currentTarget defines the current target of the state
  10994. * @returns the current event state
  10995. */
  10996. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  10997. if (skipNextObservers === void 0) { skipNextObservers = false; }
  10998. this.mask = mask;
  10999. this.skipNextObservers = skipNextObservers;
  11000. this.target = target;
  11001. this.currentTarget = currentTarget;
  11002. return this;
  11003. };
  11004. return EventState;
  11005. }());
  11006. BABYLON.EventState = EventState;
  11007. /**
  11008. * Represent an Observer registered to a given Observable object.
  11009. */
  11010. var Observer = /** @class */ (function () {
  11011. /**
  11012. * Creates a new observer
  11013. * @param callback defines the callback to call when the observer is notified
  11014. * @param mask defines the mask of the observer (used to filter notifications)
  11015. * @param scope defines the current scope used to restore the JS context
  11016. */
  11017. function Observer(
  11018. /**
  11019. * Defines the callback to call when the observer is notified
  11020. */
  11021. callback,
  11022. /**
  11023. * Defines the mask of the observer (used to filter notifications)
  11024. */
  11025. mask,
  11026. /**
  11027. * Defines the current scope used to restore the JS context
  11028. */
  11029. scope) {
  11030. if (scope === void 0) { scope = null; }
  11031. this.callback = callback;
  11032. this.mask = mask;
  11033. this.scope = scope;
  11034. /** @hidden */
  11035. this._willBeUnregistered = false;
  11036. /**
  11037. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  11038. */
  11039. this.unregisterOnNextCall = false;
  11040. }
  11041. return Observer;
  11042. }());
  11043. BABYLON.Observer = Observer;
  11044. /**
  11045. * Represent a list of observers registered to multiple Observables object.
  11046. */
  11047. var MultiObserver = /** @class */ (function () {
  11048. function MultiObserver() {
  11049. }
  11050. /**
  11051. * Release associated resources
  11052. */
  11053. MultiObserver.prototype.dispose = function () {
  11054. if (this._observers && this._observables) {
  11055. for (var index = 0; index < this._observers.length; index++) {
  11056. this._observables[index].remove(this._observers[index]);
  11057. }
  11058. }
  11059. this._observers = null;
  11060. this._observables = null;
  11061. };
  11062. /**
  11063. * Raise a callback when one of the observable will notify
  11064. * @param observables defines a list of observables to watch
  11065. * @param callback defines the callback to call on notification
  11066. * @param mask defines the mask used to filter notifications
  11067. * @param scope defines the current scope used to restore the JS context
  11068. * @returns the new MultiObserver
  11069. */
  11070. MultiObserver.Watch = function (observables, callback, mask, scope) {
  11071. if (mask === void 0) { mask = -1; }
  11072. if (scope === void 0) { scope = null; }
  11073. var result = new MultiObserver();
  11074. result._observers = new Array();
  11075. result._observables = observables;
  11076. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  11077. var observable = observables_1[_i];
  11078. var observer = observable.add(callback, mask, false, scope);
  11079. if (observer) {
  11080. result._observers.push(observer);
  11081. }
  11082. }
  11083. return result;
  11084. };
  11085. return MultiObserver;
  11086. }());
  11087. BABYLON.MultiObserver = MultiObserver;
  11088. /**
  11089. * The Observable class is a simple implementation of the Observable pattern.
  11090. *
  11091. * 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.
  11092. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  11093. * 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).
  11094. * 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.
  11095. */
  11096. var Observable = /** @class */ (function () {
  11097. /**
  11098. * Creates a new observable
  11099. * @param onObserverAdded defines a callback to call when a new observer is added
  11100. */
  11101. function Observable(onObserverAdded) {
  11102. this._observers = new Array();
  11103. this._eventState = new EventState(0);
  11104. if (onObserverAdded) {
  11105. this._onObserverAdded = onObserverAdded;
  11106. }
  11107. }
  11108. /**
  11109. * Create a new Observer with the specified callback
  11110. * @param callback the callback that will be executed for that Observer
  11111. * @param mask the mask used to filter observers
  11112. * @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.
  11113. * @param scope optional scope for the callback to be called from
  11114. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  11115. * @returns the new observer created for the callback
  11116. */
  11117. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  11118. if (mask === void 0) { mask = -1; }
  11119. if (insertFirst === void 0) { insertFirst = false; }
  11120. if (scope === void 0) { scope = null; }
  11121. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  11122. if (!callback) {
  11123. return null;
  11124. }
  11125. var observer = new Observer(callback, mask, scope);
  11126. observer.unregisterOnNextCall = unregisterOnFirstCall;
  11127. if (insertFirst) {
  11128. this._observers.unshift(observer);
  11129. }
  11130. else {
  11131. this._observers.push(observer);
  11132. }
  11133. if (this._onObserverAdded) {
  11134. this._onObserverAdded(observer);
  11135. }
  11136. return observer;
  11137. };
  11138. /**
  11139. * Create a new Observer with the specified callback and unregisters after the next notification
  11140. * @param callback the callback that will be executed for that Observer
  11141. * @returns the new observer created for the callback
  11142. */
  11143. Observable.prototype.addOnce = function (callback) {
  11144. return this.add(callback, undefined, undefined, undefined, true);
  11145. };
  11146. /**
  11147. * Remove an Observer from the Observable object
  11148. * @param observer the instance of the Observer to remove
  11149. * @returns false if it doesn't belong to this Observable
  11150. */
  11151. Observable.prototype.remove = function (observer) {
  11152. if (!observer) {
  11153. return false;
  11154. }
  11155. var index = this._observers.indexOf(observer);
  11156. if (index !== -1) {
  11157. this._deferUnregister(observer);
  11158. return true;
  11159. }
  11160. return false;
  11161. };
  11162. /**
  11163. * Remove a callback from the Observable object
  11164. * @param callback the callback to remove
  11165. * @param scope optional scope. If used only the callbacks with this scope will be removed
  11166. * @returns false if it doesn't belong to this Observable
  11167. */
  11168. Observable.prototype.removeCallback = function (callback, scope) {
  11169. for (var index = 0; index < this._observers.length; index++) {
  11170. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  11171. this._deferUnregister(this._observers[index]);
  11172. return true;
  11173. }
  11174. }
  11175. return false;
  11176. };
  11177. Observable.prototype._deferUnregister = function (observer) {
  11178. var _this = this;
  11179. observer.unregisterOnNextCall = false;
  11180. observer._willBeUnregistered = true;
  11181. BABYLON.Tools.SetImmediate(function () {
  11182. _this._remove(observer);
  11183. });
  11184. };
  11185. // This should only be called when not iterating over _observers to avoid callback skipping.
  11186. // Removes an observer from the _observer Array.
  11187. Observable.prototype._remove = function (observer) {
  11188. if (!observer) {
  11189. return false;
  11190. }
  11191. var index = this._observers.indexOf(observer);
  11192. if (index !== -1) {
  11193. this._observers.splice(index, 1);
  11194. return true;
  11195. }
  11196. return false;
  11197. };
  11198. /**
  11199. * Notify all Observers by calling their respective callback with the given data
  11200. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  11201. * @param eventData defines the data to send to all observers
  11202. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  11203. * @param target defines the original target of the state
  11204. * @param currentTarget defines the current target of the state
  11205. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  11206. */
  11207. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  11208. if (mask === void 0) { mask = -1; }
  11209. if (!this._observers.length) {
  11210. return true;
  11211. }
  11212. var state = this._eventState;
  11213. state.mask = mask;
  11214. state.target = target;
  11215. state.currentTarget = currentTarget;
  11216. state.skipNextObservers = false;
  11217. state.lastReturnValue = eventData;
  11218. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  11219. var obs = _a[_i];
  11220. if (obs._willBeUnregistered) {
  11221. continue;
  11222. }
  11223. if (obs.mask & mask) {
  11224. if (obs.scope) {
  11225. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  11226. }
  11227. else {
  11228. state.lastReturnValue = obs.callback(eventData, state);
  11229. }
  11230. if (obs.unregisterOnNextCall) {
  11231. this._deferUnregister(obs);
  11232. }
  11233. }
  11234. if (state.skipNextObservers) {
  11235. return false;
  11236. }
  11237. }
  11238. return true;
  11239. };
  11240. /**
  11241. * Calling this will execute each callback, expecting it to be a promise or return a value.
  11242. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  11243. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  11244. * and it is crucial that all callbacks will be executed.
  11245. * The order of the callbacks is kept, callbacks are not executed parallel.
  11246. *
  11247. * @param eventData The data to be sent to each callback
  11248. * @param mask is used to filter observers defaults to -1
  11249. * @param target defines the callback target (see EventState)
  11250. * @param currentTarget defines he current object in the bubbling phase
  11251. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  11252. */
  11253. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  11254. var _this = this;
  11255. if (mask === void 0) { mask = -1; }
  11256. // create an empty promise
  11257. var p = Promise.resolve(eventData);
  11258. // no observers? return this promise.
  11259. if (!this._observers.length) {
  11260. return p;
  11261. }
  11262. var state = this._eventState;
  11263. state.mask = mask;
  11264. state.target = target;
  11265. state.currentTarget = currentTarget;
  11266. state.skipNextObservers = false;
  11267. // execute one callback after another (not using Promise.all, the order is important)
  11268. this._observers.forEach(function (obs) {
  11269. if (state.skipNextObservers) {
  11270. return;
  11271. }
  11272. if (obs._willBeUnregistered) {
  11273. return;
  11274. }
  11275. if (obs.mask & mask) {
  11276. if (obs.scope) {
  11277. p = p.then(function (lastReturnedValue) {
  11278. state.lastReturnValue = lastReturnedValue;
  11279. return obs.callback.apply(obs.scope, [eventData, state]);
  11280. });
  11281. }
  11282. else {
  11283. p = p.then(function (lastReturnedValue) {
  11284. state.lastReturnValue = lastReturnedValue;
  11285. return obs.callback(eventData, state);
  11286. });
  11287. }
  11288. if (obs.unregisterOnNextCall) {
  11289. _this._deferUnregister(obs);
  11290. }
  11291. }
  11292. });
  11293. // return the eventData
  11294. return p.then(function () { return eventData; });
  11295. };
  11296. /**
  11297. * Notify a specific observer
  11298. * @param observer defines the observer to notify
  11299. * @param eventData defines the data to be sent to each callback
  11300. * @param mask is used to filter observers defaults to -1
  11301. */
  11302. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  11303. if (mask === void 0) { mask = -1; }
  11304. var state = this._eventState;
  11305. state.mask = mask;
  11306. state.skipNextObservers = false;
  11307. observer.callback(eventData, state);
  11308. };
  11309. /**
  11310. * Gets a boolean indicating if the observable has at least one observer
  11311. * @returns true is the Observable has at least one Observer registered
  11312. */
  11313. Observable.prototype.hasObservers = function () {
  11314. return this._observers.length > 0;
  11315. };
  11316. /**
  11317. * Clear the list of observers
  11318. */
  11319. Observable.prototype.clear = function () {
  11320. this._observers = new Array();
  11321. this._onObserverAdded = null;
  11322. };
  11323. /**
  11324. * Clone the current observable
  11325. * @returns a new observable
  11326. */
  11327. Observable.prototype.clone = function () {
  11328. var result = new Observable();
  11329. result._observers = this._observers.slice(0);
  11330. return result;
  11331. };
  11332. /**
  11333. * Does this observable handles observer registered with a given mask
  11334. * @param mask defines the mask to be tested
  11335. * @return whether or not one observer registered with the given mask is handeled
  11336. **/
  11337. Observable.prototype.hasSpecificMask = function (mask) {
  11338. if (mask === void 0) { mask = -1; }
  11339. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  11340. var obs = _a[_i];
  11341. if (obs.mask & mask || obs.mask === mask) {
  11342. return true;
  11343. }
  11344. }
  11345. return false;
  11346. };
  11347. return Observable;
  11348. }());
  11349. BABYLON.Observable = Observable;
  11350. })(BABYLON || (BABYLON = {}));
  11351. //# sourceMappingURL=babylon.observable.js.map
  11352. var BABYLON;
  11353. (function (BABYLON) {
  11354. /**
  11355. * Defines an GC Friendly array where the backfield array do not shrink to prevent over allocations.
  11356. */
  11357. var SmartArray = /** @class */ (function () {
  11358. /**
  11359. * Instantiates a Smart Array.
  11360. * @param capacity defines the default capacity of the array.
  11361. */
  11362. function SmartArray(capacity) {
  11363. /**
  11364. * The active length of the array.
  11365. */
  11366. this.length = 0;
  11367. this.data = new Array(capacity);
  11368. this._id = SmartArray._GlobalId++;
  11369. }
  11370. /**
  11371. * Pushes a value at the end of the active data.
  11372. * @param value defines the object to push in the array.
  11373. */
  11374. SmartArray.prototype.push = function (value) {
  11375. this.data[this.length++] = value;
  11376. if (this.length > this.data.length) {
  11377. this.data.length *= 2;
  11378. }
  11379. };
  11380. /**
  11381. * Iterates over the active data and apply the lambda to them.
  11382. * @param func defines the action to apply on each value.
  11383. */
  11384. SmartArray.prototype.forEach = function (func) {
  11385. for (var index = 0; index < this.length; index++) {
  11386. func(this.data[index]);
  11387. }
  11388. };
  11389. /**
  11390. * Sorts the full sets of data.
  11391. * @param compareFn defines the comparison function to apply.
  11392. */
  11393. SmartArray.prototype.sort = function (compareFn) {
  11394. this.data.sort(compareFn);
  11395. };
  11396. /**
  11397. * Resets the active data to an empty array.
  11398. */
  11399. SmartArray.prototype.reset = function () {
  11400. this.length = 0;
  11401. };
  11402. /**
  11403. * Releases all the data from the array as well as the array.
  11404. */
  11405. SmartArray.prototype.dispose = function () {
  11406. this.reset();
  11407. if (this.data) {
  11408. this.data.length = 0;
  11409. this.data = [];
  11410. }
  11411. };
  11412. /**
  11413. * Concats the active data with a given array.
  11414. * @param array defines the data to concatenate with.
  11415. */
  11416. SmartArray.prototype.concat = function (array) {
  11417. if (array.length === 0) {
  11418. return;
  11419. }
  11420. if (this.length + array.length > this.data.length) {
  11421. this.data.length = (this.length + array.length) * 2;
  11422. }
  11423. for (var index = 0; index < array.length; index++) {
  11424. this.data[this.length++] = (array.data || array)[index];
  11425. }
  11426. };
  11427. /**
  11428. * Returns the position of a value in the active data.
  11429. * @param value defines the value to find the index for
  11430. * @returns the index if found in the active data otherwise -1
  11431. */
  11432. SmartArray.prototype.indexOf = function (value) {
  11433. var position = this.data.indexOf(value);
  11434. if (position >= this.length) {
  11435. return -1;
  11436. }
  11437. return position;
  11438. };
  11439. /**
  11440. * Returns whether an element is part of the active data.
  11441. * @param value defines the value to look for
  11442. * @returns true if found in the active data otherwise false
  11443. */
  11444. SmartArray.prototype.contains = function (value) {
  11445. return this.indexOf(value) !== -1;
  11446. };
  11447. // Statics
  11448. SmartArray._GlobalId = 0;
  11449. return SmartArray;
  11450. }());
  11451. BABYLON.SmartArray = SmartArray;
  11452. /**
  11453. * Defines an GC Friendly array where the backfield array do not shrink to prevent over allocations.
  11454. * The data in this array can only be present once
  11455. */
  11456. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  11457. __extends(SmartArrayNoDuplicate, _super);
  11458. function SmartArrayNoDuplicate() {
  11459. var _this = _super !== null && _super.apply(this, arguments) || this;
  11460. _this._duplicateId = 0;
  11461. return _this;
  11462. }
  11463. /**
  11464. * Pushes a value at the end of the active data.
  11465. * THIS DOES NOT PREVENT DUPPLICATE DATA
  11466. * @param value defines the object to push in the array.
  11467. */
  11468. SmartArrayNoDuplicate.prototype.push = function (value) {
  11469. _super.prototype.push.call(this, value);
  11470. if (!value.__smartArrayFlags) {
  11471. value.__smartArrayFlags = {};
  11472. }
  11473. value.__smartArrayFlags[this._id] = this._duplicateId;
  11474. };
  11475. /**
  11476. * Pushes a value at the end of the active data.
  11477. * If the data is already present, it won t be added again
  11478. * @param value defines the object to push in the array.
  11479. * @returns true if added false if it was already present
  11480. */
  11481. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  11482. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  11483. return false;
  11484. }
  11485. this.push(value);
  11486. return true;
  11487. };
  11488. /**
  11489. * Resets the active data to an empty array.
  11490. */
  11491. SmartArrayNoDuplicate.prototype.reset = function () {
  11492. _super.prototype.reset.call(this);
  11493. this._duplicateId++;
  11494. };
  11495. /**
  11496. * Concats the active data with a given array.
  11497. * This ensures no dupplicate will be present in the result.
  11498. * @param array defines the data to concatenate with.
  11499. */
  11500. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  11501. if (array.length === 0) {
  11502. return;
  11503. }
  11504. if (this.length + array.length > this.data.length) {
  11505. this.data.length = (this.length + array.length) * 2;
  11506. }
  11507. for (var index = 0; index < array.length; index++) {
  11508. var item = (array.data || array)[index];
  11509. this.pushNoDuplicate(item);
  11510. }
  11511. };
  11512. return SmartArrayNoDuplicate;
  11513. }(SmartArray));
  11514. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  11515. })(BABYLON || (BABYLON = {}));
  11516. //# sourceMappingURL=babylon.smartArray.js.map
  11517. var BABYLON;
  11518. (function (BABYLON) {
  11519. var PromiseStates;
  11520. (function (PromiseStates) {
  11521. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  11522. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  11523. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  11524. })(PromiseStates || (PromiseStates = {}));
  11525. var FulFillmentAgregator = /** @class */ (function () {
  11526. function FulFillmentAgregator() {
  11527. this.count = 0;
  11528. this.target = 0;
  11529. this.results = [];
  11530. }
  11531. return FulFillmentAgregator;
  11532. }());
  11533. var InternalPromise = /** @class */ (function () {
  11534. function InternalPromise(resolver) {
  11535. var _this = this;
  11536. this._state = PromiseStates.Pending;
  11537. this._children = new Array();
  11538. this._rejectWasConsumed = false;
  11539. if (!resolver) {
  11540. return;
  11541. }
  11542. try {
  11543. resolver(function (value) {
  11544. _this._resolve(value);
  11545. }, function (reason) {
  11546. _this._reject(reason);
  11547. });
  11548. }
  11549. catch (e) {
  11550. this._reject(e);
  11551. }
  11552. }
  11553. Object.defineProperty(InternalPromise.prototype, "_result", {
  11554. get: function () {
  11555. return this._resultValue;
  11556. },
  11557. set: function (value) {
  11558. this._resultValue = value;
  11559. if (this._parent && this._parent._result === undefined) {
  11560. this._parent._result = value;
  11561. }
  11562. },
  11563. enumerable: true,
  11564. configurable: true
  11565. });
  11566. InternalPromise.prototype.catch = function (onRejected) {
  11567. return this.then(undefined, onRejected);
  11568. };
  11569. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  11570. var _this = this;
  11571. var newPromise = new InternalPromise();
  11572. newPromise._onFulfilled = onFulfilled;
  11573. newPromise._onRejected = onRejected;
  11574. // Composition
  11575. this._children.push(newPromise);
  11576. newPromise._parent = this;
  11577. if (this._state !== PromiseStates.Pending) {
  11578. BABYLON.Tools.SetImmediate(function () {
  11579. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  11580. var returnedValue = newPromise._resolve(_this._result);
  11581. if (returnedValue !== undefined && returnedValue !== null) {
  11582. if (returnedValue._state !== undefined) {
  11583. var returnedPromise = returnedValue;
  11584. newPromise._children.push(returnedPromise);
  11585. returnedPromise._parent = newPromise;
  11586. newPromise = returnedPromise;
  11587. }
  11588. else {
  11589. newPromise._result = returnedValue;
  11590. }
  11591. }
  11592. }
  11593. else {
  11594. newPromise._reject(_this._reason);
  11595. }
  11596. });
  11597. }
  11598. return newPromise;
  11599. };
  11600. InternalPromise.prototype._moveChildren = function (children) {
  11601. var _this = this;
  11602. var _a;
  11603. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  11604. this._children.forEach(function (child) {
  11605. child._parent = _this;
  11606. });
  11607. if (this._state === PromiseStates.Fulfilled) {
  11608. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  11609. var child = _b[_i];
  11610. child._resolve(this._result);
  11611. }
  11612. }
  11613. else if (this._state === PromiseStates.Rejected) {
  11614. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  11615. var child = _d[_c];
  11616. child._reject(this._reason);
  11617. }
  11618. }
  11619. };
  11620. InternalPromise.prototype._resolve = function (value) {
  11621. try {
  11622. this._state = PromiseStates.Fulfilled;
  11623. var returnedValue = null;
  11624. if (this._onFulfilled) {
  11625. returnedValue = this._onFulfilled(value);
  11626. }
  11627. if (returnedValue !== undefined && returnedValue !== null) {
  11628. if (returnedValue._state !== undefined) {
  11629. // Transmit children
  11630. var returnedPromise = returnedValue;
  11631. returnedPromise._parent = this;
  11632. returnedPromise._moveChildren(this._children);
  11633. value = returnedPromise._result;
  11634. }
  11635. else {
  11636. value = returnedValue;
  11637. }
  11638. }
  11639. this._result = value;
  11640. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  11641. var child = _a[_i];
  11642. child._resolve(value);
  11643. }
  11644. this._children.length = 0;
  11645. delete this._onFulfilled;
  11646. delete this._onRejected;
  11647. }
  11648. catch (e) {
  11649. this._reject(e, true);
  11650. }
  11651. };
  11652. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  11653. if (onLocalThrow === void 0) { onLocalThrow = false; }
  11654. this._state = PromiseStates.Rejected;
  11655. this._reason = reason;
  11656. if (this._onRejected && !onLocalThrow) {
  11657. try {
  11658. this._onRejected(reason);
  11659. this._rejectWasConsumed = true;
  11660. }
  11661. catch (e) {
  11662. reason = e;
  11663. }
  11664. }
  11665. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  11666. var child = _a[_i];
  11667. if (this._rejectWasConsumed) {
  11668. child._resolve(null);
  11669. }
  11670. else {
  11671. child._reject(reason);
  11672. }
  11673. }
  11674. this._children.length = 0;
  11675. delete this._onFulfilled;
  11676. delete this._onRejected;
  11677. };
  11678. InternalPromise.resolve = function (value) {
  11679. var newPromise = new InternalPromise();
  11680. newPromise._resolve(value);
  11681. return newPromise;
  11682. };
  11683. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  11684. promise.then(function (value) {
  11685. agregator.results[index] = value;
  11686. agregator.count++;
  11687. if (agregator.count === agregator.target) {
  11688. agregator.rootPromise._resolve(agregator.results);
  11689. }
  11690. return null;
  11691. }, function (reason) {
  11692. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  11693. agregator.rootPromise._reject(reason);
  11694. }
  11695. });
  11696. };
  11697. InternalPromise.all = function (promises) {
  11698. var newPromise = new InternalPromise();
  11699. var agregator = new FulFillmentAgregator();
  11700. agregator.target = promises.length;
  11701. agregator.rootPromise = newPromise;
  11702. if (promises.length) {
  11703. for (var index = 0; index < promises.length; index++) {
  11704. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  11705. }
  11706. }
  11707. else {
  11708. newPromise._resolve([]);
  11709. }
  11710. return newPromise;
  11711. };
  11712. InternalPromise.race = function (promises) {
  11713. var newPromise = new InternalPromise();
  11714. if (promises.length) {
  11715. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  11716. var promise = promises_1[_i];
  11717. promise.then(function (value) {
  11718. if (newPromise) {
  11719. newPromise._resolve(value);
  11720. newPromise = null;
  11721. }
  11722. return null;
  11723. }, function (reason) {
  11724. if (newPromise) {
  11725. newPromise._reject(reason);
  11726. newPromise = null;
  11727. }
  11728. });
  11729. }
  11730. }
  11731. return newPromise;
  11732. };
  11733. return InternalPromise;
  11734. }());
  11735. /**
  11736. * Helper class that provides a small promise polyfill
  11737. */
  11738. var PromisePolyfill = /** @class */ (function () {
  11739. function PromisePolyfill() {
  11740. }
  11741. /**
  11742. * Static function used to check if the polyfill is required
  11743. * If this is the case then the function will inject the polyfill to window.Promise
  11744. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  11745. */
  11746. PromisePolyfill.Apply = function (force) {
  11747. if (force === void 0) { force = false; }
  11748. if (force || typeof Promise === 'undefined') {
  11749. var root = window;
  11750. root.Promise = InternalPromise;
  11751. }
  11752. };
  11753. return PromisePolyfill;
  11754. }());
  11755. BABYLON.PromisePolyfill = PromisePolyfill;
  11756. })(BABYLON || (BABYLON = {}));
  11757. //# sourceMappingURL=babylon.promise.js.map
  11758. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  11759. var BABYLON;
  11760. (function (BABYLON) {
  11761. /**
  11762. * Helper class to push actions to a pool of workers.
  11763. */
  11764. var WorkerPool = /** @class */ (function () {
  11765. /**
  11766. * Constructor
  11767. * @param workers Array of workers to use for actions
  11768. */
  11769. function WorkerPool(workers) {
  11770. this._pendingActions = new Array();
  11771. this._workerInfos = workers.map(function (worker) { return ({
  11772. worker: worker,
  11773. active: false
  11774. }); });
  11775. }
  11776. /**
  11777. * Terminates all workers and clears any pending actions.
  11778. */
  11779. WorkerPool.prototype.dispose = function () {
  11780. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  11781. var workerInfo = _a[_i];
  11782. workerInfo.worker.terminate();
  11783. }
  11784. delete this._workerInfos;
  11785. delete this._pendingActions;
  11786. };
  11787. /**
  11788. * Pushes an action to the worker pool. If all the workers are active, the action will be
  11789. * pended until a worker has completed its action.
  11790. * @param action The action to perform. Call onComplete when the action is complete.
  11791. */
  11792. WorkerPool.prototype.push = function (action) {
  11793. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  11794. var workerInfo = _a[_i];
  11795. if (!workerInfo.active) {
  11796. this._execute(workerInfo, action);
  11797. return;
  11798. }
  11799. }
  11800. this._pendingActions.push(action);
  11801. };
  11802. WorkerPool.prototype._execute = function (workerInfo, action) {
  11803. var _this = this;
  11804. workerInfo.active = true;
  11805. action(workerInfo.worker, function () {
  11806. workerInfo.active = false;
  11807. var nextAction = _this._pendingActions.shift();
  11808. if (nextAction) {
  11809. _this._execute(workerInfo, nextAction);
  11810. }
  11811. });
  11812. };
  11813. return WorkerPool;
  11814. }());
  11815. BABYLON.WorkerPool = WorkerPool;
  11816. })(BABYLON || (BABYLON = {}));
  11817. //# sourceMappingURL=babylon.workerPool.js.map
  11818. var BABYLON;
  11819. (function (BABYLON) {
  11820. /**
  11821. * @hidden
  11822. **/
  11823. var _AlphaState = /** @class */ (function () {
  11824. /**
  11825. * Initializes the state.
  11826. */
  11827. function _AlphaState() {
  11828. this._isAlphaBlendDirty = false;
  11829. this._isBlendFunctionParametersDirty = false;
  11830. this._isBlendEquationParametersDirty = false;
  11831. this._isBlendConstantsDirty = false;
  11832. this._alphaBlend = false;
  11833. this._blendFunctionParameters = new Array(4);
  11834. this._blendEquationParameters = new Array(2);
  11835. this._blendConstants = new Array(4);
  11836. this.reset();
  11837. }
  11838. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  11839. get: function () {
  11840. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  11841. },
  11842. enumerable: true,
  11843. configurable: true
  11844. });
  11845. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  11846. get: function () {
  11847. return this._alphaBlend;
  11848. },
  11849. set: function (value) {
  11850. if (this._alphaBlend === value) {
  11851. return;
  11852. }
  11853. this._alphaBlend = value;
  11854. this._isAlphaBlendDirty = true;
  11855. },
  11856. enumerable: true,
  11857. configurable: true
  11858. });
  11859. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  11860. if (this._blendConstants[0] === r &&
  11861. this._blendConstants[1] === g &&
  11862. this._blendConstants[2] === b &&
  11863. this._blendConstants[3] === a) {
  11864. return;
  11865. }
  11866. this._blendConstants[0] = r;
  11867. this._blendConstants[1] = g;
  11868. this._blendConstants[2] = b;
  11869. this._blendConstants[3] = a;
  11870. this._isBlendConstantsDirty = true;
  11871. };
  11872. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  11873. if (this._blendFunctionParameters[0] === value0 &&
  11874. this._blendFunctionParameters[1] === value1 &&
  11875. this._blendFunctionParameters[2] === value2 &&
  11876. this._blendFunctionParameters[3] === value3) {
  11877. return;
  11878. }
  11879. this._blendFunctionParameters[0] = value0;
  11880. this._blendFunctionParameters[1] = value1;
  11881. this._blendFunctionParameters[2] = value2;
  11882. this._blendFunctionParameters[3] = value3;
  11883. this._isBlendFunctionParametersDirty = true;
  11884. };
  11885. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  11886. if (this._blendEquationParameters[0] === rgb &&
  11887. this._blendEquationParameters[1] === alpha) {
  11888. return;
  11889. }
  11890. this._blendEquationParameters[0] = rgb;
  11891. this._blendEquationParameters[1] = alpha;
  11892. this._isBlendEquationParametersDirty = true;
  11893. };
  11894. _AlphaState.prototype.reset = function () {
  11895. this._alphaBlend = false;
  11896. this._blendFunctionParameters[0] = null;
  11897. this._blendFunctionParameters[1] = null;
  11898. this._blendFunctionParameters[2] = null;
  11899. this._blendFunctionParameters[3] = null;
  11900. this._blendEquationParameters[0] = null;
  11901. this._blendEquationParameters[1] = null;
  11902. this._blendConstants[0] = null;
  11903. this._blendConstants[1] = null;
  11904. this._blendConstants[2] = null;
  11905. this._blendConstants[3] = null;
  11906. this._isAlphaBlendDirty = true;
  11907. this._isBlendFunctionParametersDirty = false;
  11908. this._isBlendEquationParametersDirty = false;
  11909. this._isBlendConstantsDirty = false;
  11910. };
  11911. _AlphaState.prototype.apply = function (gl) {
  11912. if (!this.isDirty) {
  11913. return;
  11914. }
  11915. // Alpha blend
  11916. if (this._isAlphaBlendDirty) {
  11917. if (this._alphaBlend) {
  11918. gl.enable(gl.BLEND);
  11919. }
  11920. else {
  11921. gl.disable(gl.BLEND);
  11922. }
  11923. this._isAlphaBlendDirty = false;
  11924. }
  11925. // Alpha function
  11926. if (this._isBlendFunctionParametersDirty) {
  11927. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  11928. this._isBlendFunctionParametersDirty = false;
  11929. }
  11930. // Alpha equation
  11931. if (this._isBlendEquationParametersDirty) {
  11932. gl.blendEquationSeparate(this._blendEquationParameters[0], this._blendEquationParameters[1]);
  11933. this._isBlendEquationParametersDirty = false;
  11934. }
  11935. // Constants
  11936. if (this._isBlendConstantsDirty) {
  11937. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  11938. this._isBlendConstantsDirty = false;
  11939. }
  11940. };
  11941. return _AlphaState;
  11942. }());
  11943. BABYLON._AlphaState = _AlphaState;
  11944. })(BABYLON || (BABYLON = {}));
  11945. //# sourceMappingURL=babylon.alphaCullingState.js.map
  11946. var BABYLON;
  11947. (function (BABYLON) {
  11948. /**
  11949. * @hidden
  11950. **/
  11951. var _DepthCullingState = /** @class */ (function () {
  11952. /**
  11953. * Initializes the state.
  11954. */
  11955. function _DepthCullingState() {
  11956. this._isDepthTestDirty = false;
  11957. this._isDepthMaskDirty = false;
  11958. this._isDepthFuncDirty = false;
  11959. this._isCullFaceDirty = false;
  11960. this._isCullDirty = false;
  11961. this._isZOffsetDirty = false;
  11962. this._isFrontFaceDirty = false;
  11963. this.reset();
  11964. }
  11965. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  11966. get: function () {
  11967. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  11968. },
  11969. enumerable: true,
  11970. configurable: true
  11971. });
  11972. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  11973. get: function () {
  11974. return this._zOffset;
  11975. },
  11976. set: function (value) {
  11977. if (this._zOffset === value) {
  11978. return;
  11979. }
  11980. this._zOffset = value;
  11981. this._isZOffsetDirty = true;
  11982. },
  11983. enumerable: true,
  11984. configurable: true
  11985. });
  11986. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  11987. get: function () {
  11988. return this._cullFace;
  11989. },
  11990. set: function (value) {
  11991. if (this._cullFace === value) {
  11992. return;
  11993. }
  11994. this._cullFace = value;
  11995. this._isCullFaceDirty = true;
  11996. },
  11997. enumerable: true,
  11998. configurable: true
  11999. });
  12000. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  12001. get: function () {
  12002. return this._cull;
  12003. },
  12004. set: function (value) {
  12005. if (this._cull === value) {
  12006. return;
  12007. }
  12008. this._cull = value;
  12009. this._isCullDirty = true;
  12010. },
  12011. enumerable: true,
  12012. configurable: true
  12013. });
  12014. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  12015. get: function () {
  12016. return this._depthFunc;
  12017. },
  12018. set: function (value) {
  12019. if (this._depthFunc === value) {
  12020. return;
  12021. }
  12022. this._depthFunc = value;
  12023. this._isDepthFuncDirty = true;
  12024. },
  12025. enumerable: true,
  12026. configurable: true
  12027. });
  12028. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  12029. get: function () {
  12030. return this._depthMask;
  12031. },
  12032. set: function (value) {
  12033. if (this._depthMask === value) {
  12034. return;
  12035. }
  12036. this._depthMask = value;
  12037. this._isDepthMaskDirty = true;
  12038. },
  12039. enumerable: true,
  12040. configurable: true
  12041. });
  12042. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  12043. get: function () {
  12044. return this._depthTest;
  12045. },
  12046. set: function (value) {
  12047. if (this._depthTest === value) {
  12048. return;
  12049. }
  12050. this._depthTest = value;
  12051. this._isDepthTestDirty = true;
  12052. },
  12053. enumerable: true,
  12054. configurable: true
  12055. });
  12056. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  12057. get: function () {
  12058. return this._frontFace;
  12059. },
  12060. set: function (value) {
  12061. if (this._frontFace === value) {
  12062. return;
  12063. }
  12064. this._frontFace = value;
  12065. this._isFrontFaceDirty = true;
  12066. },
  12067. enumerable: true,
  12068. configurable: true
  12069. });
  12070. _DepthCullingState.prototype.reset = function () {
  12071. this._depthMask = true;
  12072. this._depthTest = true;
  12073. this._depthFunc = null;
  12074. this._cullFace = null;
  12075. this._cull = null;
  12076. this._zOffset = 0;
  12077. this._frontFace = null;
  12078. this._isDepthTestDirty = true;
  12079. this._isDepthMaskDirty = true;
  12080. this._isDepthFuncDirty = false;
  12081. this._isCullFaceDirty = false;
  12082. this._isCullDirty = false;
  12083. this._isZOffsetDirty = false;
  12084. this._isFrontFaceDirty = false;
  12085. };
  12086. _DepthCullingState.prototype.apply = function (gl) {
  12087. if (!this.isDirty) {
  12088. return;
  12089. }
  12090. // Cull
  12091. if (this._isCullDirty) {
  12092. if (this.cull) {
  12093. gl.enable(gl.CULL_FACE);
  12094. }
  12095. else {
  12096. gl.disable(gl.CULL_FACE);
  12097. }
  12098. this._isCullDirty = false;
  12099. }
  12100. // Cull face
  12101. if (this._isCullFaceDirty) {
  12102. gl.cullFace(this.cullFace);
  12103. this._isCullFaceDirty = false;
  12104. }
  12105. // Depth mask
  12106. if (this._isDepthMaskDirty) {
  12107. gl.depthMask(this.depthMask);
  12108. this._isDepthMaskDirty = false;
  12109. }
  12110. // Depth test
  12111. if (this._isDepthTestDirty) {
  12112. if (this.depthTest) {
  12113. gl.enable(gl.DEPTH_TEST);
  12114. }
  12115. else {
  12116. gl.disable(gl.DEPTH_TEST);
  12117. }
  12118. this._isDepthTestDirty = false;
  12119. }
  12120. // Depth func
  12121. if (this._isDepthFuncDirty) {
  12122. gl.depthFunc(this.depthFunc);
  12123. this._isDepthFuncDirty = false;
  12124. }
  12125. // zOffset
  12126. if (this._isZOffsetDirty) {
  12127. if (this.zOffset) {
  12128. gl.enable(gl.POLYGON_OFFSET_FILL);
  12129. gl.polygonOffset(this.zOffset, 0);
  12130. }
  12131. else {
  12132. gl.disable(gl.POLYGON_OFFSET_FILL);
  12133. }
  12134. this._isZOffsetDirty = false;
  12135. }
  12136. // Front face
  12137. if (this._isFrontFaceDirty) {
  12138. gl.frontFace(this.frontFace);
  12139. this._isFrontFaceDirty = false;
  12140. }
  12141. };
  12142. return _DepthCullingState;
  12143. }());
  12144. BABYLON._DepthCullingState = _DepthCullingState;
  12145. })(BABYLON || (BABYLON = {}));
  12146. //# sourceMappingURL=babylon.depthCullingState.js.map
  12147. var BABYLON;
  12148. (function (BABYLON) {
  12149. /**
  12150. * @hidden
  12151. **/
  12152. var _StencilState = /** @class */ (function () {
  12153. function _StencilState() {
  12154. this._isStencilTestDirty = false;
  12155. this._isStencilMaskDirty = false;
  12156. this._isStencilFuncDirty = false;
  12157. this._isStencilOpDirty = false;
  12158. this.reset();
  12159. }
  12160. Object.defineProperty(_StencilState.prototype, "isDirty", {
  12161. get: function () {
  12162. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  12163. },
  12164. enumerable: true,
  12165. configurable: true
  12166. });
  12167. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  12168. get: function () {
  12169. return this._stencilFunc;
  12170. },
  12171. set: function (value) {
  12172. if (this._stencilFunc === value) {
  12173. return;
  12174. }
  12175. this._stencilFunc = value;
  12176. this._isStencilFuncDirty = true;
  12177. },
  12178. enumerable: true,
  12179. configurable: true
  12180. });
  12181. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  12182. get: function () {
  12183. return this._stencilFuncRef;
  12184. },
  12185. set: function (value) {
  12186. if (this._stencilFuncRef === value) {
  12187. return;
  12188. }
  12189. this._stencilFuncRef = value;
  12190. this._isStencilFuncDirty = true;
  12191. },
  12192. enumerable: true,
  12193. configurable: true
  12194. });
  12195. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  12196. get: function () {
  12197. return this._stencilFuncMask;
  12198. },
  12199. set: function (value) {
  12200. if (this._stencilFuncMask === value) {
  12201. return;
  12202. }
  12203. this._stencilFuncMask = value;
  12204. this._isStencilFuncDirty = true;
  12205. },
  12206. enumerable: true,
  12207. configurable: true
  12208. });
  12209. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  12210. get: function () {
  12211. return this._stencilOpStencilFail;
  12212. },
  12213. set: function (value) {
  12214. if (this._stencilOpStencilFail === value) {
  12215. return;
  12216. }
  12217. this._stencilOpStencilFail = value;
  12218. this._isStencilOpDirty = true;
  12219. },
  12220. enumerable: true,
  12221. configurable: true
  12222. });
  12223. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  12224. get: function () {
  12225. return this._stencilOpDepthFail;
  12226. },
  12227. set: function (value) {
  12228. if (this._stencilOpDepthFail === value) {
  12229. return;
  12230. }
  12231. this._stencilOpDepthFail = value;
  12232. this._isStencilOpDirty = true;
  12233. },
  12234. enumerable: true,
  12235. configurable: true
  12236. });
  12237. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  12238. get: function () {
  12239. return this._stencilOpStencilDepthPass;
  12240. },
  12241. set: function (value) {
  12242. if (this._stencilOpStencilDepthPass === value) {
  12243. return;
  12244. }
  12245. this._stencilOpStencilDepthPass = value;
  12246. this._isStencilOpDirty = true;
  12247. },
  12248. enumerable: true,
  12249. configurable: true
  12250. });
  12251. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  12252. get: function () {
  12253. return this._stencilMask;
  12254. },
  12255. set: function (value) {
  12256. if (this._stencilMask === value) {
  12257. return;
  12258. }
  12259. this._stencilMask = value;
  12260. this._isStencilMaskDirty = true;
  12261. },
  12262. enumerable: true,
  12263. configurable: true
  12264. });
  12265. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  12266. get: function () {
  12267. return this._stencilTest;
  12268. },
  12269. set: function (value) {
  12270. if (this._stencilTest === value) {
  12271. return;
  12272. }
  12273. this._stencilTest = value;
  12274. this._isStencilTestDirty = true;
  12275. },
  12276. enumerable: true,
  12277. configurable: true
  12278. });
  12279. _StencilState.prototype.reset = function () {
  12280. this._stencilTest = false;
  12281. this._stencilMask = 0xFF;
  12282. this._stencilFunc = BABYLON.Engine.ALWAYS;
  12283. this._stencilFuncRef = 1;
  12284. this._stencilFuncMask = 0xFF;
  12285. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  12286. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  12287. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  12288. this._isStencilTestDirty = true;
  12289. this._isStencilMaskDirty = true;
  12290. this._isStencilFuncDirty = true;
  12291. this._isStencilOpDirty = true;
  12292. };
  12293. _StencilState.prototype.apply = function (gl) {
  12294. if (!this.isDirty) {
  12295. return;
  12296. }
  12297. // Stencil test
  12298. if (this._isStencilTestDirty) {
  12299. if (this.stencilTest) {
  12300. gl.enable(gl.STENCIL_TEST);
  12301. }
  12302. else {
  12303. gl.disable(gl.STENCIL_TEST);
  12304. }
  12305. this._isStencilTestDirty = false;
  12306. }
  12307. // Stencil mask
  12308. if (this._isStencilMaskDirty) {
  12309. gl.stencilMask(this.stencilMask);
  12310. this._isStencilMaskDirty = false;
  12311. }
  12312. // Stencil func
  12313. if (this._isStencilFuncDirty) {
  12314. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  12315. this._isStencilFuncDirty = false;
  12316. }
  12317. // Stencil op
  12318. if (this._isStencilOpDirty) {
  12319. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  12320. this._isStencilOpDirty = false;
  12321. }
  12322. };
  12323. return _StencilState;
  12324. }());
  12325. BABYLON._StencilState = _StencilState;
  12326. })(BABYLON || (BABYLON = {}));
  12327. //# sourceMappingURL=babylon.stencilState.js.map
  12328. var __assign = (this && this.__assign) || function () {
  12329. __assign = Object.assign || function(t) {
  12330. for (var s, i = 1, n = arguments.length; i < n; i++) {
  12331. s = arguments[i];
  12332. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  12333. t[p] = s[p];
  12334. }
  12335. return t;
  12336. };
  12337. return __assign.apply(this, arguments);
  12338. };
  12339. var BABYLON;
  12340. (function (BABYLON) {
  12341. /**
  12342. * Keeps track of all the buffer info used in engine.
  12343. */
  12344. var BufferPointer = /** @class */ (function () {
  12345. function BufferPointer() {
  12346. }
  12347. return BufferPointer;
  12348. }());
  12349. /**
  12350. * Interface for attribute information associated with buffer instanciation
  12351. */
  12352. var InstancingAttributeInfo = /** @class */ (function () {
  12353. function InstancingAttributeInfo() {
  12354. }
  12355. return InstancingAttributeInfo;
  12356. }());
  12357. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  12358. /**
  12359. * Define options used to create a render target texture
  12360. */
  12361. var RenderTargetCreationOptions = /** @class */ (function () {
  12362. function RenderTargetCreationOptions() {
  12363. }
  12364. return RenderTargetCreationOptions;
  12365. }());
  12366. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  12367. /**
  12368. * Define options used to create a depth texture
  12369. */
  12370. var DepthTextureCreationOptions = /** @class */ (function () {
  12371. function DepthTextureCreationOptions() {
  12372. }
  12373. return DepthTextureCreationOptions;
  12374. }());
  12375. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  12376. /**
  12377. * Class used to describe the capabilities of the engine relatively to the current browser
  12378. */
  12379. var EngineCapabilities = /** @class */ (function () {
  12380. function EngineCapabilities() {
  12381. }
  12382. return EngineCapabilities;
  12383. }());
  12384. BABYLON.EngineCapabilities = EngineCapabilities;
  12385. /**
  12386. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  12387. */
  12388. var Engine = /** @class */ (function () {
  12389. /**
  12390. * Creates a new engine
  12391. * @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
  12392. * @param antialias defines enable antialiasing (default: false)
  12393. * @param options defines further options to be sent to the getContext() function
  12394. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  12395. */
  12396. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  12397. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  12398. var _this = this;
  12399. // Public members
  12400. /**
  12401. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  12402. */
  12403. this.forcePOTTextures = false;
  12404. /**
  12405. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  12406. */
  12407. this.isFullscreen = false;
  12408. /**
  12409. * Gets a boolean indicating if the pointer is currently locked
  12410. */
  12411. this.isPointerLock = false;
  12412. /**
  12413. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  12414. */
  12415. this.cullBackFaces = true;
  12416. /**
  12417. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  12418. */
  12419. this.renderEvenInBackground = true;
  12420. /**
  12421. * Gets or sets a boolean indicating that cache can be kept between frames
  12422. */
  12423. this.preventCacheWipeBetweenFrames = false;
  12424. /**
  12425. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  12426. **/
  12427. this.enableOfflineSupport = false;
  12428. /**
  12429. * 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)
  12430. **/
  12431. this.disableManifestCheck = false;
  12432. /**
  12433. * Gets the list of created scenes
  12434. */
  12435. this.scenes = new Array();
  12436. /**
  12437. * Event raised when a new scene is created
  12438. */
  12439. this.onNewSceneAddedObservable = new BABYLON.Observable();
  12440. /**
  12441. * Gets the list of created postprocesses
  12442. */
  12443. this.postProcesses = new Array();
  12444. /** Gets or sets a boolean indicating if the engine should validate programs after compilation */
  12445. this.validateShaderPrograms = false;
  12446. // Observables
  12447. /**
  12448. * Observable event triggered each time the rendering canvas is resized
  12449. */
  12450. this.onResizeObservable = new BABYLON.Observable();
  12451. /**
  12452. * Observable event triggered each time the canvas loses focus
  12453. */
  12454. this.onCanvasBlurObservable = new BABYLON.Observable();
  12455. /**
  12456. * Observable event triggered each time the canvas gains focus
  12457. */
  12458. this.onCanvasFocusObservable = new BABYLON.Observable();
  12459. /**
  12460. * Observable event triggered each time the canvas receives pointerout event
  12461. */
  12462. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  12463. /**
  12464. * Observable event triggered before each texture is initialized
  12465. */
  12466. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  12467. //WebVR
  12468. this._vrDisplay = undefined;
  12469. this._vrSupported = false;
  12470. this._vrExclusivePointerMode = false;
  12471. // Uniform buffers list
  12472. /**
  12473. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  12474. */
  12475. this.disableUniformBuffers = false;
  12476. /** @hidden */
  12477. this._uniformBuffers = new Array();
  12478. // Observables
  12479. /**
  12480. * Observable raised when the engine begins a new frame
  12481. */
  12482. this.onBeginFrameObservable = new BABYLON.Observable();
  12483. /**
  12484. * If set, will be used to request the next animation frame for the render loop
  12485. */
  12486. this.customAnimationFrameRequester = null;
  12487. /**
  12488. * Observable raised when the engine ends the current frame
  12489. */
  12490. this.onEndFrameObservable = new BABYLON.Observable();
  12491. /**
  12492. * Observable raised when the engine is about to compile a shader
  12493. */
  12494. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  12495. /**
  12496. * Observable raised when the engine has jsut compiled a shader
  12497. */
  12498. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  12499. this._windowIsBackground = false;
  12500. this._webGLVersion = 1.0;
  12501. /** @hidden */
  12502. this._badOS = false;
  12503. /** @hidden */
  12504. this._badDesktopOS = false;
  12505. /**
  12506. * Gets or sets a value indicating if we want to disable texture binding optimization.
  12507. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  12508. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  12509. */
  12510. this.disableTextureBindingOptimization = false;
  12511. /**
  12512. * Observable signaled when VR display mode changes
  12513. */
  12514. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  12515. /**
  12516. * Observable signaled when VR request present is complete
  12517. */
  12518. this.onVRRequestPresentComplete = new BABYLON.Observable();
  12519. /**
  12520. * Observable signaled when VR request present starts
  12521. */
  12522. this.onVRRequestPresentStart = new BABYLON.Observable();
  12523. this._colorWrite = true;
  12524. /** @hidden */
  12525. this._drawCalls = new BABYLON.PerfCounter();
  12526. /** @hidden */
  12527. this._textureCollisions = new BABYLON.PerfCounter();
  12528. this._renderingQueueLaunched = false;
  12529. this._activeRenderLoops = new Array();
  12530. // Deterministic lockstepMaxSteps
  12531. this._deterministicLockstep = false;
  12532. this._lockstepMaxSteps = 4;
  12533. // Lost context
  12534. /**
  12535. * Observable signaled when a context lost event is raised
  12536. */
  12537. this.onContextLostObservable = new BABYLON.Observable();
  12538. /**
  12539. * Observable signaled when a context restored event is raised
  12540. */
  12541. this.onContextRestoredObservable = new BABYLON.Observable();
  12542. this._contextWasLost = false;
  12543. this._doNotHandleContextLost = false;
  12544. // FPS
  12545. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  12546. this._fps = 60;
  12547. this._deltaTime = 0;
  12548. /**
  12549. * Turn this value on if you want to pause FPS computation when in background
  12550. */
  12551. this.disablePerformanceMonitorInBackground = false;
  12552. // States
  12553. /** @hidden */
  12554. this._depthCullingState = new BABYLON._DepthCullingState();
  12555. /** @hidden */
  12556. this._stencilState = new BABYLON._StencilState();
  12557. /** @hidden */
  12558. this._alphaState = new BABYLON._AlphaState();
  12559. /** @hidden */
  12560. this._alphaMode = Engine.ALPHA_DISABLE;
  12561. // Cache
  12562. this._internalTexturesCache = new Array();
  12563. /** @hidden */
  12564. this._activeChannel = 0;
  12565. this._currentTextureChannel = -1;
  12566. /** @hidden */
  12567. this._boundTexturesCache = {};
  12568. this._compiledEffects = {};
  12569. this._vertexAttribArraysEnabled = [];
  12570. this._uintIndicesCurrentlySet = false;
  12571. this._currentBoundBuffer = new Array();
  12572. /** @hidden */
  12573. this._currentFramebuffer = null;
  12574. this._currentBufferPointers = new Array();
  12575. this._currentInstanceLocations = new Array();
  12576. this._currentInstanceBuffers = new Array();
  12577. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  12578. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  12579. this._vaoRecordInProgress = false;
  12580. this._mustWipeVertexAttributes = false;
  12581. this._nextFreeTextureSlots = new Array();
  12582. this._maxSimultaneousTextures = 0;
  12583. this._activeRequests = new Array();
  12584. // Hardware supported Compressed Textures
  12585. this._texturesSupported = new Array();
  12586. /**
  12587. * Defines whether the engine has been created with the premultipliedAlpha option on or not.
  12588. */
  12589. this.premultipliedAlpha = true;
  12590. this._viewportCached = new BABYLON.Vector4(0, 0, 0, 0);
  12591. this._onVRFullScreenTriggered = function () {
  12592. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  12593. //get the old size before we change
  12594. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  12595. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  12596. //get the width and height, change the render size
  12597. var leftEye = _this._vrDisplay.getEyeParameters('left');
  12598. _this.setHardwareScalingLevel(1);
  12599. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  12600. }
  12601. else {
  12602. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  12603. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  12604. }
  12605. };
  12606. this._unpackFlipYCached = null;
  12607. /**
  12608. * In case you are sharing the context with other applications, it might
  12609. * be interested to not cache the unpack flip y state to ensure a consistent
  12610. * value would be set.
  12611. */
  12612. this.enableUnpackFlipYCached = true;
  12613. this._boundUniforms = {};
  12614. // Register promises
  12615. BABYLON.PromisePolyfill.Apply();
  12616. var canvas = null;
  12617. Engine.Instances.push(this);
  12618. if (!canvasOrContext) {
  12619. return;
  12620. }
  12621. options = options || {};
  12622. if (canvasOrContext.getContext) {
  12623. canvas = canvasOrContext;
  12624. this._renderingCanvas = canvas;
  12625. if (antialias != null) {
  12626. options.antialias = antialias;
  12627. }
  12628. if (options.deterministicLockstep === undefined) {
  12629. options.deterministicLockstep = false;
  12630. }
  12631. if (options.lockstepMaxSteps === undefined) {
  12632. options.lockstepMaxSteps = 4;
  12633. }
  12634. if (options.preserveDrawingBuffer === undefined) {
  12635. options.preserveDrawingBuffer = false;
  12636. }
  12637. if (options.audioEngine === undefined) {
  12638. options.audioEngine = true;
  12639. }
  12640. if (options.stencil === undefined) {
  12641. options.stencil = true;
  12642. }
  12643. if (options.premultipliedAlpha === false) {
  12644. this.premultipliedAlpha = false;
  12645. }
  12646. this._deterministicLockstep = options.deterministicLockstep;
  12647. this._lockstepMaxSteps = options.lockstepMaxSteps;
  12648. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  12649. // Exceptions
  12650. if (navigator && navigator.userAgent) {
  12651. var ua = navigator.userAgent;
  12652. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  12653. var exception = _a[_i];
  12654. var key = exception.key;
  12655. var targets = exception.targets;
  12656. if (ua.indexOf(key) > -1) {
  12657. if (exception.capture && exception.captureConstraint) {
  12658. var capture = exception.capture;
  12659. var constraint = exception.captureConstraint;
  12660. var regex = new RegExp(capture);
  12661. var matches = regex.exec(ua);
  12662. if (matches && matches.length > 0) {
  12663. var capturedValue = parseInt(matches[matches.length - 1]);
  12664. if (capturedValue >= constraint) {
  12665. continue;
  12666. }
  12667. }
  12668. }
  12669. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  12670. var target = targets_1[_b];
  12671. switch (target) {
  12672. case "uniformBuffer":
  12673. this.disableUniformBuffers = true;
  12674. break;
  12675. case "textureBindingOptimization":
  12676. this.disableTextureBindingOptimization = true;
  12677. break;
  12678. }
  12679. }
  12680. }
  12681. }
  12682. }
  12683. // GL
  12684. if (!options.disableWebGL2Support) {
  12685. try {
  12686. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  12687. if (this._gl) {
  12688. this._webGLVersion = 2.0;
  12689. // Prevent weird browsers to lie :-)
  12690. if (!this._gl.deleteQuery) {
  12691. this._webGLVersion = 1.0;
  12692. }
  12693. }
  12694. }
  12695. catch (e) {
  12696. // Do nothing
  12697. }
  12698. }
  12699. if (!this._gl) {
  12700. if (!canvas) {
  12701. throw new Error("The provided canvas is null or undefined.");
  12702. }
  12703. try {
  12704. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  12705. }
  12706. catch (e) {
  12707. throw new Error("WebGL not supported");
  12708. }
  12709. }
  12710. if (!this._gl) {
  12711. throw new Error("WebGL not supported");
  12712. }
  12713. this._onCanvasFocus = function () {
  12714. _this.onCanvasFocusObservable.notifyObservers(_this);
  12715. };
  12716. this._onCanvasBlur = function () {
  12717. _this.onCanvasBlurObservable.notifyObservers(_this);
  12718. };
  12719. canvas.addEventListener("focus", this._onCanvasFocus);
  12720. canvas.addEventListener("blur", this._onCanvasBlur);
  12721. this._onBlur = function () {
  12722. if (_this.disablePerformanceMonitorInBackground) {
  12723. _this._performanceMonitor.disable();
  12724. }
  12725. _this._windowIsBackground = true;
  12726. };
  12727. this._onFocus = function () {
  12728. if (_this.disablePerformanceMonitorInBackground) {
  12729. _this._performanceMonitor.enable();
  12730. }
  12731. _this._windowIsBackground = false;
  12732. };
  12733. this._onCanvasPointerOut = function (ev) {
  12734. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  12735. };
  12736. if (BABYLON.Tools.IsWindowObjectExist()) {
  12737. window.addEventListener("blur", this._onBlur);
  12738. window.addEventListener("focus", this._onFocus);
  12739. }
  12740. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  12741. // Context lost
  12742. if (!this._doNotHandleContextLost) {
  12743. this._onContextLost = function (evt) {
  12744. evt.preventDefault();
  12745. _this._contextWasLost = true;
  12746. BABYLON.Tools.Warn("WebGL context lost.");
  12747. _this.onContextLostObservable.notifyObservers(_this);
  12748. };
  12749. this._onContextRestored = function (evt) {
  12750. // Adding a timeout to avoid race condition at browser level
  12751. setTimeout(function () {
  12752. // Rebuild gl context
  12753. _this._initGLContext();
  12754. // Rebuild effects
  12755. _this._rebuildEffects();
  12756. // Rebuild textures
  12757. _this._rebuildInternalTextures();
  12758. // Rebuild buffers
  12759. _this._rebuildBuffers();
  12760. // Cache
  12761. _this.wipeCaches(true);
  12762. BABYLON.Tools.Warn("WebGL context successfully restored.");
  12763. _this.onContextRestoredObservable.notifyObservers(_this);
  12764. _this._contextWasLost = false;
  12765. }, 0);
  12766. };
  12767. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  12768. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  12769. }
  12770. if (!options.doNotHandleTouchAction) {
  12771. this._disableTouchAction();
  12772. }
  12773. }
  12774. else {
  12775. this._gl = canvasOrContext;
  12776. this._renderingCanvas = this._gl.canvas;
  12777. if (this._gl.renderbufferStorageMultisample) {
  12778. this._webGLVersion = 2.0;
  12779. }
  12780. var attributes = this._gl.getContextAttributes();
  12781. if (attributes) {
  12782. options.stencil = attributes.stencil;
  12783. }
  12784. }
  12785. // Viewport
  12786. var devicePixelRatio = BABYLON.Tools.IsWindowObjectExist() ? (window.devicePixelRatio || 1.0) : 1.0;
  12787. var limitDeviceRatio = options.limitDeviceRatio || devicePixelRatio;
  12788. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, devicePixelRatio) : 1.0;
  12789. this.resize();
  12790. this._isStencilEnable = options.stencil ? true : false;
  12791. this._initGLContext();
  12792. if (canvas) {
  12793. // Fullscreen
  12794. this._onFullscreenChange = function () {
  12795. if (document.fullscreen !== undefined) {
  12796. _this.isFullscreen = document.fullscreen;
  12797. }
  12798. else if (document.mozFullScreen !== undefined) {
  12799. _this.isFullscreen = document.mozFullScreen;
  12800. }
  12801. else if (document.webkitIsFullScreen !== undefined) {
  12802. _this.isFullscreen = document.webkitIsFullScreen;
  12803. }
  12804. else if (document.msIsFullScreen !== undefined) {
  12805. _this.isFullscreen = document.msIsFullScreen;
  12806. }
  12807. // Pointer lock
  12808. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  12809. canvas.requestPointerLock = canvas.requestPointerLock ||
  12810. canvas.msRequestPointerLock ||
  12811. canvas.mozRequestPointerLock ||
  12812. canvas.webkitRequestPointerLock;
  12813. if (canvas.requestPointerLock) {
  12814. canvas.requestPointerLock();
  12815. }
  12816. }
  12817. };
  12818. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  12819. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  12820. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  12821. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  12822. // Pointer lock
  12823. this._onPointerLockChange = function () {
  12824. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  12825. document.webkitPointerLockElement === canvas ||
  12826. document.msPointerLockElement === canvas ||
  12827. document.pointerLockElement === canvas);
  12828. };
  12829. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  12830. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  12831. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  12832. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  12833. this._onVRDisplayPointerRestricted = function () {
  12834. if (canvas) {
  12835. canvas.requestPointerLock();
  12836. }
  12837. };
  12838. this._onVRDisplayPointerUnrestricted = function () {
  12839. document.exitPointerLock();
  12840. };
  12841. if (BABYLON.Tools.IsWindowObjectExist()) {
  12842. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  12843. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  12844. }
  12845. }
  12846. // Create Audio Engine if needed.
  12847. if (!Engine.audioEngine && options.audioEngine && Engine.AudioEngineFactory) {
  12848. Engine.audioEngine = Engine.AudioEngineFactory(this.getRenderingCanvas());
  12849. }
  12850. // Prepare buffer pointers
  12851. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  12852. this._currentBufferPointers[i] = new BufferPointer();
  12853. }
  12854. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  12855. // Load WebVR Devices
  12856. if (options.autoEnableWebVR) {
  12857. this.initWebVR();
  12858. }
  12859. // Detect if we are running on a faulty buggy OS.
  12860. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  12861. // Detect if we are running on a faulty buggy desktop OS.
  12862. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  12863. console.log("Babylon.js v" + Engine.Version + " - " + this.description);
  12864. this.enableOfflineSupport = Engine.OfflineProviderFactory !== undefined;
  12865. }
  12866. Object.defineProperty(Engine, "LastCreatedEngine", {
  12867. /**
  12868. * Gets the latest created engine
  12869. */
  12870. get: function () {
  12871. if (Engine.Instances.length === 0) {
  12872. return null;
  12873. }
  12874. return Engine.Instances[Engine.Instances.length - 1];
  12875. },
  12876. enumerable: true,
  12877. configurable: true
  12878. });
  12879. Object.defineProperty(Engine, "LastCreatedScene", {
  12880. /**
  12881. * Gets the latest created scene
  12882. */
  12883. get: function () {
  12884. var lastCreatedEngine = Engine.LastCreatedEngine;
  12885. if (!lastCreatedEngine) {
  12886. return null;
  12887. }
  12888. if (lastCreatedEngine.scenes.length === 0) {
  12889. return null;
  12890. }
  12891. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  12892. },
  12893. enumerable: true,
  12894. configurable: true
  12895. });
  12896. /**
  12897. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  12898. * @param flag defines which part of the materials must be marked as dirty
  12899. * @param predicate defines a predicate used to filter which materials should be affected
  12900. */
  12901. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  12902. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  12903. var engine = Engine.Instances[engineIndex];
  12904. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  12905. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  12906. }
  12907. }
  12908. };
  12909. Object.defineProperty(Engine, "Version", {
  12910. /**
  12911. * Returns the current version of the framework
  12912. */
  12913. get: function () {
  12914. return "4.0.0-alpha.16";
  12915. },
  12916. enumerable: true,
  12917. configurable: true
  12918. });
  12919. Object.defineProperty(Engine.prototype, "description", {
  12920. /**
  12921. * Returns a string describing the current engine
  12922. */
  12923. get: function () {
  12924. var description = "WebGL" + this.webGLVersion;
  12925. if (this._caps.parallelShaderCompile) {
  12926. description += " - Parallel shader compilation";
  12927. }
  12928. return description;
  12929. },
  12930. enumerable: true,
  12931. configurable: true
  12932. });
  12933. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  12934. /**
  12935. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  12936. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  12937. */
  12938. get: function () {
  12939. return this._vrExclusivePointerMode;
  12940. },
  12941. enumerable: true,
  12942. configurable: true
  12943. });
  12944. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  12945. /**
  12946. * Gets a boolean indicating that the engine supports uniform buffers
  12947. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12948. */
  12949. get: function () {
  12950. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  12951. },
  12952. enumerable: true,
  12953. configurable: true
  12954. });
  12955. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  12956. /**
  12957. * Gets a boolean indicating that only power of 2 textures are supported
  12958. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  12959. */
  12960. get: function () {
  12961. return this._webGLVersion < 2 || this.forcePOTTextures;
  12962. },
  12963. enumerable: true,
  12964. configurable: true
  12965. });
  12966. Object.defineProperty(Engine.prototype, "doNotHandleContextLost", {
  12967. /**
  12968. * Gets or sets a boolean indicating if resources should be retained to be able to handle context lost events
  12969. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#handling-webgl-context-lost
  12970. */
  12971. get: function () {
  12972. return this._doNotHandleContextLost;
  12973. },
  12974. set: function (value) {
  12975. this._doNotHandleContextLost = value;
  12976. },
  12977. enumerable: true,
  12978. configurable: true
  12979. });
  12980. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  12981. /**
  12982. * Gets the performance monitor attached to this engine
  12983. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  12984. */
  12985. get: function () {
  12986. return this._performanceMonitor;
  12987. },
  12988. enumerable: true,
  12989. configurable: true
  12990. });
  12991. Object.defineProperty(Engine.prototype, "texturesSupported", {
  12992. /**
  12993. * Gets the list of texture formats supported
  12994. */
  12995. get: function () {
  12996. return this._texturesSupported;
  12997. },
  12998. enumerable: true,
  12999. configurable: true
  13000. });
  13001. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  13002. /**
  13003. * Gets the list of texture formats in use
  13004. */
  13005. get: function () {
  13006. return this._textureFormatInUse;
  13007. },
  13008. enumerable: true,
  13009. configurable: true
  13010. });
  13011. Object.defineProperty(Engine.prototype, "currentViewport", {
  13012. /**
  13013. * Gets the current viewport
  13014. */
  13015. get: function () {
  13016. return this._cachedViewport;
  13017. },
  13018. enumerable: true,
  13019. configurable: true
  13020. });
  13021. Object.defineProperty(Engine.prototype, "emptyTexture", {
  13022. /**
  13023. * Gets the default empty texture
  13024. */
  13025. get: function () {
  13026. if (!this._emptyTexture) {
  13027. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  13028. }
  13029. return this._emptyTexture;
  13030. },
  13031. enumerable: true,
  13032. configurable: true
  13033. });
  13034. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  13035. /**
  13036. * Gets the default empty 3D texture
  13037. */
  13038. get: function () {
  13039. if (!this._emptyTexture3D) {
  13040. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  13041. }
  13042. return this._emptyTexture3D;
  13043. },
  13044. enumerable: true,
  13045. configurable: true
  13046. });
  13047. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  13048. /**
  13049. * Gets the default empty cube texture
  13050. */
  13051. get: function () {
  13052. if (!this._emptyCubeTexture) {
  13053. var faceData = new Uint8Array(4);
  13054. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  13055. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  13056. }
  13057. return this._emptyCubeTexture;
  13058. },
  13059. enumerable: true,
  13060. configurable: true
  13061. });
  13062. Engine.prototype._disableTouchAction = function () {
  13063. if (!this._renderingCanvas) {
  13064. return;
  13065. }
  13066. this._renderingCanvas.setAttribute("touch-action", "none");
  13067. this._renderingCanvas.style.touchAction = "none";
  13068. this._renderingCanvas.style.msTouchAction = "none";
  13069. };
  13070. Engine.prototype._rebuildInternalTextures = function () {
  13071. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  13072. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  13073. var internalTexture = currentState_1[_i];
  13074. internalTexture._rebuild();
  13075. }
  13076. };
  13077. Engine.prototype._rebuildEffects = function () {
  13078. for (var key in this._compiledEffects) {
  13079. var effect = this._compiledEffects[key];
  13080. effect._prepareEffect();
  13081. }
  13082. BABYLON.Effect.ResetCache();
  13083. };
  13084. /**
  13085. * Gets a boolean indicating if all created effects are ready
  13086. * @returns true if all effects are ready
  13087. */
  13088. Engine.prototype.areAllEffectsReady = function () {
  13089. for (var key in this._compiledEffects) {
  13090. var effect = this._compiledEffects[key];
  13091. if (!effect.isReady()) {
  13092. return false;
  13093. }
  13094. }
  13095. return true;
  13096. };
  13097. Engine.prototype._rebuildBuffers = function () {
  13098. // Index / Vertex
  13099. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  13100. var scene = _a[_i];
  13101. scene.resetCachedMaterial();
  13102. scene._rebuildGeometries();
  13103. scene._rebuildTextures();
  13104. }
  13105. // Uniforms
  13106. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  13107. var uniformBuffer = _c[_b];
  13108. uniformBuffer._rebuild();
  13109. }
  13110. };
  13111. Engine.prototype._initGLContext = function () {
  13112. // Caps
  13113. this._caps = new EngineCapabilities();
  13114. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  13115. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  13116. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  13117. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  13118. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  13119. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  13120. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  13121. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  13122. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  13123. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  13124. // Infos
  13125. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  13126. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  13127. if (rendererInfo != null) {
  13128. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  13129. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  13130. }
  13131. if (!this._glVendor) {
  13132. this._glVendor = "Unknown vendor";
  13133. }
  13134. if (!this._glRenderer) {
  13135. this._glRenderer = "Unknown renderer";
  13136. }
  13137. // Constants
  13138. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  13139. if (this._gl.RGBA16F !== 0x881A) {
  13140. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  13141. }
  13142. if (this._gl.RGBA32F !== 0x8814) {
  13143. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  13144. }
  13145. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  13146. this._gl.DEPTH24_STENCIL8 = 35056;
  13147. }
  13148. // Extensions
  13149. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  13150. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  13151. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  13152. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  13153. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  13154. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  13155. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  13156. 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');
  13157. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  13158. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  13159. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  13160. this._caps.highPrecisionShaderSupported = false;
  13161. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  13162. if (this._caps.timerQuery) {
  13163. if (this._webGLVersion === 1) {
  13164. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  13165. }
  13166. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  13167. }
  13168. // Checks if some of the format renders first to allow the use of webgl inspector.
  13169. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  13170. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  13171. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  13172. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  13173. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  13174. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  13175. if (this._webGLVersion > 1) {
  13176. this._gl.HALF_FLOAT_OES = 0x140B;
  13177. }
  13178. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  13179. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  13180. // Draw buffers
  13181. if (this._webGLVersion > 1) {
  13182. this._caps.drawBuffersExtension = true;
  13183. }
  13184. else {
  13185. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  13186. if (drawBuffersExtension !== null) {
  13187. this._caps.drawBuffersExtension = true;
  13188. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  13189. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  13190. for (var i = 0; i < 16; i++) {
  13191. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  13192. }
  13193. }
  13194. else {
  13195. this._caps.drawBuffersExtension = false;
  13196. }
  13197. }
  13198. // Shader compiler threads
  13199. this._caps.parallelShaderCompile = this._gl.getExtension('KHR_parallel_shader_compile');
  13200. if (this._caps.parallelShaderCompile) {
  13201. var threads = this._gl.getParameter(this._caps.parallelShaderCompile.MAX_SHADER_COMPILER_THREADS_KHR);
  13202. this._caps.parallelShaderCompile.maxShaderCompilerThreadsKHR(threads);
  13203. }
  13204. // Depth Texture
  13205. if (this._webGLVersion > 1) {
  13206. this._caps.depthTextureExtension = true;
  13207. }
  13208. else {
  13209. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  13210. if (depthTextureExtension != null) {
  13211. this._caps.depthTextureExtension = true;
  13212. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  13213. }
  13214. }
  13215. // Vertex array object
  13216. if (this._webGLVersion > 1) {
  13217. this._caps.vertexArrayObject = true;
  13218. }
  13219. else {
  13220. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  13221. if (vertexArrayObjectExtension != null) {
  13222. this._caps.vertexArrayObject = true;
  13223. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  13224. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  13225. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  13226. }
  13227. else {
  13228. this._caps.vertexArrayObject = false;
  13229. }
  13230. }
  13231. // Instances count
  13232. if (this._webGLVersion > 1) {
  13233. this._caps.instancedArrays = true;
  13234. }
  13235. else {
  13236. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  13237. if (instanceExtension != null) {
  13238. this._caps.instancedArrays = true;
  13239. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  13240. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  13241. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  13242. }
  13243. else {
  13244. this._caps.instancedArrays = false;
  13245. }
  13246. }
  13247. // Intelligently add supported compressed formats in order to check for.
  13248. // Check for ASTC support first as it is most powerful and to be very cross platform.
  13249. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  13250. // Likely no hardware which supports both PVR & DXT, so order matters little.
  13251. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  13252. if (this._caps.astc) {
  13253. this.texturesSupported.push('-astc.ktx');
  13254. }
  13255. if (this._caps.s3tc) {
  13256. this.texturesSupported.push('-dxt.ktx');
  13257. }
  13258. if (this._caps.pvrtc) {
  13259. this.texturesSupported.push('-pvrtc.ktx');
  13260. }
  13261. if (this._caps.etc2) {
  13262. this.texturesSupported.push('-etc2.ktx');
  13263. }
  13264. if (this._caps.etc1) {
  13265. this.texturesSupported.push('-etc1.ktx');
  13266. }
  13267. if (this._gl.getShaderPrecisionFormat) {
  13268. var vertex_highp = this._gl.getShaderPrecisionFormat(this._gl.VERTEX_SHADER, this._gl.HIGH_FLOAT);
  13269. var fragment_highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  13270. if (vertex_highp && fragment_highp) {
  13271. this._caps.highPrecisionShaderSupported = vertex_highp.precision !== 0 && fragment_highp.precision !== 0;
  13272. }
  13273. }
  13274. // Depth buffer
  13275. this.setDepthBuffer(true);
  13276. this.setDepthFunctionToLessOrEqual();
  13277. this.setDepthWrite(true);
  13278. // Texture maps
  13279. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  13280. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  13281. this._nextFreeTextureSlots.push(slot);
  13282. }
  13283. };
  13284. Object.defineProperty(Engine.prototype, "webGLVersion", {
  13285. /**
  13286. * Gets version of the current webGL context
  13287. */
  13288. get: function () {
  13289. return this._webGLVersion;
  13290. },
  13291. enumerable: true,
  13292. configurable: true
  13293. });
  13294. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  13295. /**
  13296. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  13297. */
  13298. get: function () {
  13299. return this._isStencilEnable;
  13300. },
  13301. enumerable: true,
  13302. configurable: true
  13303. });
  13304. Engine.prototype._prepareWorkingCanvas = function () {
  13305. if (this._workingCanvas) {
  13306. return;
  13307. }
  13308. this._workingCanvas = document.createElement("canvas");
  13309. var context = this._workingCanvas.getContext("2d");
  13310. if (context) {
  13311. this._workingContext = context;
  13312. }
  13313. };
  13314. /**
  13315. * Reset the texture cache to empty state
  13316. */
  13317. Engine.prototype.resetTextureCache = function () {
  13318. for (var key in this._boundTexturesCache) {
  13319. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  13320. continue;
  13321. }
  13322. var boundTexture = this._boundTexturesCache[key];
  13323. if (boundTexture) {
  13324. this._removeDesignatedSlot(boundTexture);
  13325. }
  13326. this._boundTexturesCache[key] = null;
  13327. }
  13328. if (!this.disableTextureBindingOptimization) {
  13329. this._nextFreeTextureSlots = [];
  13330. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  13331. this._nextFreeTextureSlots.push(slot);
  13332. }
  13333. }
  13334. this._currentTextureChannel = -1;
  13335. };
  13336. /**
  13337. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  13338. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  13339. * @returns true if engine is in deterministic lock step mode
  13340. */
  13341. Engine.prototype.isDeterministicLockStep = function () {
  13342. return this._deterministicLockstep;
  13343. };
  13344. /**
  13345. * Gets the max steps when engine is running in deterministic lock step
  13346. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  13347. * @returns the max steps
  13348. */
  13349. Engine.prototype.getLockstepMaxSteps = function () {
  13350. return this._lockstepMaxSteps;
  13351. };
  13352. /**
  13353. * Gets an object containing information about the current webGL context
  13354. * @returns an object containing the vender, the renderer and the version of the current webGL context
  13355. */
  13356. Engine.prototype.getGlInfo = function () {
  13357. return {
  13358. vendor: this._glVendor,
  13359. renderer: this._glRenderer,
  13360. version: this._glVersion
  13361. };
  13362. };
  13363. /**
  13364. * Gets current aspect ratio
  13365. * @param camera defines the camera to use to get the aspect ratio
  13366. * @param useScreen defines if screen size must be used (or the current render target if any)
  13367. * @returns a number defining the aspect ratio
  13368. */
  13369. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  13370. if (useScreen === void 0) { useScreen = false; }
  13371. var viewport = camera.viewport;
  13372. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  13373. };
  13374. /**
  13375. * Gets current screen aspect ratio
  13376. * @returns a number defining the aspect ratio
  13377. */
  13378. Engine.prototype.getScreenAspectRatio = function () {
  13379. return (this.getRenderWidth(true)) / (this.getRenderHeight(true));
  13380. };
  13381. /**
  13382. * Gets the current render width
  13383. * @param useScreen defines if screen size must be used (or the current render target if any)
  13384. * @returns a number defining the current render width
  13385. */
  13386. Engine.prototype.getRenderWidth = function (useScreen) {
  13387. if (useScreen === void 0) { useScreen = false; }
  13388. if (!useScreen && this._currentRenderTarget) {
  13389. return this._currentRenderTarget.width;
  13390. }
  13391. return this._gl.drawingBufferWidth;
  13392. };
  13393. /**
  13394. * Gets the current render height
  13395. * @param useScreen defines if screen size must be used (or the current render target if any)
  13396. * @returns a number defining the current render height
  13397. */
  13398. Engine.prototype.getRenderHeight = function (useScreen) {
  13399. if (useScreen === void 0) { useScreen = false; }
  13400. if (!useScreen && this._currentRenderTarget) {
  13401. return this._currentRenderTarget.height;
  13402. }
  13403. return this._gl.drawingBufferHeight;
  13404. };
  13405. /**
  13406. * Gets the HTML canvas attached with the current webGL context
  13407. * @returns a HTML canvas
  13408. */
  13409. Engine.prototype.getRenderingCanvas = function () {
  13410. return this._renderingCanvas;
  13411. };
  13412. /**
  13413. * Gets the client rect of the HTML canvas attached with the current webGL context
  13414. * @returns a client rectanglee
  13415. */
  13416. Engine.prototype.getRenderingCanvasClientRect = function () {
  13417. if (!this._renderingCanvas) {
  13418. return null;
  13419. }
  13420. return this._renderingCanvas.getBoundingClientRect();
  13421. };
  13422. /**
  13423. * Defines the hardware scaling level.
  13424. * By default the hardware scaling level is computed from the window device ratio.
  13425. * 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.
  13426. * @param level defines the level to use
  13427. */
  13428. Engine.prototype.setHardwareScalingLevel = function (level) {
  13429. this._hardwareScalingLevel = level;
  13430. this.resize();
  13431. };
  13432. /**
  13433. * Gets the current hardware scaling level.
  13434. * By default the hardware scaling level is computed from the window device ratio.
  13435. * 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.
  13436. * @returns a number indicating the current hardware scaling level
  13437. */
  13438. Engine.prototype.getHardwareScalingLevel = function () {
  13439. return this._hardwareScalingLevel;
  13440. };
  13441. /**
  13442. * Gets the list of loaded textures
  13443. * @returns an array containing all loaded textures
  13444. */
  13445. Engine.prototype.getLoadedTexturesCache = function () {
  13446. return this._internalTexturesCache;
  13447. };
  13448. /**
  13449. * Gets the object containing all engine capabilities
  13450. * @returns the EngineCapabilities object
  13451. */
  13452. Engine.prototype.getCaps = function () {
  13453. return this._caps;
  13454. };
  13455. /**
  13456. * Gets the current depth function
  13457. * @returns a number defining the depth function
  13458. */
  13459. Engine.prototype.getDepthFunction = function () {
  13460. return this._depthCullingState.depthFunc;
  13461. };
  13462. /**
  13463. * Sets the current depth function
  13464. * @param depthFunc defines the function to use
  13465. */
  13466. Engine.prototype.setDepthFunction = function (depthFunc) {
  13467. this._depthCullingState.depthFunc = depthFunc;
  13468. };
  13469. /**
  13470. * Sets the current depth function to GREATER
  13471. */
  13472. Engine.prototype.setDepthFunctionToGreater = function () {
  13473. this._depthCullingState.depthFunc = this._gl.GREATER;
  13474. };
  13475. /**
  13476. * Sets the current depth function to GEQUAL
  13477. */
  13478. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  13479. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  13480. };
  13481. /**
  13482. * Sets the current depth function to LESS
  13483. */
  13484. Engine.prototype.setDepthFunctionToLess = function () {
  13485. this._depthCullingState.depthFunc = this._gl.LESS;
  13486. };
  13487. /**
  13488. * Sets the current depth function to LEQUAL
  13489. */
  13490. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  13491. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  13492. };
  13493. /**
  13494. * Gets a boolean indicating if stencil buffer is enabled
  13495. * @returns the current stencil buffer state
  13496. */
  13497. Engine.prototype.getStencilBuffer = function () {
  13498. return this._stencilState.stencilTest;
  13499. };
  13500. /**
  13501. * Enable or disable the stencil buffer
  13502. * @param enable defines if the stencil buffer must be enabled or disabled
  13503. */
  13504. Engine.prototype.setStencilBuffer = function (enable) {
  13505. this._stencilState.stencilTest = enable;
  13506. };
  13507. /**
  13508. * Gets the current stencil mask
  13509. * @returns a number defining the new stencil mask to use
  13510. */
  13511. Engine.prototype.getStencilMask = function () {
  13512. return this._stencilState.stencilMask;
  13513. };
  13514. /**
  13515. * Sets the current stencil mask
  13516. * @param mask defines the new stencil mask to use
  13517. */
  13518. Engine.prototype.setStencilMask = function (mask) {
  13519. this._stencilState.stencilMask = mask;
  13520. };
  13521. /**
  13522. * Gets the current stencil function
  13523. * @returns a number defining the stencil function to use
  13524. */
  13525. Engine.prototype.getStencilFunction = function () {
  13526. return this._stencilState.stencilFunc;
  13527. };
  13528. /**
  13529. * Gets the current stencil reference value
  13530. * @returns a number defining the stencil reference value to use
  13531. */
  13532. Engine.prototype.getStencilFunctionReference = function () {
  13533. return this._stencilState.stencilFuncRef;
  13534. };
  13535. /**
  13536. * Gets the current stencil mask
  13537. * @returns a number defining the stencil mask to use
  13538. */
  13539. Engine.prototype.getStencilFunctionMask = function () {
  13540. return this._stencilState.stencilFuncMask;
  13541. };
  13542. /**
  13543. * Sets the current stencil function
  13544. * @param stencilFunc defines the new stencil function to use
  13545. */
  13546. Engine.prototype.setStencilFunction = function (stencilFunc) {
  13547. this._stencilState.stencilFunc = stencilFunc;
  13548. };
  13549. /**
  13550. * Sets the current stencil reference
  13551. * @param reference defines the new stencil reference to use
  13552. */
  13553. Engine.prototype.setStencilFunctionReference = function (reference) {
  13554. this._stencilState.stencilFuncRef = reference;
  13555. };
  13556. /**
  13557. * Sets the current stencil mask
  13558. * @param mask defines the new stencil mask to use
  13559. */
  13560. Engine.prototype.setStencilFunctionMask = function (mask) {
  13561. this._stencilState.stencilFuncMask = mask;
  13562. };
  13563. /**
  13564. * Gets the current stencil operation when stencil fails
  13565. * @returns a number defining stencil operation to use when stencil fails
  13566. */
  13567. Engine.prototype.getStencilOperationFail = function () {
  13568. return this._stencilState.stencilOpStencilFail;
  13569. };
  13570. /**
  13571. * Gets the current stencil operation when depth fails
  13572. * @returns a number defining stencil operation to use when depth fails
  13573. */
  13574. Engine.prototype.getStencilOperationDepthFail = function () {
  13575. return this._stencilState.stencilOpDepthFail;
  13576. };
  13577. /**
  13578. * Gets the current stencil operation when stencil passes
  13579. * @returns a number defining stencil operation to use when stencil passes
  13580. */
  13581. Engine.prototype.getStencilOperationPass = function () {
  13582. return this._stencilState.stencilOpStencilDepthPass;
  13583. };
  13584. /**
  13585. * Sets the stencil operation to use when stencil fails
  13586. * @param operation defines the stencil operation to use when stencil fails
  13587. */
  13588. Engine.prototype.setStencilOperationFail = function (operation) {
  13589. this._stencilState.stencilOpStencilFail = operation;
  13590. };
  13591. /**
  13592. * Sets the stencil operation to use when depth fails
  13593. * @param operation defines the stencil operation to use when depth fails
  13594. */
  13595. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  13596. this._stencilState.stencilOpDepthFail = operation;
  13597. };
  13598. /**
  13599. * Sets the stencil operation to use when stencil passes
  13600. * @param operation defines the stencil operation to use when stencil passes
  13601. */
  13602. Engine.prototype.setStencilOperationPass = function (operation) {
  13603. this._stencilState.stencilOpStencilDepthPass = operation;
  13604. };
  13605. /**
  13606. * Sets a boolean indicating if the dithering state is enabled or disabled
  13607. * @param value defines the dithering state
  13608. */
  13609. Engine.prototype.setDitheringState = function (value) {
  13610. if (value) {
  13611. this._gl.enable(this._gl.DITHER);
  13612. }
  13613. else {
  13614. this._gl.disable(this._gl.DITHER);
  13615. }
  13616. };
  13617. /**
  13618. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  13619. * @param value defines the rasterizer state
  13620. */
  13621. Engine.prototype.setRasterizerState = function (value) {
  13622. if (value) {
  13623. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  13624. }
  13625. else {
  13626. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  13627. }
  13628. };
  13629. /**
  13630. * stop executing a render loop function and remove it from the execution array
  13631. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  13632. */
  13633. Engine.prototype.stopRenderLoop = function (renderFunction) {
  13634. if (!renderFunction) {
  13635. this._activeRenderLoops = [];
  13636. return;
  13637. }
  13638. var index = this._activeRenderLoops.indexOf(renderFunction);
  13639. if (index >= 0) {
  13640. this._activeRenderLoops.splice(index, 1);
  13641. }
  13642. };
  13643. /** @hidden */
  13644. Engine.prototype._renderLoop = function () {
  13645. if (!this._contextWasLost) {
  13646. var shouldRender = true;
  13647. if (!this.renderEvenInBackground && this._windowIsBackground) {
  13648. shouldRender = false;
  13649. }
  13650. if (shouldRender) {
  13651. // Start new frame
  13652. this.beginFrame();
  13653. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  13654. var renderFunction = this._activeRenderLoops[index];
  13655. renderFunction();
  13656. }
  13657. // Present
  13658. this.endFrame();
  13659. }
  13660. }
  13661. if (this._activeRenderLoops.length > 0) {
  13662. // Register new frame
  13663. if (this.customAnimationFrameRequester) {
  13664. this.customAnimationFrameRequester.requestID = BABYLON.Tools.QueueNewFrame(this.customAnimationFrameRequester.renderFunction || this._bindedRenderFunction, this.customAnimationFrameRequester);
  13665. this._frameHandler = this.customAnimationFrameRequester.requestID;
  13666. }
  13667. else if (this._vrDisplay && this._vrDisplay.isPresenting) {
  13668. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, this._vrDisplay);
  13669. }
  13670. else {
  13671. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  13672. }
  13673. }
  13674. else {
  13675. this._renderingQueueLaunched = false;
  13676. }
  13677. };
  13678. /**
  13679. * Register and execute a render loop. The engine can have more than one render function
  13680. * @param renderFunction defines the function to continuously execute
  13681. */
  13682. Engine.prototype.runRenderLoop = function (renderFunction) {
  13683. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  13684. return;
  13685. }
  13686. this._activeRenderLoops.push(renderFunction);
  13687. if (!this._renderingQueueLaunched) {
  13688. this._renderingQueueLaunched = true;
  13689. this._bindedRenderFunction = this._renderLoop.bind(this);
  13690. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  13691. }
  13692. };
  13693. /**
  13694. * Toggle full screen mode
  13695. * @param requestPointerLock defines if a pointer lock should be requested from the user
  13696. */
  13697. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  13698. if (this.isFullscreen) {
  13699. BABYLON.Tools.ExitFullscreen();
  13700. }
  13701. else {
  13702. this._pointerLockRequested = requestPointerLock;
  13703. if (this._renderingCanvas) {
  13704. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  13705. }
  13706. }
  13707. };
  13708. /**
  13709. * Clear the current render buffer or the current render target (if any is set up)
  13710. * @param color defines the color to use
  13711. * @param backBuffer defines if the back buffer must be cleared
  13712. * @param depth defines if the depth buffer must be cleared
  13713. * @param stencil defines if the stencil buffer must be cleared
  13714. */
  13715. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  13716. if (stencil === void 0) { stencil = false; }
  13717. this.applyStates();
  13718. var mode = 0;
  13719. if (backBuffer && color) {
  13720. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  13721. mode |= this._gl.COLOR_BUFFER_BIT;
  13722. }
  13723. if (depth) {
  13724. this._gl.clearDepth(1.0);
  13725. mode |= this._gl.DEPTH_BUFFER_BIT;
  13726. }
  13727. if (stencil) {
  13728. this._gl.clearStencil(0);
  13729. mode |= this._gl.STENCIL_BUFFER_BIT;
  13730. }
  13731. this._gl.clear(mode);
  13732. };
  13733. /**
  13734. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  13735. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  13736. * @param y defines the y-coordinate of the corner of the clear rectangle
  13737. * @param width defines the width of the clear rectangle
  13738. * @param height defines the height of the clear rectangle
  13739. * @param clearColor defines the clear color
  13740. */
  13741. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  13742. this.enableScissor(x, y, width, height);
  13743. this.clear(clearColor, true, true, true);
  13744. this.disableScissor();
  13745. };
  13746. /**
  13747. * Enable scissor test on a specific rectangle (ie. render will only be executed on a specific portion of the screen)
  13748. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  13749. * @param y defines the y-coordinate of the corner of the clear rectangle
  13750. * @param width defines the width of the clear rectangle
  13751. * @param height defines the height of the clear rectangle
  13752. */
  13753. Engine.prototype.enableScissor = function (x, y, width, height) {
  13754. var gl = this._gl;
  13755. // Change state
  13756. gl.enable(gl.SCISSOR_TEST);
  13757. gl.scissor(x, y, width, height);
  13758. };
  13759. /**
  13760. * Disable previously set scissor test rectangle
  13761. */
  13762. Engine.prototype.disableScissor = function () {
  13763. var gl = this._gl;
  13764. gl.disable(gl.SCISSOR_TEST);
  13765. };
  13766. /** @hidden */
  13767. Engine.prototype._viewport = function (x, y, width, height) {
  13768. if (x !== this._viewportCached.x ||
  13769. y !== this._viewportCached.y ||
  13770. width !== this._viewportCached.z ||
  13771. height !== this._viewportCached.w) {
  13772. this._viewportCached.x = x;
  13773. this._viewportCached.y = y;
  13774. this._viewportCached.z = width;
  13775. this._viewportCached.w = height;
  13776. this._gl.viewport(x, y, width, height);
  13777. }
  13778. };
  13779. /**
  13780. * Set the WebGL's viewport
  13781. * @param viewport defines the viewport element to be used
  13782. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  13783. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  13784. */
  13785. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  13786. var width = requiredWidth || this.getRenderWidth();
  13787. var height = requiredHeight || this.getRenderHeight();
  13788. var x = viewport.x || 0;
  13789. var y = viewport.y || 0;
  13790. this._cachedViewport = viewport;
  13791. this._viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  13792. };
  13793. /**
  13794. * Directly set the WebGL Viewport
  13795. * @param x defines the x coordinate of the viewport (in screen space)
  13796. * @param y defines the y coordinate of the viewport (in screen space)
  13797. * @param width defines the width of the viewport (in screen space)
  13798. * @param height defines the height of the viewport (in screen space)
  13799. * @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
  13800. */
  13801. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  13802. var currentViewport = this._cachedViewport;
  13803. this._cachedViewport = null;
  13804. this._viewport(x, y, width, height);
  13805. return currentViewport;
  13806. };
  13807. /**
  13808. * Begin a new frame
  13809. */
  13810. Engine.prototype.beginFrame = function () {
  13811. this.onBeginFrameObservable.notifyObservers(this);
  13812. this._measureFps();
  13813. };
  13814. /**
  13815. * Enf the current frame
  13816. */
  13817. Engine.prototype.endFrame = function () {
  13818. // Force a flush in case we are using a bad OS.
  13819. if (this._badOS) {
  13820. this.flushFramebuffer();
  13821. }
  13822. // Submit frame to the vr device, if enabled
  13823. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  13824. // TODO: We should only submit the frame if we read frameData successfully.
  13825. this._vrDisplay.submitFrame();
  13826. }
  13827. this.onEndFrameObservable.notifyObservers(this);
  13828. };
  13829. /**
  13830. * Resize the view according to the canvas' size
  13831. */
  13832. Engine.prototype.resize = function () {
  13833. // We're not resizing the size of the canvas while in VR mode & presenting
  13834. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  13835. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  13836. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  13837. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  13838. }
  13839. };
  13840. /**
  13841. * Force a specific size of the canvas
  13842. * @param width defines the new canvas' width
  13843. * @param height defines the new canvas' height
  13844. */
  13845. Engine.prototype.setSize = function (width, height) {
  13846. if (!this._renderingCanvas) {
  13847. return;
  13848. }
  13849. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  13850. return;
  13851. }
  13852. this._renderingCanvas.width = width;
  13853. this._renderingCanvas.height = height;
  13854. for (var index = 0; index < this.scenes.length; index++) {
  13855. var scene = this.scenes[index];
  13856. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  13857. var cam = scene.cameras[camIndex];
  13858. cam._currentRenderId = 0;
  13859. }
  13860. }
  13861. if (this.onResizeObservable.hasObservers) {
  13862. this.onResizeObservable.notifyObservers(this);
  13863. }
  13864. };
  13865. // WebVR functions
  13866. /**
  13867. * Gets a boolean indicating if a webVR device was detected
  13868. * @returns true if a webVR device was detected
  13869. */
  13870. Engine.prototype.isVRDevicePresent = function () {
  13871. return !!this._vrDisplay;
  13872. };
  13873. /**
  13874. * Gets the current webVR device
  13875. * @returns the current webVR device (or null)
  13876. */
  13877. Engine.prototype.getVRDevice = function () {
  13878. return this._vrDisplay;
  13879. };
  13880. /**
  13881. * Initializes a webVR display and starts listening to display change events
  13882. * The onVRDisplayChangedObservable will be notified upon these changes
  13883. * @returns The onVRDisplayChangedObservable
  13884. */
  13885. Engine.prototype.initWebVR = function () {
  13886. this.initWebVRAsync();
  13887. return this.onVRDisplayChangedObservable;
  13888. };
  13889. /**
  13890. * Initializes a webVR display and starts listening to display change events
  13891. * The onVRDisplayChangedObservable will be notified upon these changes
  13892. * @returns A promise containing a VRDisplay and if vr is supported
  13893. */
  13894. Engine.prototype.initWebVRAsync = function () {
  13895. var _this = this;
  13896. var notifyObservers = function () {
  13897. var eventArgs = {
  13898. vrDisplay: _this._vrDisplay,
  13899. vrSupported: _this._vrSupported
  13900. };
  13901. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  13902. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  13903. };
  13904. if (!this._onVrDisplayConnect) {
  13905. this._onVrDisplayConnect = function (event) {
  13906. _this._vrDisplay = event.display;
  13907. notifyObservers();
  13908. };
  13909. this._onVrDisplayDisconnect = function () {
  13910. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  13911. _this._vrDisplay = undefined;
  13912. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  13913. notifyObservers();
  13914. };
  13915. this._onVrDisplayPresentChange = function () {
  13916. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  13917. };
  13918. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  13919. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  13920. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  13921. }
  13922. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  13923. this._webVRInitPromise.then(notifyObservers);
  13924. return this._webVRInitPromise;
  13925. };
  13926. /**
  13927. * Call this function to switch to webVR mode
  13928. * Will do nothing if webVR is not supported or if there is no webVR device
  13929. * @see http://doc.babylonjs.com/how_to/webvr_camera
  13930. */
  13931. Engine.prototype.enableVR = function () {
  13932. var _this = this;
  13933. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  13934. var onResolved = function () {
  13935. _this.onVRRequestPresentComplete.notifyObservers(true);
  13936. _this._onVRFullScreenTriggered();
  13937. };
  13938. var onRejected = function () {
  13939. _this.onVRRequestPresentComplete.notifyObservers(false);
  13940. };
  13941. this.onVRRequestPresentStart.notifyObservers(this);
  13942. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  13943. }
  13944. };
  13945. /**
  13946. * Call this function to leave webVR mode
  13947. * Will do nothing if webVR is not supported or if there is no webVR device
  13948. * @see http://doc.babylonjs.com/how_to/webvr_camera
  13949. */
  13950. Engine.prototype.disableVR = function () {
  13951. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  13952. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  13953. }
  13954. };
  13955. Engine.prototype._getVRDisplaysAsync = function () {
  13956. var _this = this;
  13957. return new Promise(function (res, rej) {
  13958. if (navigator.getVRDisplays) {
  13959. navigator.getVRDisplays().then(function (devices) {
  13960. _this._vrSupported = true;
  13961. // note that devices may actually be an empty array. This is fine;
  13962. // we expect this._vrDisplay to be undefined in this case.
  13963. _this._vrDisplay = devices[0];
  13964. res({
  13965. vrDisplay: _this._vrDisplay,
  13966. vrSupported: _this._vrSupported
  13967. });
  13968. });
  13969. }
  13970. else {
  13971. _this._vrDisplay = undefined;
  13972. _this._vrSupported = false;
  13973. res({
  13974. vrDisplay: _this._vrDisplay,
  13975. vrSupported: _this._vrSupported
  13976. });
  13977. }
  13978. });
  13979. };
  13980. /**
  13981. * Binds the frame buffer to the specified texture.
  13982. * @param texture The texture to render to or null for the default canvas
  13983. * @param faceIndex The face of the texture to render to in case of cube texture
  13984. * @param requiredWidth The width of the target to render to
  13985. * @param requiredHeight The height of the target to render to
  13986. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  13987. * @param depthStencilTexture The depth stencil texture to use to render
  13988. * @param lodLevel defines le lod level to bind to the frame buffer
  13989. */
  13990. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture, lodLevel) {
  13991. if (lodLevel === void 0) { lodLevel = 0; }
  13992. if (this._currentRenderTarget) {
  13993. this.unBindFramebuffer(this._currentRenderTarget);
  13994. }
  13995. this._currentRenderTarget = texture;
  13996. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  13997. var gl = this._gl;
  13998. if (texture.isCube) {
  13999. if (faceIndex === undefined) {
  14000. faceIndex = 0;
  14001. }
  14002. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, lodLevel);
  14003. if (depthStencilTexture) {
  14004. if (depthStencilTexture._generateStencilBuffer) {
  14005. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  14006. }
  14007. else {
  14008. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  14009. }
  14010. }
  14011. }
  14012. if (this._cachedViewport && !forceFullscreenViewport) {
  14013. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  14014. }
  14015. else {
  14016. if (!requiredWidth) {
  14017. requiredWidth = texture.width;
  14018. if (lodLevel) {
  14019. requiredWidth = requiredWidth / Math.pow(2, lodLevel);
  14020. }
  14021. }
  14022. if (!requiredHeight) {
  14023. requiredHeight = texture.height;
  14024. if (lodLevel) {
  14025. requiredHeight = requiredHeight / Math.pow(2, lodLevel);
  14026. }
  14027. }
  14028. this._viewport(0, 0, requiredWidth, requiredHeight);
  14029. }
  14030. this.wipeCaches();
  14031. };
  14032. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  14033. if (this._currentFramebuffer !== framebuffer) {
  14034. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  14035. this._currentFramebuffer = framebuffer;
  14036. }
  14037. };
  14038. /**
  14039. * Unbind the current render target texture from the webGL context
  14040. * @param texture defines the render target texture to unbind
  14041. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  14042. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  14043. */
  14044. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  14045. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  14046. this._currentRenderTarget = null;
  14047. // If MSAA, we need to bitblt back to main texture
  14048. var gl = this._gl;
  14049. if (texture._MSAAFramebuffer) {
  14050. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  14051. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  14052. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  14053. }
  14054. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  14055. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14056. gl.generateMipmap(gl.TEXTURE_2D);
  14057. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  14058. }
  14059. if (onBeforeUnbind) {
  14060. if (texture._MSAAFramebuffer) {
  14061. // Bind the correct framebuffer
  14062. this.bindUnboundFramebuffer(texture._framebuffer);
  14063. }
  14064. onBeforeUnbind();
  14065. }
  14066. this.bindUnboundFramebuffer(null);
  14067. };
  14068. /**
  14069. * Unbind a list of render target textures from the webGL context
  14070. * This is used only when drawBuffer extension or webGL2 are active
  14071. * @param textures defines the render target textures to unbind
  14072. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  14073. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  14074. */
  14075. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  14076. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  14077. this._currentRenderTarget = null;
  14078. // If MSAA, we need to bitblt back to main texture
  14079. var gl = this._gl;
  14080. if (textures[0]._MSAAFramebuffer) {
  14081. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  14082. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  14083. var attachments = textures[0]._attachments;
  14084. if (!attachments) {
  14085. attachments = new Array(textures.length);
  14086. textures[0]._attachments = attachments;
  14087. }
  14088. for (var i = 0; i < textures.length; i++) {
  14089. var texture = textures[i];
  14090. for (var j = 0; j < attachments.length; j++) {
  14091. attachments[j] = gl.NONE;
  14092. }
  14093. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  14094. gl.readBuffer(attachments[i]);
  14095. gl.drawBuffers(attachments);
  14096. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  14097. }
  14098. for (var i = 0; i < attachments.length; i++) {
  14099. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  14100. }
  14101. gl.drawBuffers(attachments);
  14102. }
  14103. for (var i = 0; i < textures.length; i++) {
  14104. var texture = textures[i];
  14105. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  14106. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  14107. gl.generateMipmap(gl.TEXTURE_2D);
  14108. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  14109. }
  14110. }
  14111. if (onBeforeUnbind) {
  14112. if (textures[0]._MSAAFramebuffer) {
  14113. // Bind the correct framebuffer
  14114. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  14115. }
  14116. onBeforeUnbind();
  14117. }
  14118. this.bindUnboundFramebuffer(null);
  14119. };
  14120. /**
  14121. * Force the mipmap generation for the given render target texture
  14122. * @param texture defines the render target texture to use
  14123. */
  14124. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  14125. if (texture.generateMipMaps) {
  14126. var gl = this._gl;
  14127. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14128. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  14129. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14130. }
  14131. };
  14132. /**
  14133. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  14134. */
  14135. Engine.prototype.flushFramebuffer = function () {
  14136. this._gl.flush();
  14137. };
  14138. /**
  14139. * Unbind the current render target and bind the default framebuffer
  14140. */
  14141. Engine.prototype.restoreDefaultFramebuffer = function () {
  14142. if (this._currentRenderTarget) {
  14143. this.unBindFramebuffer(this._currentRenderTarget);
  14144. }
  14145. else {
  14146. this.bindUnboundFramebuffer(null);
  14147. }
  14148. if (this._cachedViewport) {
  14149. this.setViewport(this._cachedViewport);
  14150. }
  14151. this.wipeCaches();
  14152. };
  14153. // UBOs
  14154. /**
  14155. * Create an uniform buffer
  14156. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  14157. * @param elements defines the content of the uniform buffer
  14158. * @returns the webGL uniform buffer
  14159. */
  14160. Engine.prototype.createUniformBuffer = function (elements) {
  14161. var ubo = this._gl.createBuffer();
  14162. if (!ubo) {
  14163. throw new Error("Unable to create uniform buffer");
  14164. }
  14165. this.bindUniformBuffer(ubo);
  14166. if (elements instanceof Float32Array) {
  14167. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  14168. }
  14169. else {
  14170. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  14171. }
  14172. this.bindUniformBuffer(null);
  14173. ubo.references = 1;
  14174. return ubo;
  14175. };
  14176. /**
  14177. * Create a dynamic uniform buffer
  14178. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  14179. * @param elements defines the content of the uniform buffer
  14180. * @returns the webGL uniform buffer
  14181. */
  14182. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  14183. var ubo = this._gl.createBuffer();
  14184. if (!ubo) {
  14185. throw new Error("Unable to create dynamic uniform buffer");
  14186. }
  14187. this.bindUniformBuffer(ubo);
  14188. if (elements instanceof Float32Array) {
  14189. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  14190. }
  14191. else {
  14192. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  14193. }
  14194. this.bindUniformBuffer(null);
  14195. ubo.references = 1;
  14196. return ubo;
  14197. };
  14198. /**
  14199. * Update an existing uniform buffer
  14200. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  14201. * @param uniformBuffer defines the target uniform buffer
  14202. * @param elements defines the content to update
  14203. * @param offset defines the offset in the uniform buffer where update should start
  14204. * @param count defines the size of the data to update
  14205. */
  14206. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  14207. this.bindUniformBuffer(uniformBuffer);
  14208. if (offset === undefined) {
  14209. offset = 0;
  14210. }
  14211. if (count === undefined) {
  14212. if (elements instanceof Float32Array) {
  14213. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  14214. }
  14215. else {
  14216. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  14217. }
  14218. }
  14219. else {
  14220. if (elements instanceof Float32Array) {
  14221. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  14222. }
  14223. else {
  14224. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  14225. }
  14226. }
  14227. this.bindUniformBuffer(null);
  14228. };
  14229. // VBOs
  14230. Engine.prototype._resetVertexBufferBinding = function () {
  14231. this.bindArrayBuffer(null);
  14232. this._cachedVertexBuffers = null;
  14233. };
  14234. /**
  14235. * Creates a vertex buffer
  14236. * @param data the data for the vertex buffer
  14237. * @returns the new WebGL static buffer
  14238. */
  14239. Engine.prototype.createVertexBuffer = function (data) {
  14240. var vbo = this._gl.createBuffer();
  14241. if (!vbo) {
  14242. throw new Error("Unable to create vertex buffer");
  14243. }
  14244. this.bindArrayBuffer(vbo);
  14245. if (data instanceof Array) {
  14246. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  14247. }
  14248. else {
  14249. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
  14250. }
  14251. this._resetVertexBufferBinding();
  14252. vbo.references = 1;
  14253. return vbo;
  14254. };
  14255. /**
  14256. * Creates a dynamic vertex buffer
  14257. * @param data the data for the dynamic vertex buffer
  14258. * @returns the new WebGL dynamic buffer
  14259. */
  14260. Engine.prototype.createDynamicVertexBuffer = function (data) {
  14261. var vbo = this._gl.createBuffer();
  14262. if (!vbo) {
  14263. throw new Error("Unable to create dynamic vertex buffer");
  14264. }
  14265. this.bindArrayBuffer(vbo);
  14266. if (data instanceof Array) {
  14267. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  14268. }
  14269. else {
  14270. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
  14271. }
  14272. this._resetVertexBufferBinding();
  14273. vbo.references = 1;
  14274. return vbo;
  14275. };
  14276. /**
  14277. * Update a dynamic index buffer
  14278. * @param indexBuffer defines the target index buffer
  14279. * @param indices defines the data to update
  14280. * @param offset defines the offset in the target index buffer where update should start
  14281. */
  14282. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  14283. if (offset === void 0) { offset = 0; }
  14284. // Force cache update
  14285. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  14286. this.bindIndexBuffer(indexBuffer);
  14287. var arrayBuffer;
  14288. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  14289. arrayBuffer = indices;
  14290. }
  14291. else {
  14292. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  14293. }
  14294. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  14295. this._resetIndexBufferBinding();
  14296. };
  14297. /**
  14298. * Updates a dynamic vertex buffer.
  14299. * @param vertexBuffer the vertex buffer to update
  14300. * @param data the data used to update the vertex buffer
  14301. * @param byteOffset the byte offset of the data
  14302. * @param byteLength the byte length of the data
  14303. */
  14304. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
  14305. this.bindArrayBuffer(vertexBuffer);
  14306. if (byteOffset === undefined) {
  14307. byteOffset = 0;
  14308. }
  14309. if (byteLength === undefined) {
  14310. if (data instanceof Array) {
  14311. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  14312. }
  14313. else {
  14314. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
  14315. }
  14316. }
  14317. else {
  14318. if (data instanceof Array) {
  14319. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  14320. }
  14321. else {
  14322. if (data instanceof ArrayBuffer) {
  14323. data = new Uint8Array(data, byteOffset, byteLength);
  14324. }
  14325. else {
  14326. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  14327. }
  14328. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  14329. }
  14330. }
  14331. this._resetVertexBufferBinding();
  14332. };
  14333. Engine.prototype._resetIndexBufferBinding = function () {
  14334. this.bindIndexBuffer(null);
  14335. this._cachedIndexBuffer = null;
  14336. };
  14337. /**
  14338. * Creates a new index buffer
  14339. * @param indices defines the content of the index buffer
  14340. * @param updatable defines if the index buffer must be updatable
  14341. * @returns a new webGL buffer
  14342. */
  14343. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  14344. var vbo = this._gl.createBuffer();
  14345. if (!vbo) {
  14346. throw new Error("Unable to create index buffer");
  14347. }
  14348. this.bindIndexBuffer(vbo);
  14349. // Check for 32 bits indices
  14350. var arrayBuffer;
  14351. var need32Bits = false;
  14352. if (indices instanceof Uint16Array) {
  14353. arrayBuffer = indices;
  14354. }
  14355. else {
  14356. //check 32 bit support
  14357. if (this._caps.uintIndices) {
  14358. if (indices instanceof Uint32Array) {
  14359. arrayBuffer = indices;
  14360. need32Bits = true;
  14361. }
  14362. else {
  14363. //number[] or Int32Array, check if 32 bit is necessary
  14364. for (var index = 0; index < indices.length; index++) {
  14365. if (indices[index] > 65535) {
  14366. need32Bits = true;
  14367. break;
  14368. }
  14369. }
  14370. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  14371. }
  14372. }
  14373. else {
  14374. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  14375. arrayBuffer = new Uint16Array(indices);
  14376. }
  14377. }
  14378. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  14379. this._resetIndexBufferBinding();
  14380. vbo.references = 1;
  14381. vbo.is32Bits = need32Bits;
  14382. return vbo;
  14383. };
  14384. /**
  14385. * Bind a webGL buffer to the webGL context
  14386. * @param buffer defines the buffer to bind
  14387. */
  14388. Engine.prototype.bindArrayBuffer = function (buffer) {
  14389. if (!this._vaoRecordInProgress) {
  14390. this._unbindVertexArrayObject();
  14391. }
  14392. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  14393. };
  14394. /**
  14395. * Bind an uniform buffer to the current webGL context
  14396. * @param buffer defines the buffer to bind
  14397. */
  14398. Engine.prototype.bindUniformBuffer = function (buffer) {
  14399. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  14400. };
  14401. /**
  14402. * Bind a buffer to the current webGL context at a given location
  14403. * @param buffer defines the buffer to bind
  14404. * @param location defines the index where to bind the buffer
  14405. */
  14406. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  14407. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  14408. };
  14409. /**
  14410. * Bind a specific block at a given index in a specific shader program
  14411. * @param shaderProgram defines the shader program
  14412. * @param blockName defines the block name
  14413. * @param index defines the index where to bind the block
  14414. */
  14415. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  14416. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  14417. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  14418. };
  14419. Engine.prototype.bindIndexBuffer = function (buffer) {
  14420. if (!this._vaoRecordInProgress) {
  14421. this._unbindVertexArrayObject();
  14422. }
  14423. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  14424. };
  14425. Engine.prototype.bindBuffer = function (buffer, target) {
  14426. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  14427. this._gl.bindBuffer(target, buffer);
  14428. this._currentBoundBuffer[target] = buffer;
  14429. }
  14430. };
  14431. /**
  14432. * update the bound buffer with the given data
  14433. * @param data defines the data to update
  14434. */
  14435. Engine.prototype.updateArrayBuffer = function (data) {
  14436. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  14437. };
  14438. Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  14439. var pointer = this._currentBufferPointers[indx];
  14440. var changed = false;
  14441. if (!pointer.active) {
  14442. changed = true;
  14443. pointer.active = true;
  14444. pointer.index = indx;
  14445. pointer.size = size;
  14446. pointer.type = type;
  14447. pointer.normalized = normalized;
  14448. pointer.stride = stride;
  14449. pointer.offset = offset;
  14450. pointer.buffer = buffer;
  14451. }
  14452. else {
  14453. if (pointer.buffer !== buffer) {
  14454. pointer.buffer = buffer;
  14455. changed = true;
  14456. }
  14457. if (pointer.size !== size) {
  14458. pointer.size = size;
  14459. changed = true;
  14460. }
  14461. if (pointer.type !== type) {
  14462. pointer.type = type;
  14463. changed = true;
  14464. }
  14465. if (pointer.normalized !== normalized) {
  14466. pointer.normalized = normalized;
  14467. changed = true;
  14468. }
  14469. if (pointer.stride !== stride) {
  14470. pointer.stride = stride;
  14471. changed = true;
  14472. }
  14473. if (pointer.offset !== offset) {
  14474. pointer.offset = offset;
  14475. changed = true;
  14476. }
  14477. }
  14478. if (changed || this._vaoRecordInProgress) {
  14479. this.bindArrayBuffer(buffer);
  14480. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  14481. }
  14482. };
  14483. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  14484. if (indexBuffer == null) {
  14485. return;
  14486. }
  14487. if (this._cachedIndexBuffer !== indexBuffer) {
  14488. this._cachedIndexBuffer = indexBuffer;
  14489. this.bindIndexBuffer(indexBuffer);
  14490. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  14491. }
  14492. };
  14493. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  14494. var attributes = effect.getAttributesNames();
  14495. if (!this._vaoRecordInProgress) {
  14496. this._unbindVertexArrayObject();
  14497. }
  14498. this.unbindAllAttributes();
  14499. for (var index = 0; index < attributes.length; index++) {
  14500. var order = effect.getAttributeLocation(index);
  14501. if (order >= 0) {
  14502. var vertexBuffer = vertexBuffers[attributes[index]];
  14503. if (!vertexBuffer) {
  14504. continue;
  14505. }
  14506. this._gl.enableVertexAttribArray(order);
  14507. if (!this._vaoRecordInProgress) {
  14508. this._vertexAttribArraysEnabled[order] = true;
  14509. }
  14510. var buffer = vertexBuffer.getBuffer();
  14511. if (buffer) {
  14512. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  14513. if (vertexBuffer.getIsInstanced()) {
  14514. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  14515. if (!this._vaoRecordInProgress) {
  14516. this._currentInstanceLocations.push(order);
  14517. this._currentInstanceBuffers.push(buffer);
  14518. }
  14519. }
  14520. }
  14521. }
  14522. }
  14523. };
  14524. /**
  14525. * Records a vertex array object
  14526. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  14527. * @param vertexBuffers defines the list of vertex buffers to store
  14528. * @param indexBuffer defines the index buffer to store
  14529. * @param effect defines the effect to store
  14530. * @returns the new vertex array object
  14531. */
  14532. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  14533. var vao = this._gl.createVertexArray();
  14534. this._vaoRecordInProgress = true;
  14535. this._gl.bindVertexArray(vao);
  14536. this._mustWipeVertexAttributes = true;
  14537. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  14538. this.bindIndexBuffer(indexBuffer);
  14539. this._vaoRecordInProgress = false;
  14540. this._gl.bindVertexArray(null);
  14541. return vao;
  14542. };
  14543. /**
  14544. * Bind a specific vertex array object
  14545. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  14546. * @param vertexArrayObject defines the vertex array object to bind
  14547. * @param indexBuffer defines the index buffer to bind
  14548. */
  14549. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  14550. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  14551. this._cachedVertexArrayObject = vertexArrayObject;
  14552. this._gl.bindVertexArray(vertexArrayObject);
  14553. this._cachedVertexBuffers = null;
  14554. this._cachedIndexBuffer = null;
  14555. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  14556. this._mustWipeVertexAttributes = true;
  14557. }
  14558. };
  14559. /**
  14560. * Bind webGl buffers directly to the webGL context
  14561. * @param vertexBuffer defines the vertex buffer to bind
  14562. * @param indexBuffer defines the index buffer to bind
  14563. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  14564. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  14565. * @param effect defines the effect associated with the vertex buffer
  14566. */
  14567. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  14568. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  14569. this._cachedVertexBuffers = vertexBuffer;
  14570. this._cachedEffectForVertexBuffers = effect;
  14571. var attributesCount = effect.getAttributesCount();
  14572. this._unbindVertexArrayObject();
  14573. this.unbindAllAttributes();
  14574. var offset = 0;
  14575. for (var index = 0; index < attributesCount; index++) {
  14576. if (index < vertexDeclaration.length) {
  14577. var order = effect.getAttributeLocation(index);
  14578. if (order >= 0) {
  14579. this._gl.enableVertexAttribArray(order);
  14580. this._vertexAttribArraysEnabled[order] = true;
  14581. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  14582. }
  14583. offset += vertexDeclaration[index] * 4;
  14584. }
  14585. }
  14586. }
  14587. this._bindIndexBufferWithCache(indexBuffer);
  14588. };
  14589. Engine.prototype._unbindVertexArrayObject = function () {
  14590. if (!this._cachedVertexArrayObject) {
  14591. return;
  14592. }
  14593. this._cachedVertexArrayObject = null;
  14594. this._gl.bindVertexArray(null);
  14595. };
  14596. /**
  14597. * Bind a list of vertex buffers to the webGL context
  14598. * @param vertexBuffers defines the list of vertex buffers to bind
  14599. * @param indexBuffer defines the index buffer to bind
  14600. * @param effect defines the effect associated with the vertex buffers
  14601. */
  14602. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  14603. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  14604. this._cachedVertexBuffers = vertexBuffers;
  14605. this._cachedEffectForVertexBuffers = effect;
  14606. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  14607. }
  14608. this._bindIndexBufferWithCache(indexBuffer);
  14609. };
  14610. /**
  14611. * Unbind all instance attributes
  14612. */
  14613. Engine.prototype.unbindInstanceAttributes = function () {
  14614. var boundBuffer;
  14615. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  14616. var instancesBuffer = this._currentInstanceBuffers[i];
  14617. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  14618. boundBuffer = instancesBuffer;
  14619. this.bindArrayBuffer(instancesBuffer);
  14620. }
  14621. var offsetLocation = this._currentInstanceLocations[i];
  14622. this._gl.vertexAttribDivisor(offsetLocation, 0);
  14623. }
  14624. this._currentInstanceBuffers.length = 0;
  14625. this._currentInstanceLocations.length = 0;
  14626. };
  14627. /**
  14628. * Release and free the memory of a vertex array object
  14629. * @param vao defines the vertex array object to delete
  14630. */
  14631. Engine.prototype.releaseVertexArrayObject = function (vao) {
  14632. this._gl.deleteVertexArray(vao);
  14633. };
  14634. /** @hidden */
  14635. Engine.prototype._releaseBuffer = function (buffer) {
  14636. buffer.references--;
  14637. if (buffer.references === 0) {
  14638. this._gl.deleteBuffer(buffer);
  14639. return true;
  14640. }
  14641. return false;
  14642. };
  14643. /**
  14644. * Creates a webGL buffer to use with instanciation
  14645. * @param capacity defines the size of the buffer
  14646. * @returns the webGL buffer
  14647. */
  14648. Engine.prototype.createInstancesBuffer = function (capacity) {
  14649. var buffer = this._gl.createBuffer();
  14650. if (!buffer) {
  14651. throw new Error("Unable to create instance buffer");
  14652. }
  14653. buffer.capacity = capacity;
  14654. this.bindArrayBuffer(buffer);
  14655. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  14656. return buffer;
  14657. };
  14658. /**
  14659. * Delete a webGL buffer used with instanciation
  14660. * @param buffer defines the webGL buffer to delete
  14661. */
  14662. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  14663. this._gl.deleteBuffer(buffer);
  14664. };
  14665. /**
  14666. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  14667. * @param instancesBuffer defines the webGL buffer to update and bind
  14668. * @param data defines the data to store in the buffer
  14669. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  14670. */
  14671. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  14672. this.bindArrayBuffer(instancesBuffer);
  14673. if (data) {
  14674. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  14675. }
  14676. if (offsetLocations[0].index !== undefined) {
  14677. var stride = 0;
  14678. for (var i = 0; i < offsetLocations.length; i++) {
  14679. var ai = offsetLocations[i];
  14680. stride += ai.attributeSize * 4;
  14681. }
  14682. for (var i = 0; i < offsetLocations.length; i++) {
  14683. var ai = offsetLocations[i];
  14684. if (!this._vertexAttribArraysEnabled[ai.index]) {
  14685. this._gl.enableVertexAttribArray(ai.index);
  14686. this._vertexAttribArraysEnabled[ai.index] = true;
  14687. }
  14688. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  14689. this._gl.vertexAttribDivisor(ai.index, 1);
  14690. this._currentInstanceLocations.push(ai.index);
  14691. this._currentInstanceBuffers.push(instancesBuffer);
  14692. }
  14693. }
  14694. else {
  14695. for (var index = 0; index < 4; index++) {
  14696. var offsetLocation = offsetLocations[index];
  14697. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  14698. this._gl.enableVertexAttribArray(offsetLocation);
  14699. this._vertexAttribArraysEnabled[offsetLocation] = true;
  14700. }
  14701. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  14702. this._gl.vertexAttribDivisor(offsetLocation, 1);
  14703. this._currentInstanceLocations.push(offsetLocation);
  14704. this._currentInstanceBuffers.push(instancesBuffer);
  14705. }
  14706. }
  14707. };
  14708. /**
  14709. * Apply all cached states (depth, culling, stencil and alpha)
  14710. */
  14711. Engine.prototype.applyStates = function () {
  14712. this._depthCullingState.apply(this._gl);
  14713. this._stencilState.apply(this._gl);
  14714. this._alphaState.apply(this._gl);
  14715. };
  14716. /**
  14717. * Send a draw order
  14718. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  14719. * @param indexStart defines the starting index
  14720. * @param indexCount defines the number of index to draw
  14721. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  14722. */
  14723. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  14724. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  14725. };
  14726. /**
  14727. * Draw a list of points
  14728. * @param verticesStart defines the index of first vertex to draw
  14729. * @param verticesCount defines the count of vertices to draw
  14730. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  14731. */
  14732. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  14733. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  14734. };
  14735. /**
  14736. * Draw a list of unindexed primitives
  14737. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  14738. * @param verticesStart defines the index of first vertex to draw
  14739. * @param verticesCount defines the count of vertices to draw
  14740. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  14741. */
  14742. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  14743. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  14744. };
  14745. /**
  14746. * Draw a list of indexed primitives
  14747. * @param fillMode defines the primitive to use
  14748. * @param indexStart defines the starting index
  14749. * @param indexCount defines the number of index to draw
  14750. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  14751. */
  14752. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  14753. // Apply states
  14754. this.applyStates();
  14755. this._drawCalls.addCount(1, false);
  14756. // Render
  14757. var drawMode = this._drawMode(fillMode);
  14758. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  14759. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  14760. if (instancesCount) {
  14761. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  14762. }
  14763. else {
  14764. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  14765. }
  14766. };
  14767. /**
  14768. * Draw a list of unindexed primitives
  14769. * @param fillMode defines the primitive to use
  14770. * @param verticesStart defines the index of first vertex to draw
  14771. * @param verticesCount defines the count of vertices to draw
  14772. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  14773. */
  14774. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  14775. // Apply states
  14776. this.applyStates();
  14777. this._drawCalls.addCount(1, false);
  14778. var drawMode = this._drawMode(fillMode);
  14779. if (instancesCount) {
  14780. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  14781. }
  14782. else {
  14783. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  14784. }
  14785. };
  14786. Engine.prototype._drawMode = function (fillMode) {
  14787. switch (fillMode) {
  14788. // Triangle views
  14789. case BABYLON.Material.TriangleFillMode:
  14790. return this._gl.TRIANGLES;
  14791. case BABYLON.Material.PointFillMode:
  14792. return this._gl.POINTS;
  14793. case BABYLON.Material.WireFrameFillMode:
  14794. return this._gl.LINES;
  14795. // Draw modes
  14796. case BABYLON.Material.PointListDrawMode:
  14797. return this._gl.POINTS;
  14798. case BABYLON.Material.LineListDrawMode:
  14799. return this._gl.LINES;
  14800. case BABYLON.Material.LineLoopDrawMode:
  14801. return this._gl.LINE_LOOP;
  14802. case BABYLON.Material.LineStripDrawMode:
  14803. return this._gl.LINE_STRIP;
  14804. case BABYLON.Material.TriangleStripDrawMode:
  14805. return this._gl.TRIANGLE_STRIP;
  14806. case BABYLON.Material.TriangleFanDrawMode:
  14807. return this._gl.TRIANGLE_FAN;
  14808. default:
  14809. return this._gl.TRIANGLES;
  14810. }
  14811. };
  14812. // Shaders
  14813. /** @hidden */
  14814. Engine.prototype._releaseEffect = function (effect) {
  14815. if (this._compiledEffects[effect._key]) {
  14816. delete this._compiledEffects[effect._key];
  14817. this._deleteProgram(effect.getProgram());
  14818. }
  14819. };
  14820. /** @hidden */
  14821. Engine.prototype._deleteProgram = function (program) {
  14822. if (program) {
  14823. program.__SPECTOR_rebuildProgram = null;
  14824. if (program.transformFeedback) {
  14825. this.deleteTransformFeedback(program.transformFeedback);
  14826. program.transformFeedback = null;
  14827. }
  14828. this._gl.deleteProgram(program);
  14829. }
  14830. };
  14831. /**
  14832. * Create a new effect (used to store vertex/fragment shaders)
  14833. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  14834. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  14835. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  14836. * @param samplers defines an array of string used to represent textures
  14837. * @param defines defines the string containing the defines to use to compile the shaders
  14838. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  14839. * @param onCompiled defines a function to call when the effect creation is successful
  14840. * @param onError defines a function to call when the effect creation has failed
  14841. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  14842. * @returns the new Effect
  14843. */
  14844. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  14845. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  14846. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  14847. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  14848. if (this._compiledEffects[name]) {
  14849. var compiledEffect = this._compiledEffects[name];
  14850. if (onCompiled && compiledEffect.isReady()) {
  14851. onCompiled(compiledEffect);
  14852. }
  14853. return compiledEffect;
  14854. }
  14855. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  14856. effect._key = name;
  14857. this._compiledEffects[name] = effect;
  14858. return effect;
  14859. };
  14860. Engine.prototype._compileShader = function (source, type, defines, shaderVersion) {
  14861. return this._compileRawShader(shaderVersion + (defines ? defines + "\n" : "") + source, type);
  14862. };
  14863. Engine.prototype._compileRawShader = function (source, type) {
  14864. var gl = this._gl;
  14865. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  14866. if (!shader) {
  14867. throw new Error("Something went wrong while compile the shader.");
  14868. }
  14869. gl.shaderSource(shader, source);
  14870. gl.compileShader(shader);
  14871. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  14872. var log = gl.getShaderInfoLog(shader);
  14873. if (log) {
  14874. throw new Error(log);
  14875. }
  14876. }
  14877. return shader;
  14878. };
  14879. /**
  14880. * Directly creates a webGL program
  14881. * @param vertexCode defines the vertex shader code to use
  14882. * @param fragmentCode defines the fragment shader code to use
  14883. * @param context defines the webGL context to use (if not set, the current one will be used)
  14884. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  14885. * @returns the new webGL program
  14886. */
  14887. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  14888. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  14889. context = context || this._gl;
  14890. var vertexShader = this._compileRawShader(vertexCode, "vertex");
  14891. var fragmentShader = this._compileRawShader(fragmentCode, "fragment");
  14892. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  14893. };
  14894. /**
  14895. * Creates a webGL program
  14896. * @param vertexCode defines the vertex shader code to use
  14897. * @param fragmentCode defines the fragment shader code to use
  14898. * @param defines defines the string containing the defines to use to compile the shaders
  14899. * @param context defines the webGL context to use (if not set, the current one will be used)
  14900. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  14901. * @returns the new webGL program
  14902. */
  14903. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  14904. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  14905. context = context || this._gl;
  14906. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  14907. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  14908. var vertexShader = this._compileShader(vertexCode, "vertex", defines, shaderVersion);
  14909. var fragmentShader = this._compileShader(fragmentCode, "fragment", defines, shaderVersion);
  14910. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  14911. this.onAfterShaderCompilationObservable.notifyObservers(this);
  14912. return program;
  14913. };
  14914. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  14915. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  14916. var shaderProgram = context.createProgram();
  14917. if (!shaderProgram) {
  14918. throw new Error("Unable to create program");
  14919. }
  14920. context.attachShader(shaderProgram, vertexShader);
  14921. context.attachShader(shaderProgram, fragmentShader);
  14922. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  14923. var transformFeedback = this.createTransformFeedback();
  14924. this.bindTransformFeedback(transformFeedback);
  14925. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  14926. shaderProgram.transformFeedback = transformFeedback;
  14927. }
  14928. context.linkProgram(shaderProgram);
  14929. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  14930. this.bindTransformFeedback(null);
  14931. }
  14932. shaderProgram.context = context;
  14933. shaderProgram.vertexShader = vertexShader;
  14934. shaderProgram.fragmentShader = fragmentShader;
  14935. if (!this._caps.parallelShaderCompile) {
  14936. this._finalizeProgram(shaderProgram);
  14937. }
  14938. else {
  14939. shaderProgram.isParallelCompiled = true;
  14940. }
  14941. return shaderProgram;
  14942. };
  14943. Engine.prototype._finalizeProgram = function (shaderProgram) {
  14944. var context = shaderProgram.context;
  14945. var vertexShader = shaderProgram.vertexShader;
  14946. var fragmentShader = shaderProgram.fragmentShader;
  14947. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  14948. if (!linked) {
  14949. var error = context.getProgramInfoLog(shaderProgram);
  14950. if (error) {
  14951. throw new Error(error);
  14952. }
  14953. }
  14954. if (this.validateShaderPrograms) {
  14955. context.validateProgram(shaderProgram);
  14956. var validated = context.getProgramParameter(shaderProgram, context.VALIDATE_STATUS);
  14957. if (!validated) {
  14958. var error = context.getProgramInfoLog(shaderProgram);
  14959. if (error) {
  14960. throw new Error(error);
  14961. }
  14962. }
  14963. }
  14964. context.deleteShader(vertexShader);
  14965. context.deleteShader(fragmentShader);
  14966. shaderProgram.context = undefined;
  14967. shaderProgram.vertexShader = undefined;
  14968. shaderProgram.fragmentShader = undefined;
  14969. if (shaderProgram.onCompiled) {
  14970. shaderProgram.onCompiled();
  14971. shaderProgram.onCompiled = undefined;
  14972. }
  14973. };
  14974. /** @hidden */
  14975. Engine.prototype._isProgramCompiled = function (shaderProgram) {
  14976. if (!shaderProgram.isParallelCompiled) {
  14977. return true;
  14978. }
  14979. if (this._gl.getProgramParameter(shaderProgram, this._caps.parallelShaderCompile.COMPLETION_STATUS_KHR)) {
  14980. this._finalizeProgram(shaderProgram);
  14981. return true;
  14982. }
  14983. return false;
  14984. };
  14985. /** @hidden */
  14986. Engine.prototype._executeWhenProgramIsCompiled = function (shaderProgram, action) {
  14987. if (!shaderProgram.isParallelCompiled) {
  14988. action();
  14989. return;
  14990. }
  14991. shaderProgram.onCompiled = action;
  14992. };
  14993. /**
  14994. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  14995. * @param shaderProgram defines the webGL program to use
  14996. * @param uniformsNames defines the list of uniform names
  14997. * @returns an array of webGL uniform locations
  14998. */
  14999. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  15000. var results = new Array();
  15001. for (var index = 0; index < uniformsNames.length; index++) {
  15002. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  15003. }
  15004. return results;
  15005. };
  15006. /**
  15007. * Gets the lsit of active attributes for a given webGL program
  15008. * @param shaderProgram defines the webGL program to use
  15009. * @param attributesNames defines the list of attribute names to get
  15010. * @returns an array of indices indicating the offset of each attribute
  15011. */
  15012. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  15013. var results = [];
  15014. for (var index = 0; index < attributesNames.length; index++) {
  15015. try {
  15016. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  15017. }
  15018. catch (e) {
  15019. results.push(-1);
  15020. }
  15021. }
  15022. return results;
  15023. };
  15024. /**
  15025. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  15026. * @param effect defines the effect to activate
  15027. */
  15028. Engine.prototype.enableEffect = function (effect) {
  15029. if (!effect || effect === this._currentEffect) {
  15030. return;
  15031. }
  15032. // Use program
  15033. this.bindSamplers(effect);
  15034. this._currentEffect = effect;
  15035. if (effect.onBind) {
  15036. effect.onBind(effect);
  15037. }
  15038. if (effect._onBindObservable) {
  15039. effect._onBindObservable.notifyObservers(effect);
  15040. }
  15041. };
  15042. /**
  15043. * Set the value of an uniform to an array of int32
  15044. * @param uniform defines the webGL uniform location where to store the value
  15045. * @param array defines the array of int32 to store
  15046. */
  15047. Engine.prototype.setIntArray = function (uniform, array) {
  15048. if (!uniform) {
  15049. return;
  15050. }
  15051. this._gl.uniform1iv(uniform, array);
  15052. };
  15053. /**
  15054. * Set the value of an uniform to an array of int32 (stored as vec2)
  15055. * @param uniform defines the webGL uniform location where to store the value
  15056. * @param array defines the array of int32 to store
  15057. */
  15058. Engine.prototype.setIntArray2 = function (uniform, array) {
  15059. if (!uniform || array.length % 2 !== 0) {
  15060. return;
  15061. }
  15062. this._gl.uniform2iv(uniform, array);
  15063. };
  15064. /**
  15065. * Set the value of an uniform to an array of int32 (stored as vec3)
  15066. * @param uniform defines the webGL uniform location where to store the value
  15067. * @param array defines the array of int32 to store
  15068. */
  15069. Engine.prototype.setIntArray3 = function (uniform, array) {
  15070. if (!uniform || array.length % 3 !== 0) {
  15071. return;
  15072. }
  15073. this._gl.uniform3iv(uniform, array);
  15074. };
  15075. /**
  15076. * Set the value of an uniform to an array of int32 (stored as vec4)
  15077. * @param uniform defines the webGL uniform location where to store the value
  15078. * @param array defines the array of int32 to store
  15079. */
  15080. Engine.prototype.setIntArray4 = function (uniform, array) {
  15081. if (!uniform || array.length % 4 !== 0) {
  15082. return;
  15083. }
  15084. this._gl.uniform4iv(uniform, array);
  15085. };
  15086. /**
  15087. * Set the value of an uniform to an array of float32
  15088. * @param uniform defines the webGL uniform location where to store the value
  15089. * @param array defines the array of float32 to store
  15090. */
  15091. Engine.prototype.setFloatArray = function (uniform, array) {
  15092. if (!uniform) {
  15093. return;
  15094. }
  15095. this._gl.uniform1fv(uniform, array);
  15096. };
  15097. /**
  15098. * Set the value of an uniform to an array of float32 (stored as vec2)
  15099. * @param uniform defines the webGL uniform location where to store the value
  15100. * @param array defines the array of float32 to store
  15101. */
  15102. Engine.prototype.setFloatArray2 = function (uniform, array) {
  15103. if (!uniform || array.length % 2 !== 0) {
  15104. return;
  15105. }
  15106. this._gl.uniform2fv(uniform, array);
  15107. };
  15108. /**
  15109. * Set the value of an uniform to an array of float32 (stored as vec3)
  15110. * @param uniform defines the webGL uniform location where to store the value
  15111. * @param array defines the array of float32 to store
  15112. */
  15113. Engine.prototype.setFloatArray3 = function (uniform, array) {
  15114. if (!uniform || array.length % 3 !== 0) {
  15115. return;
  15116. }
  15117. this._gl.uniform3fv(uniform, array);
  15118. };
  15119. /**
  15120. * Set the value of an uniform to an array of float32 (stored as vec4)
  15121. * @param uniform defines the webGL uniform location where to store the value
  15122. * @param array defines the array of float32 to store
  15123. */
  15124. Engine.prototype.setFloatArray4 = function (uniform, array) {
  15125. if (!uniform || array.length % 4 !== 0) {
  15126. return;
  15127. }
  15128. this._gl.uniform4fv(uniform, array);
  15129. };
  15130. /**
  15131. * Set the value of an uniform to an array of number
  15132. * @param uniform defines the webGL uniform location where to store the value
  15133. * @param array defines the array of number to store
  15134. */
  15135. Engine.prototype.setArray = function (uniform, array) {
  15136. if (!uniform) {
  15137. return;
  15138. }
  15139. this._gl.uniform1fv(uniform, array);
  15140. };
  15141. /**
  15142. * Set the value of an uniform to an array of number (stored as vec2)
  15143. * @param uniform defines the webGL uniform location where to store the value
  15144. * @param array defines the array of number to store
  15145. */
  15146. Engine.prototype.setArray2 = function (uniform, array) {
  15147. if (!uniform || array.length % 2 !== 0) {
  15148. return;
  15149. }
  15150. this._gl.uniform2fv(uniform, array);
  15151. };
  15152. /**
  15153. * Set the value of an uniform to an array of number (stored as vec3)
  15154. * @param uniform defines the webGL uniform location where to store the value
  15155. * @param array defines the array of number to store
  15156. */
  15157. Engine.prototype.setArray3 = function (uniform, array) {
  15158. if (!uniform || array.length % 3 !== 0) {
  15159. return;
  15160. }
  15161. this._gl.uniform3fv(uniform, array);
  15162. };
  15163. /**
  15164. * Set the value of an uniform to an array of number (stored as vec4)
  15165. * @param uniform defines the webGL uniform location where to store the value
  15166. * @param array defines the array of number to store
  15167. */
  15168. Engine.prototype.setArray4 = function (uniform, array) {
  15169. if (!uniform || array.length % 4 !== 0) {
  15170. return;
  15171. }
  15172. this._gl.uniform4fv(uniform, array);
  15173. };
  15174. /**
  15175. * Set the value of an uniform to an array of float32 (stored as matrices)
  15176. * @param uniform defines the webGL uniform location where to store the value
  15177. * @param matrices defines the array of float32 to store
  15178. */
  15179. Engine.prototype.setMatrices = function (uniform, matrices) {
  15180. if (!uniform) {
  15181. return;
  15182. }
  15183. this._gl.uniformMatrix4fv(uniform, false, matrices);
  15184. };
  15185. /**
  15186. * Set the value of an uniform to a matrix
  15187. * @param uniform defines the webGL uniform location where to store the value
  15188. * @param matrix defines the matrix to store
  15189. */
  15190. Engine.prototype.setMatrix = function (uniform, matrix) {
  15191. if (!uniform) {
  15192. return;
  15193. }
  15194. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  15195. };
  15196. /**
  15197. * Set the value of an uniform to a matrix (3x3)
  15198. * @param uniform defines the webGL uniform location where to store the value
  15199. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  15200. */
  15201. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  15202. if (!uniform) {
  15203. return;
  15204. }
  15205. this._gl.uniformMatrix3fv(uniform, false, matrix);
  15206. };
  15207. /**
  15208. * Set the value of an uniform to a matrix (2x2)
  15209. * @param uniform defines the webGL uniform location where to store the value
  15210. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  15211. */
  15212. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  15213. if (!uniform) {
  15214. return;
  15215. }
  15216. this._gl.uniformMatrix2fv(uniform, false, matrix);
  15217. };
  15218. /**
  15219. * Set the value of an uniform to a number (int)
  15220. * @param uniform defines the webGL uniform location where to store the value
  15221. * @param value defines the int number to store
  15222. */
  15223. Engine.prototype.setInt = function (uniform, value) {
  15224. if (!uniform) {
  15225. return;
  15226. }
  15227. this._gl.uniform1i(uniform, value);
  15228. };
  15229. /**
  15230. * Set the value of an uniform to a number (float)
  15231. * @param uniform defines the webGL uniform location where to store the value
  15232. * @param value defines the float number to store
  15233. */
  15234. Engine.prototype.setFloat = function (uniform, value) {
  15235. if (!uniform) {
  15236. return;
  15237. }
  15238. this._gl.uniform1f(uniform, value);
  15239. };
  15240. /**
  15241. * Set the value of an uniform to a vec2
  15242. * @param uniform defines the webGL uniform location where to store the value
  15243. * @param x defines the 1st component of the value
  15244. * @param y defines the 2nd component of the value
  15245. */
  15246. Engine.prototype.setFloat2 = function (uniform, x, y) {
  15247. if (!uniform) {
  15248. return;
  15249. }
  15250. this._gl.uniform2f(uniform, x, y);
  15251. };
  15252. /**
  15253. * Set the value of an uniform to a vec3
  15254. * @param uniform defines the webGL uniform location where to store the value
  15255. * @param x defines the 1st component of the value
  15256. * @param y defines the 2nd component of the value
  15257. * @param z defines the 3rd component of the value
  15258. */
  15259. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  15260. if (!uniform) {
  15261. return;
  15262. }
  15263. this._gl.uniform3f(uniform, x, y, z);
  15264. };
  15265. /**
  15266. * Set the value of an uniform to a boolean
  15267. * @param uniform defines the webGL uniform location where to store the value
  15268. * @param bool defines the boolean to store
  15269. */
  15270. Engine.prototype.setBool = function (uniform, bool) {
  15271. if (!uniform) {
  15272. return;
  15273. }
  15274. this._gl.uniform1i(uniform, bool);
  15275. };
  15276. /**
  15277. * Set the value of an uniform to a vec4
  15278. * @param uniform defines the webGL uniform location where to store the value
  15279. * @param x defines the 1st component of the value
  15280. * @param y defines the 2nd component of the value
  15281. * @param z defines the 3rd component of the value
  15282. * @param w defines the 4th component of the value
  15283. */
  15284. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  15285. if (!uniform) {
  15286. return;
  15287. }
  15288. this._gl.uniform4f(uniform, x, y, z, w);
  15289. };
  15290. /**
  15291. * Set the value of an uniform to a Color3
  15292. * @param uniform defines the webGL uniform location where to store the value
  15293. * @param color3 defines the color to store
  15294. */
  15295. Engine.prototype.setColor3 = function (uniform, color3) {
  15296. if (!uniform) {
  15297. return;
  15298. }
  15299. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  15300. };
  15301. /**
  15302. * Set the value of an uniform to a Color3 and an alpha value
  15303. * @param uniform defines the webGL uniform location where to store the value
  15304. * @param color3 defines the color to store
  15305. * @param alpha defines the alpha component to store
  15306. */
  15307. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  15308. if (!uniform) {
  15309. return;
  15310. }
  15311. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  15312. };
  15313. /**
  15314. * Sets a Color4 on a uniform variable
  15315. * @param uniform defines the uniform location
  15316. * @param color4 defines the value to be set
  15317. */
  15318. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  15319. if (!uniform) {
  15320. return;
  15321. }
  15322. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  15323. };
  15324. // States
  15325. /**
  15326. * Set various states to the webGL context
  15327. * @param culling defines backface culling state
  15328. * @param zOffset defines the value to apply to zOffset (0 by default)
  15329. * @param force defines if states must be applied even if cache is up to date
  15330. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  15331. */
  15332. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  15333. if (zOffset === void 0) { zOffset = 0; }
  15334. if (reverseSide === void 0) { reverseSide = false; }
  15335. // Culling
  15336. if (this._depthCullingState.cull !== culling || force) {
  15337. this._depthCullingState.cull = culling;
  15338. }
  15339. // Cull face
  15340. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  15341. if (this._depthCullingState.cullFace !== cullFace || force) {
  15342. this._depthCullingState.cullFace = cullFace;
  15343. }
  15344. // Z offset
  15345. this.setZOffset(zOffset);
  15346. // Front face
  15347. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  15348. if (this._depthCullingState.frontFace !== frontFace || force) {
  15349. this._depthCullingState.frontFace = frontFace;
  15350. }
  15351. };
  15352. /**
  15353. * Set the z offset to apply to current rendering
  15354. * @param value defines the offset to apply
  15355. */
  15356. Engine.prototype.setZOffset = function (value) {
  15357. this._depthCullingState.zOffset = value;
  15358. };
  15359. /**
  15360. * Gets the current value of the zOffset
  15361. * @returns the current zOffset state
  15362. */
  15363. Engine.prototype.getZOffset = function () {
  15364. return this._depthCullingState.zOffset;
  15365. };
  15366. /**
  15367. * Enable or disable depth buffering
  15368. * @param enable defines the state to set
  15369. */
  15370. Engine.prototype.setDepthBuffer = function (enable) {
  15371. this._depthCullingState.depthTest = enable;
  15372. };
  15373. /**
  15374. * Gets a boolean indicating if depth writing is enabled
  15375. * @returns the current depth writing state
  15376. */
  15377. Engine.prototype.getDepthWrite = function () {
  15378. return this._depthCullingState.depthMask;
  15379. };
  15380. /**
  15381. * Enable or disable depth writing
  15382. * @param enable defines the state to set
  15383. */
  15384. Engine.prototype.setDepthWrite = function (enable) {
  15385. this._depthCullingState.depthMask = enable;
  15386. };
  15387. /**
  15388. * Enable or disable color writing
  15389. * @param enable defines the state to set
  15390. */
  15391. Engine.prototype.setColorWrite = function (enable) {
  15392. this._gl.colorMask(enable, enable, enable, enable);
  15393. this._colorWrite = enable;
  15394. };
  15395. /**
  15396. * Gets a boolean indicating if color writing is enabled
  15397. * @returns the current color writing state
  15398. */
  15399. Engine.prototype.getColorWrite = function () {
  15400. return this._colorWrite;
  15401. };
  15402. /**
  15403. * Sets alpha constants used by some alpha blending modes
  15404. * @param r defines the red component
  15405. * @param g defines the green component
  15406. * @param b defines the blue component
  15407. * @param a defines the alpha component
  15408. */
  15409. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  15410. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  15411. };
  15412. /**
  15413. * Sets the current alpha mode
  15414. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  15415. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  15416. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  15417. */
  15418. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  15419. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  15420. if (this._alphaMode === mode) {
  15421. return;
  15422. }
  15423. switch (mode) {
  15424. case Engine.ALPHA_DISABLE:
  15425. this._alphaState.alphaBlend = false;
  15426. break;
  15427. case Engine.ALPHA_PREMULTIPLIED:
  15428. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  15429. this._alphaState.alphaBlend = true;
  15430. break;
  15431. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  15432. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  15433. this._alphaState.alphaBlend = true;
  15434. break;
  15435. case Engine.ALPHA_COMBINE:
  15436. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  15437. this._alphaState.alphaBlend = true;
  15438. break;
  15439. case Engine.ALPHA_ONEONE:
  15440. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  15441. this._alphaState.alphaBlend = true;
  15442. break;
  15443. case Engine.ALPHA_ADD:
  15444. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  15445. this._alphaState.alphaBlend = true;
  15446. break;
  15447. case Engine.ALPHA_SUBTRACT:
  15448. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  15449. this._alphaState.alphaBlend = true;
  15450. break;
  15451. case Engine.ALPHA_MULTIPLY:
  15452. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  15453. this._alphaState.alphaBlend = true;
  15454. break;
  15455. case Engine.ALPHA_MAXIMIZED:
  15456. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  15457. this._alphaState.alphaBlend = true;
  15458. break;
  15459. case Engine.ALPHA_INTERPOLATE:
  15460. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  15461. this._alphaState.alphaBlend = true;
  15462. break;
  15463. case Engine.ALPHA_SCREENMODE:
  15464. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  15465. this._alphaState.alphaBlend = true;
  15466. break;
  15467. }
  15468. if (!noDepthWriteChange) {
  15469. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  15470. }
  15471. this._alphaMode = mode;
  15472. };
  15473. /**
  15474. * Gets the current alpha mode
  15475. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  15476. * @returns the current alpha mode
  15477. */
  15478. Engine.prototype.getAlphaMode = function () {
  15479. return this._alphaMode;
  15480. };
  15481. // Textures
  15482. /**
  15483. * Clears the list of texture accessible through engine.
  15484. * This can help preventing texture load conflict due to name collision.
  15485. */
  15486. Engine.prototype.clearInternalTexturesCache = function () {
  15487. this._internalTexturesCache = [];
  15488. };
  15489. /**
  15490. * Force the entire cache to be cleared
  15491. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  15492. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  15493. */
  15494. Engine.prototype.wipeCaches = function (bruteForce) {
  15495. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  15496. return;
  15497. }
  15498. this._currentEffect = null;
  15499. this._viewportCached.x = 0;
  15500. this._viewportCached.y = 0;
  15501. this._viewportCached.z = 0;
  15502. this._viewportCached.w = 0;
  15503. if (bruteForce) {
  15504. this.resetTextureCache();
  15505. this._currentProgram = null;
  15506. this._stencilState.reset();
  15507. this._depthCullingState.reset();
  15508. this.setDepthFunctionToLessOrEqual();
  15509. this._alphaState.reset();
  15510. this._unpackFlipYCached = null;
  15511. }
  15512. this._resetVertexBufferBinding();
  15513. this._cachedIndexBuffer = null;
  15514. this._cachedEffectForVertexBuffers = null;
  15515. this._unbindVertexArrayObject();
  15516. this.bindIndexBuffer(null);
  15517. };
  15518. /**
  15519. * Set the compressed texture format to use, based on the formats you have, and the formats
  15520. * supported by the hardware / browser.
  15521. *
  15522. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  15523. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  15524. * to API arguments needed to compressed textures. This puts the burden on the container
  15525. * generator to house the arcane code for determining these for current & future formats.
  15526. *
  15527. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  15528. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  15529. *
  15530. * Note: The result of this call is not taken into account when a texture is base64.
  15531. *
  15532. * @param formatsAvailable defines the list of those format families you have created
  15533. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  15534. *
  15535. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  15536. * @returns The extension selected.
  15537. */
  15538. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  15539. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  15540. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  15541. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  15542. return this._textureFormatInUse = this._texturesSupported[i];
  15543. }
  15544. }
  15545. }
  15546. // actively set format to nothing, to allow this to be called more than once
  15547. // and possibly fail the 2nd time
  15548. this._textureFormatInUse = null;
  15549. return null;
  15550. };
  15551. Engine.prototype._getSamplingParameters = function (samplingMode, generateMipMaps) {
  15552. var gl = this._gl;
  15553. var magFilter = gl.NEAREST;
  15554. var minFilter = gl.NEAREST;
  15555. switch (samplingMode) {
  15556. case Engine.TEXTURE_BILINEAR_SAMPLINGMODE:
  15557. magFilter = gl.LINEAR;
  15558. if (generateMipMaps) {
  15559. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  15560. }
  15561. else {
  15562. minFilter = gl.LINEAR;
  15563. }
  15564. break;
  15565. case Engine.TEXTURE_TRILINEAR_SAMPLINGMODE:
  15566. magFilter = gl.LINEAR;
  15567. if (generateMipMaps) {
  15568. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  15569. }
  15570. else {
  15571. minFilter = gl.LINEAR;
  15572. }
  15573. break;
  15574. case Engine.TEXTURE_NEAREST_SAMPLINGMODE:
  15575. magFilter = gl.NEAREST;
  15576. if (generateMipMaps) {
  15577. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  15578. }
  15579. else {
  15580. minFilter = gl.NEAREST;
  15581. }
  15582. break;
  15583. case Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST:
  15584. magFilter = gl.NEAREST;
  15585. if (generateMipMaps) {
  15586. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  15587. }
  15588. else {
  15589. minFilter = gl.NEAREST;
  15590. }
  15591. break;
  15592. case Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST:
  15593. magFilter = gl.NEAREST;
  15594. if (generateMipMaps) {
  15595. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  15596. }
  15597. else {
  15598. minFilter = gl.LINEAR;
  15599. }
  15600. break;
  15601. case Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR:
  15602. magFilter = gl.NEAREST;
  15603. if (generateMipMaps) {
  15604. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  15605. }
  15606. else {
  15607. minFilter = gl.LINEAR;
  15608. }
  15609. break;
  15610. case Engine.TEXTURE_NEAREST_LINEAR:
  15611. magFilter = gl.NEAREST;
  15612. minFilter = gl.LINEAR;
  15613. break;
  15614. case Engine.TEXTURE_NEAREST_NEAREST:
  15615. magFilter = gl.NEAREST;
  15616. minFilter = gl.NEAREST;
  15617. break;
  15618. case Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST:
  15619. magFilter = gl.LINEAR;
  15620. if (generateMipMaps) {
  15621. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  15622. }
  15623. else {
  15624. minFilter = gl.NEAREST;
  15625. }
  15626. break;
  15627. case Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR:
  15628. magFilter = gl.LINEAR;
  15629. if (generateMipMaps) {
  15630. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  15631. }
  15632. else {
  15633. minFilter = gl.NEAREST;
  15634. }
  15635. break;
  15636. case Engine.TEXTURE_LINEAR_LINEAR:
  15637. magFilter = gl.LINEAR;
  15638. minFilter = gl.LINEAR;
  15639. break;
  15640. case Engine.TEXTURE_LINEAR_NEAREST:
  15641. magFilter = gl.LINEAR;
  15642. minFilter = gl.NEAREST;
  15643. break;
  15644. }
  15645. return {
  15646. min: minFilter,
  15647. mag: magFilter
  15648. };
  15649. };
  15650. Engine.prototype._partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  15651. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  15652. var img;
  15653. var onload = function () {
  15654. loadedImages[index] = img;
  15655. loadedImages._internalCount++;
  15656. if (scene) {
  15657. scene._removePendingData(img);
  15658. }
  15659. if (loadedImages._internalCount === 6) {
  15660. onfinish(loadedImages);
  15661. }
  15662. };
  15663. var onerror = function (message, exception) {
  15664. if (scene) {
  15665. scene._removePendingData(img);
  15666. }
  15667. if (onErrorCallBack) {
  15668. onErrorCallBack(message, exception);
  15669. }
  15670. };
  15671. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.offlineProvider : null);
  15672. if (scene) {
  15673. scene._addPendingData(img);
  15674. }
  15675. };
  15676. Engine.prototype._cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  15677. if (onError === void 0) { onError = null; }
  15678. var loadedImages = [];
  15679. loadedImages._internalCount = 0;
  15680. for (var index = 0; index < 6; index++) {
  15681. this._partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  15682. }
  15683. };
  15684. /** @hidden */
  15685. Engine.prototype._createTexture = function () {
  15686. var texture = this._gl.createTexture();
  15687. if (!texture) {
  15688. throw new Error("Unable to create texture");
  15689. }
  15690. return texture;
  15691. };
  15692. /**
  15693. * Usually called from BABYLON.Texture.ts.
  15694. * Passed information to create a WebGLTexture
  15695. * @param urlArg defines a value which contains one of the following:
  15696. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  15697. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  15698. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  15699. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  15700. * @param invertY when true, image is flipped when loaded. You probably want true. Certain compressed textures may invert this if their default is inverted (eg. ktx)
  15701. * @param scene needed for loading to the correct scene
  15702. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  15703. * @param onLoad optional callback to be called upon successful completion
  15704. * @param onError optional callback to be called upon failure
  15705. * @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
  15706. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  15707. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  15708. * @param forcedExtension defines the extension to use to pick the right loader
  15709. * @param excludeLoaders array of texture loaders that should be excluded when picking a loader for the texture (default: empty array)
  15710. * @returns a InternalTexture for assignment back into BABYLON.Texture
  15711. */
  15712. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format, forcedExtension, excludeLoaders) {
  15713. var _this = this;
  15714. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  15715. if (onLoad === void 0) { onLoad = null; }
  15716. if (onError === void 0) { onError = null; }
  15717. if (buffer === void 0) { buffer = null; }
  15718. if (fallback === void 0) { fallback = null; }
  15719. if (format === void 0) { format = null; }
  15720. if (forcedExtension === void 0) { forcedExtension = null; }
  15721. if (excludeLoaders === void 0) { excludeLoaders = []; }
  15722. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  15723. var fromData = url.substr(0, 5) === "data:";
  15724. var fromBlob = url.substr(0, 5) === "blob:";
  15725. var isBase64 = fromData && url.indexOf(";base64,") !== -1;
  15726. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  15727. // establish the file extension, if possible
  15728. var lastDot = url.lastIndexOf('.');
  15729. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? url.substring(lastDot).toLowerCase() : "");
  15730. var loader = null;
  15731. for (var _i = 0, _a = Engine._TextureLoaders; _i < _a.length; _i++) {
  15732. var availableLoader = _a[_i];
  15733. if (excludeLoaders.indexOf(availableLoader) === -1 && availableLoader.canLoad(extension, this._textureFormatInUse, fallback, isBase64, buffer ? true : false)) {
  15734. loader = availableLoader;
  15735. break;
  15736. }
  15737. }
  15738. if (loader) {
  15739. url = loader.transformUrl(url, this._textureFormatInUse);
  15740. }
  15741. if (scene) {
  15742. scene._addPendingData(texture);
  15743. }
  15744. texture.url = url;
  15745. texture.generateMipMaps = !noMipmap;
  15746. texture.samplingMode = samplingMode;
  15747. texture.invertY = invertY;
  15748. if (!this._doNotHandleContextLost) {
  15749. // Keep a link to the buffer only if we plan to handle context lost
  15750. texture._buffer = buffer;
  15751. }
  15752. var onLoadObserver = null;
  15753. if (onLoad && !fallback) {
  15754. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  15755. }
  15756. if (!fallback) {
  15757. this._internalTexturesCache.push(texture);
  15758. }
  15759. var onInternalError = function (message, exception) {
  15760. if (scene) {
  15761. scene._removePendingData(texture);
  15762. }
  15763. var customFallback = false;
  15764. if (loader) {
  15765. var fallbackUrl = loader.getFallbackTextureUrl(url, _this._textureFormatInUse);
  15766. if (fallbackUrl) {
  15767. // Add Back
  15768. customFallback = true;
  15769. excludeLoaders.push(loader);
  15770. BABYLON.Tools.Warn(loader.constructor.name + " failed when trying to load " + texture.url + ", falling back to the next supported loader");
  15771. _this.createTexture(urlArg, noMipmap, texture.invertY, scene, samplingMode, null, null, buffer, texture, undefined, undefined, excludeLoaders);
  15772. }
  15773. }
  15774. if (!customFallback) {
  15775. if (onLoadObserver) {
  15776. texture.onLoadedObservable.remove(onLoadObserver);
  15777. }
  15778. if (BABYLON.Tools.UseFallbackTexture) {
  15779. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, texture.invertY, scene, samplingMode, null, null, buffer, texture);
  15780. }
  15781. }
  15782. if (onError) {
  15783. onError(message || "Unknown error", exception);
  15784. }
  15785. };
  15786. // processing for non-image formats
  15787. if (loader) {
  15788. var callback = function (data) {
  15789. loader.loadData(data, texture, function (width, height, loadMipmap, isCompressed, done, loadFailed) {
  15790. if (loadFailed) {
  15791. onInternalError("TextureLoader failed to load data");
  15792. }
  15793. else {
  15794. _this._prepareWebGLTexture(texture, scene, width, height, texture.invertY, !loadMipmap, isCompressed, function () {
  15795. done();
  15796. return false;
  15797. }, samplingMode);
  15798. }
  15799. });
  15800. };
  15801. if (!buffer) {
  15802. this._loadFile(url, callback, undefined, scene ? scene.offlineProvider : undefined, true, function (request, exception) {
  15803. onInternalError("Unable to load " + (request ? request.responseURL : url, exception));
  15804. });
  15805. }
  15806. else {
  15807. callback(buffer);
  15808. }
  15809. }
  15810. else {
  15811. var onload = function (img) {
  15812. if (fromBlob && !_this._doNotHandleContextLost) {
  15813. // We need to store the image if we need to rebuild the texture
  15814. // in case of a webgl context lost
  15815. texture._buffer = img;
  15816. }
  15817. _this._prepareWebGLTexture(texture, scene, img.width, img.height, texture.invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  15818. var gl = _this._gl;
  15819. var isPot = (img.width === potWidth && img.height === potHeight);
  15820. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  15821. if (isPot) {
  15822. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  15823. return false;
  15824. }
  15825. var maxTextureSize = _this._caps.maxTextureSize;
  15826. if (img.width > maxTextureSize || img.height > maxTextureSize) {
  15827. _this._prepareWorkingCanvas();
  15828. if (!_this._workingCanvas || !_this._workingContext) {
  15829. return false;
  15830. }
  15831. _this._workingCanvas.width = potWidth;
  15832. _this._workingCanvas.height = potHeight;
  15833. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  15834. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  15835. texture.width = potWidth;
  15836. texture.height = potHeight;
  15837. return false;
  15838. }
  15839. else {
  15840. // Using shaders when possible to rescale because canvas.drawImage is lossy
  15841. var source_1 = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  15842. _this._bindTextureDirectly(gl.TEXTURE_2D, source_1, true);
  15843. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  15844. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15845. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  15846. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15847. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15848. _this._rescaleTexture(source_1, texture, scene, internalFormat, function () {
  15849. _this._releaseTexture(source_1);
  15850. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15851. continuationCallback();
  15852. });
  15853. }
  15854. return true;
  15855. }, samplingMode);
  15856. };
  15857. if (!fromData || isBase64) {
  15858. if (buffer instanceof HTMLImageElement) {
  15859. onload(buffer);
  15860. }
  15861. else {
  15862. BABYLON.Tools.LoadImage(url, onload, onInternalError, scene ? scene.offlineProvider : null);
  15863. }
  15864. }
  15865. else if (typeof buffer === "string" || buffer instanceof ArrayBuffer || buffer instanceof Blob) {
  15866. BABYLON.Tools.LoadImage(buffer, onload, onInternalError, scene ? scene.offlineProvider : null);
  15867. }
  15868. else {
  15869. onload(buffer);
  15870. }
  15871. }
  15872. return texture;
  15873. };
  15874. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  15875. var _this = this;
  15876. var rtt = this.createRenderTargetTexture({
  15877. width: destination.width,
  15878. height: destination.height,
  15879. }, {
  15880. generateMipMaps: false,
  15881. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  15882. samplingMode: Engine.TEXTURE_BILINEAR_SAMPLINGMODE,
  15883. generateDepthBuffer: false,
  15884. generateStencilBuffer: false
  15885. });
  15886. if (!this._rescalePostProcess) {
  15887. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, Engine.TEXTURE_BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  15888. }
  15889. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  15890. _this._rescalePostProcess.onApply = function (effect) {
  15891. effect._bindTexture("textureSampler", source);
  15892. };
  15893. var hostingScene = scene;
  15894. if (!hostingScene) {
  15895. hostingScene = _this.scenes[_this.scenes.length - 1];
  15896. }
  15897. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  15898. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  15899. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  15900. _this.unBindFramebuffer(rtt);
  15901. _this._releaseTexture(rtt);
  15902. if (onComplete) {
  15903. onComplete();
  15904. }
  15905. });
  15906. };
  15907. /**
  15908. * Update a raw texture
  15909. * @param texture defines the texture to update
  15910. * @param data defines the data to store in the texture
  15911. * @param format defines the format of the data
  15912. * @param invertY defines if data must be stored with Y axis inverted
  15913. * @param compression defines the compression used (null by default)
  15914. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15915. */
  15916. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  15917. if (compression === void 0) { compression = null; }
  15918. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  15919. if (!texture) {
  15920. return;
  15921. }
  15922. // babylon's internalSizedFomat but gl's texImage2D internalFormat
  15923. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  15924. // babylon's internalFormat but gl's texImage2D format
  15925. var internalFormat = this._getInternalFormat(format);
  15926. var textureType = this._getWebGLTextureType(type);
  15927. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15928. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  15929. if (!this._doNotHandleContextLost) {
  15930. texture._bufferView = data;
  15931. texture.format = format;
  15932. texture.type = type;
  15933. texture.invertY = invertY;
  15934. texture._compression = compression;
  15935. }
  15936. if (texture.width % 4 !== 0) {
  15937. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  15938. }
  15939. if (compression && data) {
  15940. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  15941. }
  15942. else {
  15943. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  15944. }
  15945. if (texture.generateMipMaps) {
  15946. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15947. }
  15948. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15949. // this.resetTextureCache();
  15950. texture.isReady = true;
  15951. };
  15952. /**
  15953. * Creates a raw texture
  15954. * @param data defines the data to store in the texture
  15955. * @param width defines the width of the texture
  15956. * @param height defines the height of the texture
  15957. * @param format defines the format of the data
  15958. * @param generateMipMaps defines if the engine should generate the mip levels
  15959. * @param invertY defines if data must be stored with Y axis inverted
  15960. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  15961. * @param compression defines the compression used (null by default)
  15962. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15963. * @returns the raw texture inside an InternalTexture
  15964. */
  15965. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  15966. if (compression === void 0) { compression = null; }
  15967. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  15968. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  15969. texture.baseWidth = width;
  15970. texture.baseHeight = height;
  15971. texture.width = width;
  15972. texture.height = height;
  15973. texture.format = format;
  15974. texture.generateMipMaps = generateMipMaps;
  15975. texture.samplingMode = samplingMode;
  15976. texture.invertY = invertY;
  15977. texture._compression = compression;
  15978. texture.type = type;
  15979. if (!this._doNotHandleContextLost) {
  15980. texture._bufferView = data;
  15981. }
  15982. this.updateRawTexture(texture, data, format, invertY, compression, type);
  15983. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15984. // Filters
  15985. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  15986. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  15987. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15988. if (generateMipMaps) {
  15989. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15990. }
  15991. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15992. this._internalTexturesCache.push(texture);
  15993. return texture;
  15994. };
  15995. /** @hidden */
  15996. Engine.prototype._unpackFlipY = function (value) {
  15997. if (this._unpackFlipYCached !== value) {
  15998. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, value ? 1 : 0);
  15999. if (this.enableUnpackFlipYCached) {
  16000. this._unpackFlipYCached = value;
  16001. }
  16002. }
  16003. };
  16004. /** @hidden */
  16005. Engine.prototype._getUnpackAlignement = function () {
  16006. return this._gl.getParameter(this._gl.UNPACK_ALIGNMENT);
  16007. };
  16008. /**
  16009. * Creates a dynamic texture
  16010. * @param width defines the width of the texture
  16011. * @param height defines the height of the texture
  16012. * @param generateMipMaps defines if the engine should generate the mip levels
  16013. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  16014. * @returns the dynamic texture inside an InternalTexture
  16015. */
  16016. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  16017. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  16018. texture.baseWidth = width;
  16019. texture.baseHeight = height;
  16020. if (generateMipMaps) {
  16021. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  16022. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  16023. }
  16024. // this.resetTextureCache();
  16025. texture.width = width;
  16026. texture.height = height;
  16027. texture.isReady = false;
  16028. texture.generateMipMaps = generateMipMaps;
  16029. texture.samplingMode = samplingMode;
  16030. this.updateTextureSamplingMode(samplingMode, texture);
  16031. this._internalTexturesCache.push(texture);
  16032. return texture;
  16033. };
  16034. /**
  16035. * Update the sampling mode of a given texture
  16036. * @param samplingMode defines the required sampling mode
  16037. * @param texture defines the texture to update
  16038. */
  16039. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  16040. var filters = this._getSamplingParameters(samplingMode, texture.generateMipMaps);
  16041. if (texture.isCube) {
  16042. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  16043. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  16044. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16045. }
  16046. else if (texture.is3D) {
  16047. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  16048. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  16049. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16050. }
  16051. else {
  16052. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  16053. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  16054. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16055. }
  16056. texture.samplingMode = samplingMode;
  16057. };
  16058. /**
  16059. * Update the content of a dynamic texture
  16060. * @param texture defines the texture to update
  16061. * @param canvas defines the canvas containing the source
  16062. * @param invertY defines if data must be stored with Y axis inverted
  16063. * @param premulAlpha defines if alpha is stored as premultiplied
  16064. * @param format defines the format of the data
  16065. * @param forceBindTexture if the texture should be forced to be bound eg. after a graphics context loss (Default: false)
  16066. */
  16067. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format, forceBindTexture) {
  16068. if (premulAlpha === void 0) { premulAlpha = false; }
  16069. if (forceBindTexture === void 0) { forceBindTexture = false; }
  16070. if (!texture) {
  16071. return;
  16072. }
  16073. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true, forceBindTexture);
  16074. this._unpackFlipY(invertY);
  16075. if (premulAlpha) {
  16076. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  16077. }
  16078. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  16079. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  16080. if (texture.generateMipMaps) {
  16081. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  16082. }
  16083. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16084. if (premulAlpha) {
  16085. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  16086. }
  16087. texture.isReady = true;
  16088. };
  16089. /**
  16090. * Update a video texture
  16091. * @param texture defines the texture to update
  16092. * @param video defines the video element to use
  16093. * @param invertY defines if data must be stored with Y axis inverted
  16094. */
  16095. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  16096. if (!texture || texture._isDisabled) {
  16097. return;
  16098. }
  16099. var wasPreviouslyBound = this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  16100. this._unpackFlipY(!invertY); // Video are upside down by default
  16101. try {
  16102. // Testing video texture support
  16103. if (this._videoTextureSupported === undefined) {
  16104. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  16105. if (this._gl.getError() !== 0) {
  16106. this._videoTextureSupported = false;
  16107. }
  16108. else {
  16109. this._videoTextureSupported = true;
  16110. }
  16111. }
  16112. // Copy video through the current working canvas if video texture is not supported
  16113. if (!this._videoTextureSupported) {
  16114. if (!texture._workingCanvas) {
  16115. texture._workingCanvas = document.createElement("canvas");
  16116. var context = texture._workingCanvas.getContext("2d");
  16117. if (!context) {
  16118. throw new Error("Unable to get 2d context");
  16119. }
  16120. texture._workingContext = context;
  16121. texture._workingCanvas.width = texture.width;
  16122. texture._workingCanvas.height = texture.height;
  16123. }
  16124. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  16125. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  16126. }
  16127. else {
  16128. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  16129. }
  16130. if (texture.generateMipMaps) {
  16131. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  16132. }
  16133. if (!wasPreviouslyBound) {
  16134. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16135. }
  16136. // this.resetTextureCache();
  16137. texture.isReady = true;
  16138. }
  16139. catch (ex) {
  16140. // Something unexpected
  16141. // Let's disable the texture
  16142. texture._isDisabled = true;
  16143. }
  16144. };
  16145. /**
  16146. * Updates a depth texture Comparison Mode and Function.
  16147. * If the comparison Function is equal to 0, the mode will be set to none.
  16148. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  16149. * @param texture The texture to set the comparison function for
  16150. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  16151. */
  16152. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  16153. if (this.webGLVersion === 1) {
  16154. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  16155. return;
  16156. }
  16157. var gl = this._gl;
  16158. if (texture.isCube) {
  16159. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  16160. if (comparisonFunction === 0) {
  16161. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  16162. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  16163. }
  16164. else {
  16165. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  16166. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  16167. }
  16168. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16169. }
  16170. else {
  16171. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  16172. if (comparisonFunction === 0) {
  16173. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  16174. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  16175. }
  16176. else {
  16177. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  16178. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  16179. }
  16180. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16181. }
  16182. texture._comparisonFunction = comparisonFunction;
  16183. };
  16184. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  16185. var width = size.width || size;
  16186. var height = size.height || size;
  16187. internalTexture.baseWidth = width;
  16188. internalTexture.baseHeight = height;
  16189. internalTexture.width = width;
  16190. internalTexture.height = height;
  16191. internalTexture.isReady = true;
  16192. internalTexture.samples = 1;
  16193. internalTexture.generateMipMaps = false;
  16194. internalTexture._generateDepthBuffer = true;
  16195. internalTexture._generateStencilBuffer = generateStencil;
  16196. internalTexture.samplingMode = bilinearFiltering ? Engine.TEXTURE_BILINEAR_SAMPLINGMODE : Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  16197. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  16198. internalTexture._comparisonFunction = comparisonFunction;
  16199. var gl = this._gl;
  16200. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  16201. var samplingParameters = this._getSamplingParameters(internalTexture.samplingMode, false);
  16202. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  16203. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  16204. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16205. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16206. if (comparisonFunction === 0) {
  16207. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  16208. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  16209. }
  16210. else {
  16211. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  16212. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  16213. }
  16214. };
  16215. /**
  16216. * Creates a depth stencil texture.
  16217. * This is only available in WebGL 2 or with the depth texture extension available.
  16218. * @param size The size of face edge in the texture.
  16219. * @param options The options defining the texture.
  16220. * @returns The texture
  16221. */
  16222. Engine.prototype.createDepthStencilTexture = function (size, options) {
  16223. if (options.isCube) {
  16224. var width = size.width || size;
  16225. return this._createDepthStencilCubeTexture(width, options);
  16226. }
  16227. else {
  16228. return this._createDepthStencilTexture(size, options);
  16229. }
  16230. };
  16231. /**
  16232. * Creates a depth stencil texture.
  16233. * This is only available in WebGL 2 or with the depth texture extension available.
  16234. * @param size The size of face edge in the texture.
  16235. * @param options The options defining the texture.
  16236. * @returns The texture
  16237. */
  16238. Engine.prototype._createDepthStencilTexture = function (size, options) {
  16239. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  16240. if (!this._caps.depthTextureExtension) {
  16241. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  16242. return internalTexture;
  16243. }
  16244. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  16245. var gl = this._gl;
  16246. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  16247. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  16248. if (this.webGLVersion > 1) {
  16249. if (internalOptions.generateStencil) {
  16250. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  16251. }
  16252. else {
  16253. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  16254. }
  16255. }
  16256. else {
  16257. if (internalOptions.generateStencil) {
  16258. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  16259. }
  16260. else {
  16261. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  16262. }
  16263. }
  16264. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  16265. return internalTexture;
  16266. };
  16267. /**
  16268. * Creates a depth stencil cube texture.
  16269. * This is only available in WebGL 2.
  16270. * @param size The size of face edge in the cube texture.
  16271. * @param options The options defining the cube texture.
  16272. * @returns The cube texture
  16273. */
  16274. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  16275. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  16276. internalTexture.isCube = true;
  16277. if (this.webGLVersion === 1) {
  16278. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  16279. return internalTexture;
  16280. }
  16281. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  16282. var gl = this._gl;
  16283. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  16284. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  16285. // Create the depth/stencil buffer
  16286. for (var face = 0; face < 6; face++) {
  16287. if (internalOptions.generateStencil) {
  16288. 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);
  16289. }
  16290. else {
  16291. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  16292. }
  16293. }
  16294. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16295. return internalTexture;
  16296. };
  16297. /**
  16298. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  16299. * @param renderTarget The render target to set the frame buffer for
  16300. */
  16301. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  16302. // Create the framebuffer
  16303. var internalTexture = renderTarget.getInternalTexture();
  16304. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  16305. return;
  16306. }
  16307. var gl = this._gl;
  16308. var depthStencilTexture = renderTarget.depthStencilTexture;
  16309. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  16310. if (depthStencilTexture.isCube) {
  16311. if (depthStencilTexture._generateStencilBuffer) {
  16312. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  16313. }
  16314. else {
  16315. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  16316. }
  16317. }
  16318. else {
  16319. if (depthStencilTexture._generateStencilBuffer) {
  16320. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  16321. }
  16322. else {
  16323. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  16324. }
  16325. }
  16326. this.bindUnboundFramebuffer(null);
  16327. };
  16328. /**
  16329. * Creates a new render target texture
  16330. * @param size defines the size of the texture
  16331. * @param options defines the options used to create the texture
  16332. * @returns a new render target texture stored in an InternalTexture
  16333. */
  16334. Engine.prototype.createRenderTargetTexture = function (size, options) {
  16335. var fullOptions = new RenderTargetCreationOptions();
  16336. if (options !== undefined && typeof options === "object") {
  16337. fullOptions.generateMipMaps = options.generateMipMaps;
  16338. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  16339. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  16340. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  16341. fullOptions.samplingMode = options.samplingMode === undefined ? Engine.TEXTURE_TRILINEAR_SAMPLINGMODE : options.samplingMode;
  16342. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  16343. }
  16344. else {
  16345. fullOptions.generateMipMaps = options;
  16346. fullOptions.generateDepthBuffer = true;
  16347. fullOptions.generateStencilBuffer = false;
  16348. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  16349. fullOptions.samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  16350. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  16351. }
  16352. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  16353. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  16354. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  16355. }
  16356. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  16357. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  16358. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  16359. }
  16360. var gl = this._gl;
  16361. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  16362. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  16363. var width = size.width || size;
  16364. var height = size.height || size;
  16365. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false);
  16366. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  16367. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  16368. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  16369. }
  16370. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  16371. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  16372. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16373. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16374. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  16375. // Create the framebuffer
  16376. var currentFrameBuffer = this._currentFramebuffer;
  16377. var framebuffer = gl.createFramebuffer();
  16378. this.bindUnboundFramebuffer(framebuffer);
  16379. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  16380. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  16381. if (fullOptions.generateMipMaps) {
  16382. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  16383. }
  16384. // Unbind
  16385. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  16386. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  16387. this.bindUnboundFramebuffer(currentFrameBuffer);
  16388. texture._framebuffer = framebuffer;
  16389. texture.baseWidth = width;
  16390. texture.baseHeight = height;
  16391. texture.width = width;
  16392. texture.height = height;
  16393. texture.isReady = true;
  16394. texture.samples = 1;
  16395. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  16396. texture.samplingMode = fullOptions.samplingMode;
  16397. texture.type = fullOptions.type;
  16398. texture.format = fullOptions.format;
  16399. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  16400. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  16401. // this.resetTextureCache();
  16402. this._internalTexturesCache.push(texture);
  16403. return texture;
  16404. };
  16405. /**
  16406. * Create a multi render target texture
  16407. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  16408. * @param size defines the size of the texture
  16409. * @param options defines the creation options
  16410. * @returns the cube texture as an InternalTexture
  16411. */
  16412. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  16413. var generateMipMaps = false;
  16414. var generateDepthBuffer = true;
  16415. var generateStencilBuffer = false;
  16416. var generateDepthTexture = false;
  16417. var textureCount = 1;
  16418. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  16419. var defaultSamplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  16420. var types = new Array();
  16421. var samplingModes = new Array();
  16422. if (options !== undefined) {
  16423. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  16424. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  16425. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  16426. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  16427. textureCount = options.textureCount || 1;
  16428. if (options.types) {
  16429. types = options.types;
  16430. }
  16431. if (options.samplingModes) {
  16432. samplingModes = options.samplingModes;
  16433. }
  16434. }
  16435. var gl = this._gl;
  16436. // Create the framebuffer
  16437. var framebuffer = gl.createFramebuffer();
  16438. this.bindUnboundFramebuffer(framebuffer);
  16439. var width = size.width || size;
  16440. var height = size.height || size;
  16441. var textures = [];
  16442. var attachments = [];
  16443. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  16444. for (var i = 0; i < textureCount; i++) {
  16445. var samplingMode = samplingModes[i] || defaultSamplingMode;
  16446. var type = types[i] || defaultType;
  16447. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  16448. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  16449. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  16450. }
  16451. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  16452. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  16453. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  16454. }
  16455. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  16456. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  16457. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  16458. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  16459. }
  16460. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  16461. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  16462. textures.push(texture);
  16463. attachments.push(attachment);
  16464. gl.activeTexture(gl["TEXTURE" + i]);
  16465. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  16466. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  16467. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  16468. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16469. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16470. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  16471. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  16472. if (generateMipMaps) {
  16473. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  16474. }
  16475. // Unbind
  16476. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  16477. texture._framebuffer = framebuffer;
  16478. texture._depthStencilBuffer = depthStencilBuffer;
  16479. texture.baseWidth = width;
  16480. texture.baseHeight = height;
  16481. texture.width = width;
  16482. texture.height = height;
  16483. texture.isReady = true;
  16484. texture.samples = 1;
  16485. texture.generateMipMaps = generateMipMaps;
  16486. texture.samplingMode = samplingMode;
  16487. texture.type = type;
  16488. texture._generateDepthBuffer = generateDepthBuffer;
  16489. texture._generateStencilBuffer = generateStencilBuffer;
  16490. texture._attachments = attachments;
  16491. this._internalTexturesCache.push(texture);
  16492. }
  16493. if (generateDepthTexture && this._caps.depthTextureExtension) {
  16494. // Depth texture
  16495. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  16496. gl.activeTexture(gl.TEXTURE0);
  16497. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  16498. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  16499. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  16500. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16501. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16502. 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);
  16503. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  16504. depthTexture._framebuffer = framebuffer;
  16505. depthTexture.baseWidth = width;
  16506. depthTexture.baseHeight = height;
  16507. depthTexture.width = width;
  16508. depthTexture.height = height;
  16509. depthTexture.isReady = true;
  16510. depthTexture.samples = 1;
  16511. depthTexture.generateMipMaps = generateMipMaps;
  16512. depthTexture.samplingMode = gl.NEAREST;
  16513. depthTexture._generateDepthBuffer = generateDepthBuffer;
  16514. depthTexture._generateStencilBuffer = generateStencilBuffer;
  16515. textures.push(depthTexture);
  16516. this._internalTexturesCache.push(depthTexture);
  16517. }
  16518. gl.drawBuffers(attachments);
  16519. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  16520. this.bindUnboundFramebuffer(null);
  16521. this.resetTextureCache();
  16522. return textures;
  16523. };
  16524. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  16525. if (samples === void 0) { samples = 1; }
  16526. var depthStencilBuffer = null;
  16527. var gl = this._gl;
  16528. // Create the depth/stencil buffer
  16529. if (generateStencilBuffer) {
  16530. depthStencilBuffer = gl.createRenderbuffer();
  16531. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  16532. if (samples > 1) {
  16533. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  16534. }
  16535. else {
  16536. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  16537. }
  16538. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  16539. }
  16540. else if (generateDepthBuffer) {
  16541. depthStencilBuffer = gl.createRenderbuffer();
  16542. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  16543. if (samples > 1) {
  16544. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  16545. }
  16546. else {
  16547. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  16548. }
  16549. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  16550. }
  16551. return depthStencilBuffer;
  16552. };
  16553. /**
  16554. * Updates the sample count of a render target texture
  16555. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  16556. * @param texture defines the texture to update
  16557. * @param samples defines the sample count to set
  16558. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  16559. */
  16560. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  16561. if (this.webGLVersion < 2 || !texture) {
  16562. return 1;
  16563. }
  16564. if (texture.samples === samples) {
  16565. return samples;
  16566. }
  16567. var gl = this._gl;
  16568. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  16569. // Dispose previous render buffers
  16570. if (texture._depthStencilBuffer) {
  16571. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  16572. texture._depthStencilBuffer = null;
  16573. }
  16574. if (texture._MSAAFramebuffer) {
  16575. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  16576. texture._MSAAFramebuffer = null;
  16577. }
  16578. if (texture._MSAARenderBuffer) {
  16579. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  16580. texture._MSAARenderBuffer = null;
  16581. }
  16582. if (samples > 1) {
  16583. var framebuffer = gl.createFramebuffer();
  16584. if (!framebuffer) {
  16585. throw new Error("Unable to create multi sampled framebuffer");
  16586. }
  16587. texture._MSAAFramebuffer = framebuffer;
  16588. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  16589. var colorRenderbuffer = gl.createRenderbuffer();
  16590. if (!colorRenderbuffer) {
  16591. throw new Error("Unable to create multi sampled framebuffer");
  16592. }
  16593. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  16594. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  16595. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  16596. texture._MSAARenderBuffer = colorRenderbuffer;
  16597. }
  16598. else {
  16599. this.bindUnboundFramebuffer(texture._framebuffer);
  16600. }
  16601. texture.samples = samples;
  16602. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  16603. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  16604. this.bindUnboundFramebuffer(null);
  16605. return samples;
  16606. };
  16607. /**
  16608. * Update the sample count for a given multiple render target texture
  16609. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  16610. * @param textures defines the textures to update
  16611. * @param samples defines the sample count to set
  16612. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  16613. */
  16614. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  16615. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  16616. return 1;
  16617. }
  16618. if (textures[0].samples === samples) {
  16619. return samples;
  16620. }
  16621. var gl = this._gl;
  16622. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  16623. // Dispose previous render buffers
  16624. if (textures[0]._depthStencilBuffer) {
  16625. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  16626. textures[0]._depthStencilBuffer = null;
  16627. }
  16628. if (textures[0]._MSAAFramebuffer) {
  16629. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  16630. textures[0]._MSAAFramebuffer = null;
  16631. }
  16632. for (var i = 0; i < textures.length; i++) {
  16633. if (textures[i]._MSAARenderBuffer) {
  16634. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  16635. textures[i]._MSAARenderBuffer = null;
  16636. }
  16637. }
  16638. if (samples > 1) {
  16639. var framebuffer = gl.createFramebuffer();
  16640. if (!framebuffer) {
  16641. throw new Error("Unable to create multi sampled framebuffer");
  16642. }
  16643. this.bindUnboundFramebuffer(framebuffer);
  16644. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  16645. var attachments = [];
  16646. for (var i = 0; i < textures.length; i++) {
  16647. var texture = textures[i];
  16648. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  16649. var colorRenderbuffer = gl.createRenderbuffer();
  16650. if (!colorRenderbuffer) {
  16651. throw new Error("Unable to create multi sampled framebuffer");
  16652. }
  16653. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  16654. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  16655. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  16656. texture._MSAAFramebuffer = framebuffer;
  16657. texture._MSAARenderBuffer = colorRenderbuffer;
  16658. texture.samples = samples;
  16659. texture._depthStencilBuffer = depthStencilBuffer;
  16660. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  16661. attachments.push(attachment);
  16662. }
  16663. gl.drawBuffers(attachments);
  16664. }
  16665. else {
  16666. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  16667. }
  16668. this.bindUnboundFramebuffer(null);
  16669. return samples;
  16670. };
  16671. /** @hidden */
  16672. Engine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
  16673. if (faceIndex === void 0) { faceIndex = 0; }
  16674. if (lod === void 0) { lod = 0; }
  16675. var gl = this._gl;
  16676. var target = gl.TEXTURE_2D;
  16677. if (texture.isCube) {
  16678. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  16679. }
  16680. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  16681. };
  16682. /** @hidden */
  16683. Engine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {
  16684. if (faceIndex === void 0) { faceIndex = 0; }
  16685. if (lod === void 0) { lod = 0; }
  16686. var gl = this._gl;
  16687. var textureType = this._getWebGLTextureType(texture.type);
  16688. var format = this._getInternalFormat(texture.format);
  16689. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  16690. this._unpackFlipY(texture.invertY);
  16691. var target = gl.TEXTURE_2D;
  16692. if (texture.isCube) {
  16693. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  16694. }
  16695. var lodMaxWidth = Math.round(BABYLON.Scalar.Log2(texture.width));
  16696. var lodMaxHeight = Math.round(BABYLON.Scalar.Log2(texture.height));
  16697. var width = Math.pow(2, Math.max(lodMaxWidth - lod, 0));
  16698. var height = Math.pow(2, Math.max(lodMaxHeight - lod, 0));
  16699. gl.texImage2D(target, lod, internalFormat, width, height, 0, format, textureType, imageData);
  16700. };
  16701. /** @hidden */
  16702. Engine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
  16703. if (faceIndex === void 0) { faceIndex = 0; }
  16704. if (lod === void 0) { lod = 0; }
  16705. var gl = this._gl;
  16706. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  16707. this._bindTextureDirectly(bindTarget, texture, true);
  16708. this._uploadDataToTextureDirectly(texture, imageData, faceIndex, lod);
  16709. this._bindTextureDirectly(bindTarget, null, true);
  16710. };
  16711. /** @hidden */
  16712. Engine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {
  16713. if (faceIndex === void 0) { faceIndex = 0; }
  16714. if (lod === void 0) { lod = 0; }
  16715. var gl = this._gl;
  16716. var textureType = this._getWebGLTextureType(texture.type);
  16717. var format = this._getInternalFormat(texture.format);
  16718. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  16719. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  16720. this._bindTextureDirectly(bindTarget, texture, true);
  16721. this._unpackFlipY(texture.invertY);
  16722. var target = gl.TEXTURE_2D;
  16723. if (texture.isCube) {
  16724. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  16725. }
  16726. gl.texImage2D(target, lod, internalFormat, format, textureType, image);
  16727. this._bindTextureDirectly(bindTarget, null, true);
  16728. };
  16729. /**
  16730. * Creates a new render target cube texture
  16731. * @param size defines the size of the texture
  16732. * @param options defines the options used to create the texture
  16733. * @returns a new render target cube texture stored in an InternalTexture
  16734. */
  16735. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  16736. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: Engine.TEXTURE_TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  16737. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  16738. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  16739. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  16740. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  16741. }
  16742. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  16743. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  16744. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  16745. }
  16746. var gl = this._gl;
  16747. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  16748. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16749. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps);
  16750. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  16751. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  16752. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  16753. }
  16754. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  16755. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  16756. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16757. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16758. for (var face = 0; face < 6; face++) {
  16759. 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);
  16760. }
  16761. // Create the framebuffer
  16762. var framebuffer = gl.createFramebuffer();
  16763. this.bindUnboundFramebuffer(framebuffer);
  16764. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  16765. // MipMaps
  16766. if (fullOptions.generateMipMaps) {
  16767. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  16768. }
  16769. // Unbind
  16770. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16771. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  16772. this.bindUnboundFramebuffer(null);
  16773. texture._framebuffer = framebuffer;
  16774. texture.width = size;
  16775. texture.height = size;
  16776. texture.isReady = true;
  16777. texture.isCube = true;
  16778. texture.samples = 1;
  16779. texture.generateMipMaps = fullOptions.generateMipMaps;
  16780. texture.samplingMode = fullOptions.samplingMode;
  16781. texture.type = fullOptions.type;
  16782. texture.format = fullOptions.format;
  16783. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  16784. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  16785. this._internalTexturesCache.push(texture);
  16786. return texture;
  16787. };
  16788. /**
  16789. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  16790. * @param rootUrl defines the url where the file to load is located
  16791. * @param scene defines the current scene
  16792. * @param lodScale defines scale to apply to the mip map selection
  16793. * @param lodOffset defines offset to apply to the mip map selection
  16794. * @param onLoad defines an optional callback raised when the texture is loaded
  16795. * @param onError defines an optional callback raised if there is an issue to load the texture
  16796. * @param format defines the format of the data
  16797. * @param forcedExtension defines the extension to use to pick the right loader
  16798. * @param createPolynomials defines wheter or not to create polynomails harmonics for the texture
  16799. * @returns the cube texture as an InternalTexture
  16800. */
  16801. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, createPolynomials) {
  16802. var _this = this;
  16803. if (onLoad === void 0) { onLoad = null; }
  16804. if (onError === void 0) { onError = null; }
  16805. if (forcedExtension === void 0) { forcedExtension = null; }
  16806. if (createPolynomials === void 0) { createPolynomials = true; }
  16807. var callback = function (loadData) {
  16808. if (!loadData) {
  16809. if (onLoad) {
  16810. onLoad(null);
  16811. }
  16812. return;
  16813. }
  16814. var texture = loadData.texture;
  16815. if (!createPolynomials) {
  16816. texture._sphericalPolynomial = new BABYLON.SphericalPolynomial();
  16817. }
  16818. else if (loadData.info.sphericalPolynomial) {
  16819. texture._sphericalPolynomial = loadData.info.sphericalPolynomial;
  16820. }
  16821. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  16822. if (_this._caps.textureLOD) {
  16823. // Do not add extra process if texture lod is supported.
  16824. if (onLoad) {
  16825. onLoad(texture);
  16826. }
  16827. return;
  16828. }
  16829. var mipSlices = 3;
  16830. var gl = _this._gl;
  16831. var width = loadData.width;
  16832. if (!width) {
  16833. return;
  16834. }
  16835. var textures = [];
  16836. for (var i = 0; i < mipSlices; i++) {
  16837. //compute LOD from even spacing in smoothness (matching shader calculation)
  16838. var smoothness = i / (mipSlices - 1);
  16839. var roughness = 1 - smoothness;
  16840. var minLODIndex = lodOffset; // roughness = 0
  16841. var maxLODIndex = BABYLON.Scalar.Log2(width) * lodScale + lodOffset; // roughness = 1
  16842. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  16843. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  16844. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  16845. glTextureFromLod.type = texture.type;
  16846. glTextureFromLod.format = texture.format;
  16847. glTextureFromLod.width = Math.pow(2, Math.max(BABYLON.Scalar.Log2(width) - mipmapIndex, 0));
  16848. glTextureFromLod.height = glTextureFromLod.width;
  16849. glTextureFromLod.isCube = true;
  16850. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  16851. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  16852. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  16853. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16854. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16855. if (loadData.isDDS) {
  16856. var info = loadData.info;
  16857. var data = loadData.data;
  16858. _this._unpackFlipY(info.isCompressed);
  16859. BABYLON.DDSTools.UploadDDSLevels(_this, glTextureFromLod, data, info, true, 6, mipmapIndex);
  16860. }
  16861. else {
  16862. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  16863. }
  16864. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16865. // Wrap in a base texture for easy binding.
  16866. var lodTexture = new BABYLON.BaseTexture(scene);
  16867. lodTexture.isCube = true;
  16868. lodTexture._texture = glTextureFromLod;
  16869. glTextureFromLod.isReady = true;
  16870. textures.push(lodTexture);
  16871. }
  16872. texture._lodTextureHigh = textures[2];
  16873. texture._lodTextureMid = textures[1];
  16874. texture._lodTextureLow = textures[0];
  16875. if (onLoad) {
  16876. onLoad(texture);
  16877. }
  16878. };
  16879. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset);
  16880. };
  16881. /**
  16882. * Creates a cube texture
  16883. * @param rootUrl defines the url where the files to load is located
  16884. * @param scene defines the current scene
  16885. * @param files defines the list of files to load (1 per face)
  16886. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  16887. * @param onLoad defines an optional callback raised when the texture is loaded
  16888. * @param onError defines an optional callback raised if there is an issue to load the texture
  16889. * @param format defines the format of the data
  16890. * @param forcedExtension defines the extension to use to pick the right loader
  16891. * @param createPolynomials if a polynomial sphere should be created for the cube texture
  16892. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  16893. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  16894. * @param fallback defines texture to use while falling back when (compressed) texture file not found.
  16895. * @param excludeLoaders array of texture loaders that should be excluded when picking a loader for the texture (defualt: empty array)
  16896. * @returns the cube texture as an InternalTexture
  16897. */
  16898. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset, fallback, excludeLoaders) {
  16899. var _this = this;
  16900. if (onLoad === void 0) { onLoad = null; }
  16901. if (onError === void 0) { onError = null; }
  16902. if (forcedExtension === void 0) { forcedExtension = null; }
  16903. if (createPolynomials === void 0) { createPolynomials = false; }
  16904. if (lodScale === void 0) { lodScale = 0; }
  16905. if (lodOffset === void 0) { lodOffset = 0; }
  16906. if (fallback === void 0) { fallback = null; }
  16907. if (excludeLoaders === void 0) { excludeLoaders = []; }
  16908. var gl = this._gl;
  16909. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  16910. texture.isCube = true;
  16911. texture.url = rootUrl;
  16912. texture.generateMipMaps = !noMipmap;
  16913. texture._lodGenerationScale = lodScale;
  16914. texture._lodGenerationOffset = lodOffset;
  16915. if (!this._doNotHandleContextLost) {
  16916. texture._extension = forcedExtension;
  16917. texture._files = files;
  16918. }
  16919. var lastDot = rootUrl.lastIndexOf('.');
  16920. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  16921. var loader = null;
  16922. for (var _i = 0, _a = Engine._TextureLoaders; _i < _a.length; _i++) {
  16923. var availableLoader = _a[_i];
  16924. if (excludeLoaders.indexOf(availableLoader) === -1 && availableLoader.canLoad(extension, this._textureFormatInUse, fallback, false, false)) {
  16925. loader = availableLoader;
  16926. break;
  16927. }
  16928. }
  16929. var onInternalError = function (request, exception) {
  16930. if (loader) {
  16931. var fallbackUrl = loader.getFallbackTextureUrl(texture.url, _this._textureFormatInUse);
  16932. BABYLON.Tools.Warn(loader.constructor.name + " failed when trying to load " + texture.url + ", falling back to the next supported loader");
  16933. if (fallbackUrl) {
  16934. excludeLoaders.push(loader);
  16935. _this.createCubeTexture(fallbackUrl, scene, files, noMipmap, onLoad, onError, format, extension, createPolynomials, lodScale, lodOffset, texture, excludeLoaders);
  16936. return;
  16937. }
  16938. }
  16939. if (onError && request) {
  16940. onError(request.status + " " + request.statusText, exception);
  16941. }
  16942. };
  16943. if (loader) {
  16944. rootUrl = loader.transformUrl(rootUrl, this._textureFormatInUse);
  16945. var onloaddata = function (data) {
  16946. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16947. loader.loadCubeData(data, texture, createPolynomials, onLoad, onError);
  16948. };
  16949. if (files && files.length === 6) {
  16950. if (loader.supportCascades) {
  16951. this._cascadeLoadFiles(scene, onloaddata, files, onError);
  16952. }
  16953. else if (onError) {
  16954. onError("Textures type does not support cascades.");
  16955. }
  16956. }
  16957. else {
  16958. this._loadFile(rootUrl, onloaddata, undefined, undefined, true, onInternalError);
  16959. }
  16960. }
  16961. else {
  16962. if (!files) {
  16963. throw new Error("Cannot load cubemap because files were not defined");
  16964. }
  16965. this._cascadeLoadImgs(rootUrl, scene, function (imgs) {
  16966. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  16967. var height = width;
  16968. _this._prepareWorkingCanvas();
  16969. if (!_this._workingCanvas || !_this._workingContext) {
  16970. return;
  16971. }
  16972. _this._workingCanvas.width = width;
  16973. _this._workingCanvas.height = height;
  16974. var faces = [
  16975. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  16976. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  16977. ];
  16978. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16979. _this._unpackFlipY(false);
  16980. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  16981. for (var index = 0; index < faces.length; index++) {
  16982. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  16983. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  16984. }
  16985. if (!noMipmap) {
  16986. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  16987. }
  16988. _this._setCubeMapTextureParams(!noMipmap);
  16989. texture.width = width;
  16990. texture.height = height;
  16991. texture.isReady = true;
  16992. if (format) {
  16993. texture.format = format;
  16994. }
  16995. texture.onLoadedObservable.notifyObservers(texture);
  16996. texture.onLoadedObservable.clear();
  16997. if (onLoad) {
  16998. onLoad();
  16999. }
  17000. }, files, onError);
  17001. }
  17002. this._internalTexturesCache.push(texture);
  17003. return texture;
  17004. };
  17005. /**
  17006. * @hidden
  17007. */
  17008. Engine.prototype._setCubeMapTextureParams = function (loadMipmap) {
  17009. var gl = this._gl;
  17010. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  17011. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  17012. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  17013. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  17014. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  17015. // this.resetTextureCache();
  17016. };
  17017. /**
  17018. * Update a raw cube texture
  17019. * @param texture defines the texture to udpdate
  17020. * @param data defines the data to store
  17021. * @param format defines the data format
  17022. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  17023. * @param invertY defines if data must be stored with Y axis inverted
  17024. * @param compression defines the compression used (null by default)
  17025. * @param level defines which level of the texture to update
  17026. */
  17027. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  17028. if (compression === void 0) { compression = null; }
  17029. if (level === void 0) { level = 0; }
  17030. texture._bufferViewArray = data;
  17031. texture.format = format;
  17032. texture.type = type;
  17033. texture.invertY = invertY;
  17034. texture._compression = compression;
  17035. var gl = this._gl;
  17036. var textureType = this._getWebGLTextureType(type);
  17037. var internalFormat = this._getInternalFormat(format);
  17038. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  17039. var needConversion = false;
  17040. if (internalFormat === gl.RGB) {
  17041. internalFormat = gl.RGBA;
  17042. needConversion = true;
  17043. }
  17044. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  17045. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  17046. if (texture.width % 4 !== 0) {
  17047. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  17048. }
  17049. // Data are known to be in +X +Y +Z -X -Y -Z
  17050. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  17051. var faceData = data[faceIndex];
  17052. if (compression) {
  17053. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  17054. }
  17055. else {
  17056. if (needConversion) {
  17057. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  17058. }
  17059. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  17060. }
  17061. }
  17062. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  17063. if (isPot && texture.generateMipMaps && level === 0) {
  17064. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  17065. }
  17066. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  17067. // this.resetTextureCache();
  17068. texture.isReady = true;
  17069. };
  17070. /**
  17071. * Creates a new raw cube texture
  17072. * @param data defines the array of data to use to create each face
  17073. * @param size defines the size of the textures
  17074. * @param format defines the format of the data
  17075. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  17076. * @param generateMipMaps defines if the engine should generate the mip levels
  17077. * @param invertY defines if data must be stored with Y axis inverted
  17078. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  17079. * @param compression defines the compression used (null by default)
  17080. * @returns the cube texture as an InternalTexture
  17081. */
  17082. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  17083. if (compression === void 0) { compression = null; }
  17084. var gl = this._gl;
  17085. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  17086. texture.isCube = true;
  17087. texture.format = format;
  17088. texture.type = type;
  17089. if (!this._doNotHandleContextLost) {
  17090. texture._bufferViewArray = data;
  17091. }
  17092. var textureType = this._getWebGLTextureType(type);
  17093. var internalFormat = this._getInternalFormat(format);
  17094. if (internalFormat === gl.RGB) {
  17095. internalFormat = gl.RGBA;
  17096. }
  17097. // Mipmap generation needs a sized internal format that is both color-renderable and texture-filterable
  17098. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  17099. generateMipMaps = false;
  17100. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  17101. BABYLON.Tools.Warn("Float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.");
  17102. }
  17103. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  17104. generateMipMaps = false;
  17105. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  17106. BABYLON.Tools.Warn("Half float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.");
  17107. }
  17108. else if (textureType === gl.FLOAT && !this._caps.textureFloatRender) {
  17109. generateMipMaps = false;
  17110. BABYLON.Tools.Warn("Render to float textures is not supported. Mipmap generation forced to false.");
  17111. }
  17112. else if (textureType === gl.HALF_FLOAT && !this._caps.colorBufferFloat) {
  17113. generateMipMaps = false;
  17114. BABYLON.Tools.Warn("Render to half float textures is not supported. Mipmap generation forced to false.");
  17115. }
  17116. var width = size;
  17117. var height = width;
  17118. texture.width = width;
  17119. texture.height = height;
  17120. // Double check on POT to generate Mips.
  17121. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  17122. if (!isPot) {
  17123. generateMipMaps = false;
  17124. }
  17125. // Upload data if needed. The texture won't be ready until then.
  17126. if (data) {
  17127. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  17128. }
  17129. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  17130. // Filters
  17131. if (data && generateMipMaps) {
  17132. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  17133. }
  17134. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  17135. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  17136. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  17137. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  17138. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  17139. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  17140. texture.generateMipMaps = generateMipMaps;
  17141. return texture;
  17142. };
  17143. /**
  17144. * Creates a new raw cube texture from a specified url
  17145. * @param url defines the url where the data is located
  17146. * @param scene defines the current scene
  17147. * @param size defines the size of the textures
  17148. * @param format defines the format of the data
  17149. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  17150. * @param noMipmap defines if the engine should avoid generating the mip levels
  17151. * @param callback defines a callback used to extract texture data from loaded data
  17152. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  17153. * @param onLoad defines a callback called when texture is loaded
  17154. * @param onError defines a callback called if there is an error
  17155. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  17156. * @param invertY defines if data must be stored with Y axis inverted
  17157. * @returns the cube texture as an InternalTexture
  17158. */
  17159. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
  17160. var _this = this;
  17161. if (onLoad === void 0) { onLoad = null; }
  17162. if (onError === void 0) { onError = null; }
  17163. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  17164. if (invertY === void 0) { invertY = false; }
  17165. var gl = this._gl;
  17166. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  17167. scene._addPendingData(texture);
  17168. texture.url = url;
  17169. this._internalTexturesCache.push(texture);
  17170. var onerror = function (request, exception) {
  17171. scene._removePendingData(texture);
  17172. if (onError && request) {
  17173. onError(request.status + " " + request.statusText, exception);
  17174. }
  17175. };
  17176. var internalCallback = function (data) {
  17177. var width = texture.width;
  17178. var faceDataArrays = callback(data);
  17179. if (!faceDataArrays) {
  17180. return;
  17181. }
  17182. if (mipmapGenerator) {
  17183. var textureType = _this._getWebGLTextureType(type);
  17184. var internalFormat = _this._getInternalFormat(format);
  17185. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  17186. var needConversion = false;
  17187. if (internalFormat === gl.RGB) {
  17188. internalFormat = gl.RGBA;
  17189. needConversion = true;
  17190. }
  17191. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  17192. _this._unpackFlipY(false);
  17193. var mipData = mipmapGenerator(faceDataArrays);
  17194. for (var level = 0; level < mipData.length; level++) {
  17195. var mipSize = width >> level;
  17196. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  17197. var mipFaceData = mipData[level][faceIndex];
  17198. if (needConversion) {
  17199. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  17200. }
  17201. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  17202. }
  17203. }
  17204. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  17205. }
  17206. else {
  17207. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  17208. }
  17209. texture.isReady = true;
  17210. // this.resetTextureCache();
  17211. scene._removePendingData(texture);
  17212. if (onLoad) {
  17213. onLoad();
  17214. }
  17215. };
  17216. this._loadFile(url, function (data) {
  17217. internalCallback(data);
  17218. }, undefined, scene.offlineProvider, true, onerror);
  17219. return texture;
  17220. };
  17221. /**
  17222. * Update a raw 3D texture
  17223. * @param texture defines the texture to update
  17224. * @param data defines the data to store
  17225. * @param format defines the data format
  17226. * @param invertY defines if data must be stored with Y axis inverted
  17227. * @param compression defines the used compression (can be null)
  17228. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  17229. */
  17230. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression, textureType) {
  17231. if (compression === void 0) { compression = null; }
  17232. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  17233. var internalType = this._getWebGLTextureType(textureType);
  17234. var internalFormat = this._getInternalFormat(format);
  17235. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(textureType, format);
  17236. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  17237. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  17238. if (!this._doNotHandleContextLost) {
  17239. texture._bufferView = data;
  17240. texture.format = format;
  17241. texture.invertY = invertY;
  17242. texture._compression = compression;
  17243. }
  17244. if (texture.width % 4 !== 0) {
  17245. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  17246. }
  17247. if (compression && data) {
  17248. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  17249. }
  17250. else {
  17251. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalSizedFomat, texture.width, texture.height, texture.depth, 0, internalFormat, internalType, data);
  17252. }
  17253. if (texture.generateMipMaps) {
  17254. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  17255. }
  17256. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  17257. // this.resetTextureCache();
  17258. texture.isReady = true;
  17259. };
  17260. /**
  17261. * Creates a new raw 3D texture
  17262. * @param data defines the data used to create the texture
  17263. * @param width defines the width of the texture
  17264. * @param height defines the height of the texture
  17265. * @param depth defines the depth of the texture
  17266. * @param format defines the format of the texture
  17267. * @param generateMipMaps defines if the engine must generate mip levels
  17268. * @param invertY defines if data must be stored with Y axis inverted
  17269. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  17270. * @param compression defines the compressed used (can be null)
  17271. * @param textureType defines the compressed used (can be null)
  17272. * @returns a new raw 3D texture (stored in an InternalTexture)
  17273. */
  17274. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression, textureType) {
  17275. if (compression === void 0) { compression = null; }
  17276. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  17277. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  17278. texture.baseWidth = width;
  17279. texture.baseHeight = height;
  17280. texture.baseDepth = depth;
  17281. texture.width = width;
  17282. texture.height = height;
  17283. texture.depth = depth;
  17284. texture.format = format;
  17285. texture.type = textureType;
  17286. texture.generateMipMaps = generateMipMaps;
  17287. texture.samplingMode = samplingMode;
  17288. texture.is3D = true;
  17289. if (!this._doNotHandleContextLost) {
  17290. texture._bufferView = data;
  17291. }
  17292. this.updateRawTexture3D(texture, data, format, invertY, compression, textureType);
  17293. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  17294. // Filters
  17295. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  17296. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  17297. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  17298. if (generateMipMaps) {
  17299. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  17300. }
  17301. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  17302. this._internalTexturesCache.push(texture);
  17303. return texture;
  17304. };
  17305. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  17306. var gl = this._gl;
  17307. if (!gl) {
  17308. return;
  17309. }
  17310. var filters = this._getSamplingParameters(samplingMode, !noMipmap);
  17311. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  17312. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  17313. if (!noMipmap && !isCompressed) {
  17314. gl.generateMipmap(gl.TEXTURE_2D);
  17315. }
  17316. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  17317. // this.resetTextureCache();
  17318. if (scene) {
  17319. scene._removePendingData(texture);
  17320. }
  17321. texture.onLoadedObservable.notifyObservers(texture);
  17322. texture.onLoadedObservable.clear();
  17323. };
  17324. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  17325. var _this = this;
  17326. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  17327. var maxTextureSize = this.getCaps().maxTextureSize;
  17328. var potWidth = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, maxTextureSize) : width);
  17329. var potHeight = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, maxTextureSize) : height);
  17330. var gl = this._gl;
  17331. if (!gl) {
  17332. return;
  17333. }
  17334. if (!texture._webGLTexture) {
  17335. // this.resetTextureCache();
  17336. if (scene) {
  17337. scene._removePendingData(texture);
  17338. }
  17339. return;
  17340. }
  17341. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  17342. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  17343. texture.baseWidth = width;
  17344. texture.baseHeight = height;
  17345. texture.width = potWidth;
  17346. texture.height = potHeight;
  17347. texture.isReady = true;
  17348. if (processFunction(potWidth, potHeight, function () {
  17349. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  17350. })) {
  17351. // Returning as texture needs extra async steps
  17352. return;
  17353. }
  17354. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  17355. };
  17356. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  17357. // Create new RGBA data container.
  17358. var rgbaData;
  17359. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  17360. rgbaData = new Float32Array(width * height * 4);
  17361. }
  17362. else {
  17363. rgbaData = new Uint32Array(width * height * 4);
  17364. }
  17365. // Convert each pixel.
  17366. for (var x = 0; x < width; x++) {
  17367. for (var y = 0; y < height; y++) {
  17368. var index = (y * width + x) * 3;
  17369. var newIndex = (y * width + x) * 4;
  17370. // Map Old Value to new value.
  17371. rgbaData[newIndex + 0] = rgbData[index + 0];
  17372. rgbaData[newIndex + 1] = rgbData[index + 1];
  17373. rgbaData[newIndex + 2] = rgbData[index + 2];
  17374. // Add fully opaque alpha channel.
  17375. rgbaData[newIndex + 3] = 1;
  17376. }
  17377. }
  17378. return rgbaData;
  17379. };
  17380. /** @hidden */
  17381. Engine.prototype._releaseFramebufferObjects = function (texture) {
  17382. var gl = this._gl;
  17383. if (texture._framebuffer) {
  17384. gl.deleteFramebuffer(texture._framebuffer);
  17385. texture._framebuffer = null;
  17386. }
  17387. if (texture._depthStencilBuffer) {
  17388. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  17389. texture._depthStencilBuffer = null;
  17390. }
  17391. if (texture._MSAAFramebuffer) {
  17392. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  17393. texture._MSAAFramebuffer = null;
  17394. }
  17395. if (texture._MSAARenderBuffer) {
  17396. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  17397. texture._MSAARenderBuffer = null;
  17398. }
  17399. };
  17400. /** @hidden */
  17401. Engine.prototype._releaseTexture = function (texture) {
  17402. var gl = this._gl;
  17403. this._releaseFramebufferObjects(texture);
  17404. gl.deleteTexture(texture._webGLTexture);
  17405. // Unbind channels
  17406. this.unbindAllTextures();
  17407. var index = this._internalTexturesCache.indexOf(texture);
  17408. if (index !== -1) {
  17409. this._internalTexturesCache.splice(index, 1);
  17410. }
  17411. // Integrated fixed lod samplers.
  17412. if (texture._lodTextureHigh) {
  17413. texture._lodTextureHigh.dispose();
  17414. }
  17415. if (texture._lodTextureMid) {
  17416. texture._lodTextureMid.dispose();
  17417. }
  17418. if (texture._lodTextureLow) {
  17419. texture._lodTextureLow.dispose();
  17420. }
  17421. // Set output texture of post process to null if the texture has been released/disposed
  17422. this.scenes.forEach(function (scene) {
  17423. scene.postProcesses.forEach(function (postProcess) {
  17424. if (postProcess._outputTexture == texture) {
  17425. postProcess._outputTexture = null;
  17426. }
  17427. });
  17428. scene.cameras.forEach(function (camera) {
  17429. camera._postProcesses.forEach(function (postProcess) {
  17430. if (postProcess) {
  17431. if (postProcess._outputTexture == texture) {
  17432. postProcess._outputTexture = null;
  17433. }
  17434. }
  17435. });
  17436. });
  17437. });
  17438. };
  17439. Engine.prototype.setProgram = function (program) {
  17440. if (this._currentProgram !== program) {
  17441. this._gl.useProgram(program);
  17442. this._currentProgram = program;
  17443. }
  17444. };
  17445. /**
  17446. * Binds an effect to the webGL context
  17447. * @param effect defines the effect to bind
  17448. */
  17449. Engine.prototype.bindSamplers = function (effect) {
  17450. this.setProgram(effect.getProgram());
  17451. var samplers = effect.getSamplers();
  17452. for (var index = 0; index < samplers.length; index++) {
  17453. var uniform = effect.getUniform(samplers[index]);
  17454. if (uniform) {
  17455. this._boundUniforms[index] = uniform;
  17456. }
  17457. }
  17458. this._currentEffect = null;
  17459. };
  17460. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  17461. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  17462. return;
  17463. }
  17464. // Remove
  17465. this._linkTrackers(internalTexture.previous, internalTexture.next);
  17466. // Bind last to it
  17467. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  17468. // Bind to dummy
  17469. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  17470. };
  17471. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  17472. if (!internalTexture) {
  17473. return -1;
  17474. }
  17475. internalTexture._initialSlot = channel;
  17476. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  17477. if (channel !== internalTexture._designatedSlot) {
  17478. this._textureCollisions.addCount(1, false);
  17479. }
  17480. }
  17481. else {
  17482. if (channel !== internalTexture._designatedSlot) {
  17483. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  17484. return internalTexture._designatedSlot;
  17485. }
  17486. else {
  17487. // No slot for this texture, let's pick a new one (if we find a free slot)
  17488. if (this._nextFreeTextureSlots.length) {
  17489. return this._nextFreeTextureSlots[0];
  17490. }
  17491. // We need to recycle the oldest bound texture, sorry.
  17492. this._textureCollisions.addCount(1, false);
  17493. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  17494. }
  17495. }
  17496. }
  17497. return channel;
  17498. };
  17499. Engine.prototype._linkTrackers = function (previous, next) {
  17500. previous.next = next;
  17501. next.previous = previous;
  17502. };
  17503. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  17504. var currentSlot = internalTexture._designatedSlot;
  17505. if (currentSlot === -1) {
  17506. return -1;
  17507. }
  17508. internalTexture._designatedSlot = -1;
  17509. if (this.disableTextureBindingOptimization) {
  17510. return -1;
  17511. }
  17512. // Remove from bound list
  17513. this._linkTrackers(internalTexture.previous, internalTexture.next);
  17514. // Free the slot
  17515. this._boundTexturesCache[currentSlot] = null;
  17516. this._nextFreeTextureSlots.push(currentSlot);
  17517. return currentSlot;
  17518. };
  17519. Engine.prototype._activateCurrentTexture = function () {
  17520. if (this._currentTextureChannel !== this._activeChannel) {
  17521. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  17522. this._currentTextureChannel = this._activeChannel;
  17523. }
  17524. };
  17525. /** @hidden */
  17526. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate, force) {
  17527. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  17528. if (force === void 0) { force = false; }
  17529. var wasPreviouslyBound = false;
  17530. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  17531. this._activeChannel = texture._designatedSlot;
  17532. }
  17533. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  17534. var isTextureForRendering = texture && texture._initialSlot > -1;
  17535. if (currentTextureBound !== texture || force) {
  17536. if (currentTextureBound) {
  17537. this._removeDesignatedSlot(currentTextureBound);
  17538. }
  17539. this._activateCurrentTexture();
  17540. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  17541. this._boundTexturesCache[this._activeChannel] = texture;
  17542. if (texture) {
  17543. if (!this.disableTextureBindingOptimization) {
  17544. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  17545. if (slotIndex > -1) {
  17546. this._nextFreeTextureSlots.splice(slotIndex, 1);
  17547. }
  17548. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  17549. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  17550. }
  17551. texture._designatedSlot = this._activeChannel;
  17552. }
  17553. }
  17554. else if (forTextureDataUpdate) {
  17555. wasPreviouslyBound = true;
  17556. this._activateCurrentTexture();
  17557. }
  17558. if (isTextureForRendering && !forTextureDataUpdate) {
  17559. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  17560. }
  17561. return wasPreviouslyBound;
  17562. };
  17563. /** @hidden */
  17564. Engine.prototype._bindTexture = function (channel, texture) {
  17565. if (channel < 0) {
  17566. return;
  17567. }
  17568. if (texture) {
  17569. channel = this._getCorrectTextureChannel(channel, texture);
  17570. }
  17571. this._activeChannel = channel;
  17572. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  17573. };
  17574. /**
  17575. * Sets a texture to the webGL context from a postprocess
  17576. * @param channel defines the channel to use
  17577. * @param postProcess defines the source postprocess
  17578. */
  17579. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  17580. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  17581. };
  17582. /**
  17583. * Binds the output of the passed in post process to the texture channel specified
  17584. * @param channel The channel the texture should be bound to
  17585. * @param postProcess The post process which's output should be bound
  17586. */
  17587. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  17588. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  17589. };
  17590. /**
  17591. * Unbind all textures from the webGL context
  17592. */
  17593. Engine.prototype.unbindAllTextures = function () {
  17594. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  17595. this._activeChannel = channel;
  17596. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  17597. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  17598. if (this.webGLVersion > 1) {
  17599. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  17600. }
  17601. }
  17602. };
  17603. /**
  17604. * Sets a texture to the according uniform.
  17605. * @param channel The texture channel
  17606. * @param uniform The uniform to set
  17607. * @param texture The texture to apply
  17608. */
  17609. Engine.prototype.setTexture = function (channel, uniform, texture) {
  17610. if (channel < 0) {
  17611. return;
  17612. }
  17613. if (uniform) {
  17614. this._boundUniforms[channel] = uniform;
  17615. }
  17616. this._setTexture(channel, texture);
  17617. };
  17618. /**
  17619. * Sets a depth stencil texture from a render target to the according uniform.
  17620. * @param channel The texture channel
  17621. * @param uniform The uniform to set
  17622. * @param texture The render target texture containing the depth stencil texture to apply
  17623. */
  17624. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  17625. if (channel < 0) {
  17626. return;
  17627. }
  17628. if (uniform) {
  17629. this._boundUniforms[channel] = uniform;
  17630. }
  17631. if (!texture || !texture.depthStencilTexture) {
  17632. this._setTexture(channel, null);
  17633. }
  17634. else {
  17635. this._setTexture(channel, texture, false, true);
  17636. }
  17637. };
  17638. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  17639. var uniform = this._boundUniforms[sourceSlot];
  17640. if (uniform._currentState === destination) {
  17641. return;
  17642. }
  17643. this._gl.uniform1i(uniform, destination);
  17644. uniform._currentState = destination;
  17645. };
  17646. Engine.prototype._getTextureWrapMode = function (mode) {
  17647. switch (mode) {
  17648. case Engine.TEXTURE_WRAP_ADDRESSMODE:
  17649. return this._gl.REPEAT;
  17650. case Engine.TEXTURE_CLAMP_ADDRESSMODE:
  17651. return this._gl.CLAMP_TO_EDGE;
  17652. case Engine.TEXTURE_MIRROR_ADDRESSMODE:
  17653. return this._gl.MIRRORED_REPEAT;
  17654. }
  17655. return this._gl.REPEAT;
  17656. };
  17657. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  17658. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  17659. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  17660. // Not ready?
  17661. if (!texture) {
  17662. if (this._boundTexturesCache[channel] != null) {
  17663. this._activeChannel = channel;
  17664. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  17665. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  17666. if (this.webGLVersion > 1) {
  17667. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  17668. }
  17669. }
  17670. return false;
  17671. }
  17672. // Video
  17673. if (texture.video) {
  17674. this._activeChannel = channel;
  17675. texture.update();
  17676. }
  17677. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  17678. texture.delayLoad();
  17679. return false;
  17680. }
  17681. var internalTexture;
  17682. if (depthStencilTexture) {
  17683. internalTexture = texture.depthStencilTexture;
  17684. }
  17685. else if (texture.isReady()) {
  17686. internalTexture = texture.getInternalTexture();
  17687. }
  17688. else if (texture.isCube) {
  17689. internalTexture = this.emptyCubeTexture;
  17690. }
  17691. else if (texture.is3D) {
  17692. internalTexture = this.emptyTexture3D;
  17693. }
  17694. else {
  17695. internalTexture = this.emptyTexture;
  17696. }
  17697. if (!isPartOfTextureArray) {
  17698. channel = this._getCorrectTextureChannel(channel, internalTexture);
  17699. }
  17700. var needToBind = true;
  17701. if (this._boundTexturesCache[channel] === internalTexture) {
  17702. this._moveBoundTextureOnTop(internalTexture);
  17703. if (!isPartOfTextureArray) {
  17704. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  17705. }
  17706. needToBind = false;
  17707. }
  17708. this._activeChannel = channel;
  17709. if (internalTexture && internalTexture.is3D) {
  17710. if (needToBind) {
  17711. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  17712. }
  17713. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  17714. internalTexture._cachedWrapU = texture.wrapU;
  17715. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  17716. }
  17717. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  17718. internalTexture._cachedWrapV = texture.wrapV;
  17719. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  17720. }
  17721. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  17722. internalTexture._cachedWrapR = texture.wrapR;
  17723. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  17724. }
  17725. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  17726. }
  17727. else if (internalTexture && internalTexture.isCube) {
  17728. if (needToBind) {
  17729. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  17730. }
  17731. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  17732. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  17733. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  17734. var textureWrapMode = (texture.coordinatesMode !== Engine.TEXTURE_CUBIC_MODE && texture.coordinatesMode !== Engine.TEXTURE_SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  17735. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  17736. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  17737. }
  17738. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  17739. }
  17740. else {
  17741. if (needToBind) {
  17742. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  17743. }
  17744. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  17745. internalTexture._cachedWrapU = texture.wrapU;
  17746. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  17747. }
  17748. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  17749. internalTexture._cachedWrapV = texture.wrapV;
  17750. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  17751. }
  17752. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  17753. }
  17754. return true;
  17755. };
  17756. /**
  17757. * Sets an array of texture to the webGL context
  17758. * @param channel defines the channel where the texture array must be set
  17759. * @param uniform defines the associated uniform location
  17760. * @param textures defines the array of textures to bind
  17761. */
  17762. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  17763. if (channel < 0 || !uniform) {
  17764. return;
  17765. }
  17766. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  17767. this._textureUnits = new Int32Array(textures.length);
  17768. }
  17769. for (var i = 0; i < textures.length; i++) {
  17770. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  17771. }
  17772. this._gl.uniform1iv(uniform, this._textureUnits);
  17773. for (var index = 0; index < textures.length; index++) {
  17774. this._setTexture(this._textureUnits[index], textures[index], true);
  17775. }
  17776. };
  17777. /** @hidden */
  17778. Engine.prototype._setAnisotropicLevel = function (target, texture) {
  17779. var internalTexture = texture.getInternalTexture();
  17780. if (!internalTexture) {
  17781. return;
  17782. }
  17783. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  17784. var value = texture.anisotropicFilteringLevel;
  17785. if (internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST
  17786. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR
  17787. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR) {
  17788. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  17789. }
  17790. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  17791. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  17792. internalTexture._cachedAnisotropicFilteringLevel = value;
  17793. }
  17794. };
  17795. Engine.prototype._setTextureParameterFloat = function (target, parameter, value, texture) {
  17796. this._bindTextureDirectly(target, texture, true, true);
  17797. this._gl.texParameterf(target, parameter, value);
  17798. };
  17799. Engine.prototype._setTextureParameterInteger = function (target, parameter, value, texture) {
  17800. if (texture) {
  17801. this._bindTextureDirectly(target, texture, true, true);
  17802. }
  17803. this._gl.texParameteri(target, parameter, value);
  17804. };
  17805. /**
  17806. * Reads pixels from the current frame buffer. Please note that this function can be slow
  17807. * @param x defines the x coordinate of the rectangle where pixels must be read
  17808. * @param y defines the y coordinate of the rectangle where pixels must be read
  17809. * @param width defines the width of the rectangle where pixels must be read
  17810. * @param height defines the height of the rectangle where pixels must be read
  17811. * @returns a Uint8Array containing RGBA colors
  17812. */
  17813. Engine.prototype.readPixels = function (x, y, width, height) {
  17814. var data = new Uint8Array(height * width * 4);
  17815. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  17816. return data;
  17817. };
  17818. /**
  17819. * Add an externaly attached data from its key.
  17820. * This method call will fail and return false, if such key already exists.
  17821. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  17822. * @param key the unique key that identifies the data
  17823. * @param data the data object to associate to the key for this Engine instance
  17824. * @return true if no such key were already present and the data was added successfully, false otherwise
  17825. */
  17826. Engine.prototype.addExternalData = function (key, data) {
  17827. if (!this._externalData) {
  17828. this._externalData = new BABYLON.StringDictionary();
  17829. }
  17830. return this._externalData.add(key, data);
  17831. };
  17832. /**
  17833. * Get an externaly attached data from its key
  17834. * @param key the unique key that identifies the data
  17835. * @return the associated data, if present (can be null), or undefined if not present
  17836. */
  17837. Engine.prototype.getExternalData = function (key) {
  17838. if (!this._externalData) {
  17839. this._externalData = new BABYLON.StringDictionary();
  17840. }
  17841. return this._externalData.get(key);
  17842. };
  17843. /**
  17844. * Get an externaly attached data from its key, create it using a factory if it's not already present
  17845. * @param key the unique key that identifies the data
  17846. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  17847. * @return the associated data, can be null if the factory returned null.
  17848. */
  17849. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  17850. if (!this._externalData) {
  17851. this._externalData = new BABYLON.StringDictionary();
  17852. }
  17853. return this._externalData.getOrAddWithFactory(key, factory);
  17854. };
  17855. /**
  17856. * Remove an externaly attached data from the Engine instance
  17857. * @param key the unique key that identifies the data
  17858. * @return true if the data was successfully removed, false if it doesn't exist
  17859. */
  17860. Engine.prototype.removeExternalData = function (key) {
  17861. if (!this._externalData) {
  17862. this._externalData = new BABYLON.StringDictionary();
  17863. }
  17864. return this._externalData.remove(key);
  17865. };
  17866. /**
  17867. * Unbind all vertex attributes from the webGL context
  17868. */
  17869. Engine.prototype.unbindAllAttributes = function () {
  17870. if (this._mustWipeVertexAttributes) {
  17871. this._mustWipeVertexAttributes = false;
  17872. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  17873. this._gl.disableVertexAttribArray(i);
  17874. this._vertexAttribArraysEnabled[i] = false;
  17875. this._currentBufferPointers[i].active = false;
  17876. }
  17877. return;
  17878. }
  17879. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  17880. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  17881. continue;
  17882. }
  17883. this._gl.disableVertexAttribArray(i);
  17884. this._vertexAttribArraysEnabled[i] = false;
  17885. this._currentBufferPointers[i].active = false;
  17886. }
  17887. };
  17888. /**
  17889. * 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
  17890. */
  17891. Engine.prototype.releaseEffects = function () {
  17892. for (var name in this._compiledEffects) {
  17893. this._deleteProgram(this._compiledEffects[name]._program);
  17894. }
  17895. this._compiledEffects = {};
  17896. };
  17897. /**
  17898. * Dispose and release all associated resources
  17899. */
  17900. Engine.prototype.dispose = function () {
  17901. this.hideLoadingUI();
  17902. this.stopRenderLoop();
  17903. this.onNewSceneAddedObservable.clear();
  17904. // Release postProcesses
  17905. while (this.postProcesses.length) {
  17906. this.postProcesses[0].dispose();
  17907. }
  17908. // Empty texture
  17909. if (this._emptyTexture) {
  17910. this._releaseTexture(this._emptyTexture);
  17911. this._emptyTexture = null;
  17912. }
  17913. if (this._emptyCubeTexture) {
  17914. this._releaseTexture(this._emptyCubeTexture);
  17915. this._emptyCubeTexture = null;
  17916. }
  17917. // Rescale PP
  17918. if (this._rescalePostProcess) {
  17919. this._rescalePostProcess.dispose();
  17920. }
  17921. // Release scenes
  17922. while (this.scenes.length) {
  17923. this.scenes[0].dispose();
  17924. }
  17925. // Release audio engine
  17926. if (Engine.Instances.length === 1 && Engine.audioEngine) {
  17927. Engine.audioEngine.dispose();
  17928. }
  17929. // Release effects
  17930. this.releaseEffects();
  17931. // Unbind
  17932. this.unbindAllAttributes();
  17933. this._boundUniforms = [];
  17934. if (this._dummyFramebuffer) {
  17935. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  17936. }
  17937. //WebVR
  17938. this.disableVR();
  17939. // Events
  17940. if (BABYLON.Tools.IsWindowObjectExist()) {
  17941. window.removeEventListener("blur", this._onBlur);
  17942. window.removeEventListener("focus", this._onFocus);
  17943. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  17944. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  17945. if (this._renderingCanvas) {
  17946. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  17947. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  17948. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  17949. if (!this._doNotHandleContextLost) {
  17950. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  17951. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  17952. }
  17953. }
  17954. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  17955. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  17956. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  17957. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  17958. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  17959. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  17960. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  17961. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  17962. if (this._onVrDisplayConnect) {
  17963. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  17964. if (this._onVrDisplayDisconnect) {
  17965. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  17966. }
  17967. if (this._onVrDisplayPresentChange) {
  17968. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  17969. }
  17970. this._onVrDisplayConnect = null;
  17971. this._onVrDisplayDisconnect = null;
  17972. }
  17973. }
  17974. // Remove from Instances
  17975. var index = Engine.Instances.indexOf(this);
  17976. if (index >= 0) {
  17977. Engine.Instances.splice(index, 1);
  17978. }
  17979. this._workingCanvas = null;
  17980. this._workingContext = null;
  17981. this._currentBufferPointers = [];
  17982. this._renderingCanvas = null;
  17983. this._currentProgram = null;
  17984. this._bindedRenderFunction = null;
  17985. this.onResizeObservable.clear();
  17986. this.onCanvasBlurObservable.clear();
  17987. this.onCanvasFocusObservable.clear();
  17988. this.onCanvasPointerOutObservable.clear();
  17989. this.onBeginFrameObservable.clear();
  17990. this.onEndFrameObservable.clear();
  17991. BABYLON.Effect.ResetCache();
  17992. // Abort active requests
  17993. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  17994. var request = _a[_i];
  17995. request.abort();
  17996. }
  17997. };
  17998. // Loading screen
  17999. /**
  18000. * Display the loading screen
  18001. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  18002. */
  18003. Engine.prototype.displayLoadingUI = function () {
  18004. if (!BABYLON.Tools.IsWindowObjectExist()) {
  18005. return;
  18006. }
  18007. var loadingScreen = this.loadingScreen;
  18008. if (loadingScreen) {
  18009. loadingScreen.displayLoadingUI();
  18010. }
  18011. };
  18012. /**
  18013. * Hide the loading screen
  18014. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  18015. */
  18016. Engine.prototype.hideLoadingUI = function () {
  18017. if (!BABYLON.Tools.IsWindowObjectExist()) {
  18018. return;
  18019. }
  18020. var loadingScreen = this.loadingScreen;
  18021. if (loadingScreen) {
  18022. loadingScreen.hideLoadingUI();
  18023. }
  18024. };
  18025. Object.defineProperty(Engine.prototype, "loadingScreen", {
  18026. /**
  18027. * Gets the current loading screen object
  18028. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  18029. */
  18030. get: function () {
  18031. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas) {
  18032. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  18033. }
  18034. return this._loadingScreen;
  18035. },
  18036. /**
  18037. * Sets the current loading screen object
  18038. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  18039. */
  18040. set: function (loadingScreen) {
  18041. this._loadingScreen = loadingScreen;
  18042. },
  18043. enumerable: true,
  18044. configurable: true
  18045. });
  18046. Object.defineProperty(Engine.prototype, "loadingUIText", {
  18047. /**
  18048. * Sets the current loading screen text
  18049. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  18050. */
  18051. set: function (text) {
  18052. this.loadingScreen.loadingUIText = text;
  18053. },
  18054. enumerable: true,
  18055. configurable: true
  18056. });
  18057. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  18058. /**
  18059. * Sets the current loading screen background color
  18060. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  18061. */
  18062. set: function (color) {
  18063. this.loadingScreen.loadingUIBackgroundColor = color;
  18064. },
  18065. enumerable: true,
  18066. configurable: true
  18067. });
  18068. /**
  18069. * Attach a new callback raised when context lost event is fired
  18070. * @param callback defines the callback to call
  18071. */
  18072. Engine.prototype.attachContextLostEvent = function (callback) {
  18073. if (this._renderingCanvas) {
  18074. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  18075. }
  18076. };
  18077. /**
  18078. * Attach a new callback raised when context restored event is fired
  18079. * @param callback defines the callback to call
  18080. */
  18081. Engine.prototype.attachContextRestoredEvent = function (callback) {
  18082. if (this._renderingCanvas) {
  18083. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  18084. }
  18085. };
  18086. /**
  18087. * Gets the source code of the vertex shader associated with a specific webGL program
  18088. * @param program defines the program to use
  18089. * @returns a string containing the source code of the vertex shader associated with the program
  18090. */
  18091. Engine.prototype.getVertexShaderSource = function (program) {
  18092. var shaders = this._gl.getAttachedShaders(program);
  18093. if (!shaders) {
  18094. return null;
  18095. }
  18096. return this._gl.getShaderSource(shaders[0]);
  18097. };
  18098. /**
  18099. * Gets the source code of the fragment shader associated with a specific webGL program
  18100. * @param program defines the program to use
  18101. * @returns a string containing the source code of the fragment shader associated with the program
  18102. */
  18103. Engine.prototype.getFragmentShaderSource = function (program) {
  18104. var shaders = this._gl.getAttachedShaders(program);
  18105. if (!shaders) {
  18106. return null;
  18107. }
  18108. return this._gl.getShaderSource(shaders[1]);
  18109. };
  18110. /**
  18111. * Get the current error code of the webGL context
  18112. * @returns the error code
  18113. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  18114. */
  18115. Engine.prototype.getError = function () {
  18116. return this._gl.getError();
  18117. };
  18118. // FPS
  18119. /**
  18120. * Gets the current framerate
  18121. * @returns a number representing the framerate
  18122. */
  18123. Engine.prototype.getFps = function () {
  18124. return this._fps;
  18125. };
  18126. /**
  18127. * Gets the time spent between current and previous frame
  18128. * @returns a number representing the delta time in ms
  18129. */
  18130. Engine.prototype.getDeltaTime = function () {
  18131. return this._deltaTime;
  18132. };
  18133. Engine.prototype._measureFps = function () {
  18134. this._performanceMonitor.sampleFrame();
  18135. this._fps = this._performanceMonitor.averageFPS;
  18136. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  18137. };
  18138. /** @hidden */
  18139. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex, level, buffer) {
  18140. if (faceIndex === void 0) { faceIndex = -1; }
  18141. if (level === void 0) { level = 0; }
  18142. if (buffer === void 0) { buffer = null; }
  18143. var gl = this._gl;
  18144. if (!this._dummyFramebuffer) {
  18145. var dummy = gl.createFramebuffer();
  18146. if (!dummy) {
  18147. throw new Error("Unable to create dummy framebuffer");
  18148. }
  18149. this._dummyFramebuffer = dummy;
  18150. }
  18151. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  18152. if (faceIndex > -1) {
  18153. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, level);
  18154. }
  18155. else {
  18156. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, level);
  18157. }
  18158. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  18159. switch (readType) {
  18160. case gl.UNSIGNED_BYTE:
  18161. if (!buffer) {
  18162. buffer = new Uint8Array(4 * width * height);
  18163. }
  18164. readType = gl.UNSIGNED_BYTE;
  18165. break;
  18166. default:
  18167. if (!buffer) {
  18168. buffer = new Float32Array(4 * width * height);
  18169. }
  18170. readType = gl.FLOAT;
  18171. break;
  18172. }
  18173. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  18174. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  18175. return buffer;
  18176. };
  18177. Engine.prototype._canRenderToFloatFramebuffer = function () {
  18178. if (this._webGLVersion > 1) {
  18179. return this._caps.colorBufferFloat;
  18180. }
  18181. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  18182. };
  18183. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  18184. if (this._webGLVersion > 1) {
  18185. return this._caps.colorBufferFloat;
  18186. }
  18187. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  18188. };
  18189. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  18190. Engine.prototype._canRenderToFramebuffer = function (type) {
  18191. var gl = this._gl;
  18192. //clear existing errors
  18193. while (gl.getError() !== gl.NO_ERROR) { }
  18194. var successful = true;
  18195. var texture = gl.createTexture();
  18196. gl.bindTexture(gl.TEXTURE_2D, texture);
  18197. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  18198. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  18199. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  18200. var fb = gl.createFramebuffer();
  18201. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  18202. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  18203. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  18204. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  18205. successful = successful && (gl.getError() === gl.NO_ERROR);
  18206. //try render by clearing frame buffer's color buffer
  18207. if (successful) {
  18208. gl.clear(gl.COLOR_BUFFER_BIT);
  18209. successful = successful && (gl.getError() === gl.NO_ERROR);
  18210. }
  18211. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  18212. if (successful) {
  18213. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  18214. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  18215. var readFormat = gl.RGBA;
  18216. var readType = gl.UNSIGNED_BYTE;
  18217. var buffer = new Uint8Array(4);
  18218. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  18219. successful = successful && (gl.getError() === gl.NO_ERROR);
  18220. }
  18221. //clean up
  18222. gl.deleteTexture(texture);
  18223. gl.deleteFramebuffer(fb);
  18224. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  18225. //clear accumulated errors
  18226. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  18227. return successful;
  18228. };
  18229. /** @hidden */
  18230. Engine.prototype._getWebGLTextureType = function (type) {
  18231. if (this._webGLVersion === 1) {
  18232. switch (type) {
  18233. case Engine.TEXTURETYPE_FLOAT:
  18234. return this._gl.FLOAT;
  18235. case Engine.TEXTURETYPE_HALF_FLOAT:
  18236. return this._gl.HALF_FLOAT_OES;
  18237. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  18238. return this._gl.UNSIGNED_BYTE;
  18239. }
  18240. return this._gl.UNSIGNED_BYTE;
  18241. }
  18242. switch (type) {
  18243. case Engine.TEXTURETYPE_BYTE:
  18244. return this._gl.BYTE;
  18245. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  18246. return this._gl.UNSIGNED_BYTE;
  18247. case Engine.TEXTURETYPE_SHORT:
  18248. return this._gl.SHORT;
  18249. case Engine.TEXTURETYPE_UNSIGNED_SHORT:
  18250. return this._gl.UNSIGNED_SHORT;
  18251. case Engine.TEXTURETYPE_INT:
  18252. return this._gl.INT;
  18253. case Engine.TEXTURETYPE_UNSIGNED_INTEGER: // Refers to UNSIGNED_INT
  18254. return this._gl.UNSIGNED_INT;
  18255. case Engine.TEXTURETYPE_FLOAT:
  18256. return this._gl.FLOAT;
  18257. case Engine.TEXTURETYPE_HALF_FLOAT:
  18258. return this._gl.HALF_FLOAT;
  18259. case Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:
  18260. return this._gl.UNSIGNED_SHORT_4_4_4_4;
  18261. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:
  18262. return this._gl.UNSIGNED_SHORT_5_5_5_1;
  18263. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:
  18264. return this._gl.UNSIGNED_SHORT_5_6_5;
  18265. case Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:
  18266. return this._gl.UNSIGNED_INT_2_10_10_10_REV;
  18267. case Engine.TEXTURETYPE_UNSIGNED_INT_24_8:
  18268. return this._gl.UNSIGNED_INT_24_8;
  18269. case Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:
  18270. return this._gl.UNSIGNED_INT_10F_11F_11F_REV;
  18271. case Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:
  18272. return this._gl.UNSIGNED_INT_5_9_9_9_REV;
  18273. case Engine.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV:
  18274. return this._gl.FLOAT_32_UNSIGNED_INT_24_8_REV;
  18275. }
  18276. return this._gl.UNSIGNED_BYTE;
  18277. };
  18278. Engine.prototype._getInternalFormat = function (format) {
  18279. var internalFormat = this._gl.RGBA;
  18280. switch (format) {
  18281. case Engine.TEXTUREFORMAT_ALPHA:
  18282. internalFormat = this._gl.ALPHA;
  18283. break;
  18284. case Engine.TEXTUREFORMAT_LUMINANCE:
  18285. internalFormat = this._gl.LUMINANCE;
  18286. break;
  18287. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  18288. internalFormat = this._gl.LUMINANCE_ALPHA;
  18289. break;
  18290. case Engine.TEXTUREFORMAT_RED:
  18291. internalFormat = this._gl.RED;
  18292. break;
  18293. case Engine.TEXTUREFORMAT_RG:
  18294. internalFormat = this._gl.RG;
  18295. break;
  18296. case Engine.TEXTUREFORMAT_RGB:
  18297. internalFormat = this._gl.RGB;
  18298. break;
  18299. case Engine.TEXTUREFORMAT_RGBA:
  18300. internalFormat = this._gl.RGBA;
  18301. break;
  18302. }
  18303. if (this._webGLVersion > 1) {
  18304. switch (format) {
  18305. case Engine.TEXTUREFORMAT_RED_INTEGER:
  18306. internalFormat = this._gl.RED_INTEGER;
  18307. break;
  18308. case Engine.TEXTUREFORMAT_RG_INTEGER:
  18309. internalFormat = this._gl.RG_INTEGER;
  18310. break;
  18311. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  18312. internalFormat = this._gl.RGB_INTEGER;
  18313. break;
  18314. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  18315. internalFormat = this._gl.RGBA_INTEGER;
  18316. break;
  18317. }
  18318. }
  18319. return internalFormat;
  18320. };
  18321. /** @hidden */
  18322. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  18323. if (this._webGLVersion === 1) {
  18324. if (format !== undefined) {
  18325. switch (format) {
  18326. case Engine.TEXTUREFORMAT_ALPHA:
  18327. return this._gl.ALPHA;
  18328. case Engine.TEXTUREFORMAT_LUMINANCE:
  18329. return this._gl.LUMINANCE;
  18330. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  18331. return this._gl.LUMINANCE_ALPHA;
  18332. }
  18333. }
  18334. return this._gl.RGBA;
  18335. }
  18336. switch (type) {
  18337. case Engine.TEXTURETYPE_BYTE:
  18338. switch (format) {
  18339. case Engine.TEXTUREFORMAT_RED:
  18340. return this._gl.R8_SNORM;
  18341. case Engine.TEXTUREFORMAT_RG:
  18342. return this._gl.RG8_SNORM;
  18343. case Engine.TEXTUREFORMAT_RGB:
  18344. return this._gl.RGB8_SNORM;
  18345. case Engine.TEXTUREFORMAT_RED_INTEGER:
  18346. return this._gl.R8I;
  18347. case Engine.TEXTUREFORMAT_RG_INTEGER:
  18348. return this._gl.RG8I;
  18349. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  18350. return this._gl.RGB8I;
  18351. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  18352. return this._gl.RGBA8I;
  18353. default:
  18354. return this._gl.RGBA8_SNORM;
  18355. }
  18356. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  18357. switch (format) {
  18358. case Engine.TEXTUREFORMAT_RED:
  18359. return this._gl.R8;
  18360. case Engine.TEXTUREFORMAT_RG:
  18361. return this._gl.RG8;
  18362. case Engine.TEXTUREFORMAT_RGB:
  18363. return this._gl.RGB8; // By default. Other possibilities are RGB565, SRGB8.
  18364. case Engine.TEXTUREFORMAT_RGBA:
  18365. return this._gl.RGBA8; // By default. Other possibilities are RGB5_A1, RGBA4, SRGB8_ALPHA8.
  18366. case Engine.TEXTUREFORMAT_RED_INTEGER:
  18367. return this._gl.R8UI;
  18368. case Engine.TEXTUREFORMAT_RG_INTEGER:
  18369. return this._gl.RG8UI;
  18370. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  18371. return this._gl.RGB8UI;
  18372. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  18373. return this._gl.RGBA8UI;
  18374. default:
  18375. return this._gl.RGBA8;
  18376. }
  18377. case Engine.TEXTURETYPE_SHORT:
  18378. switch (format) {
  18379. case Engine.TEXTUREFORMAT_RED_INTEGER:
  18380. return this._gl.R16I;
  18381. case Engine.TEXTUREFORMAT_RG_INTEGER:
  18382. return this._gl.RG16I;
  18383. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  18384. return this._gl.RGB16I;
  18385. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  18386. return this._gl.RGBA16I;
  18387. default:
  18388. return this._gl.RGBA16I;
  18389. }
  18390. case Engine.TEXTURETYPE_UNSIGNED_SHORT:
  18391. switch (format) {
  18392. case Engine.TEXTUREFORMAT_RED_INTEGER:
  18393. return this._gl.R16UI;
  18394. case Engine.TEXTUREFORMAT_RG_INTEGER:
  18395. return this._gl.RG16UI;
  18396. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  18397. return this._gl.RGB16UI;
  18398. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  18399. return this._gl.RGBA16UI;
  18400. default:
  18401. return this._gl.RGBA16UI;
  18402. }
  18403. case Engine.TEXTURETYPE_INT:
  18404. switch (format) {
  18405. case Engine.TEXTUREFORMAT_RED_INTEGER:
  18406. return this._gl.R32I;
  18407. case Engine.TEXTUREFORMAT_RG_INTEGER:
  18408. return this._gl.RG32I;
  18409. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  18410. return this._gl.RGB32I;
  18411. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  18412. return this._gl.RGBA32I;
  18413. default:
  18414. return this._gl.RGBA32I;
  18415. }
  18416. case Engine.TEXTURETYPE_UNSIGNED_INTEGER: // Refers to UNSIGNED_INT
  18417. switch (format) {
  18418. case Engine.TEXTUREFORMAT_RED_INTEGER:
  18419. return this._gl.R32UI;
  18420. case Engine.TEXTUREFORMAT_RG_INTEGER:
  18421. return this._gl.RG32UI;
  18422. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  18423. return this._gl.RGB32UI;
  18424. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  18425. return this._gl.RGBA32UI;
  18426. default:
  18427. return this._gl.RGBA32UI;
  18428. }
  18429. case Engine.TEXTURETYPE_FLOAT:
  18430. switch (format) {
  18431. case Engine.TEXTUREFORMAT_RED:
  18432. return this._gl.R32F; // By default. Other possibility is R16F.
  18433. case Engine.TEXTUREFORMAT_RG:
  18434. return this._gl.RG32F; // By default. Other possibility is RG16F.
  18435. case Engine.TEXTUREFORMAT_RGB:
  18436. return this._gl.RGB32F; // By default. Other possibilities are RGB16F, R11F_G11F_B10F, RGB9_E5.
  18437. case Engine.TEXTUREFORMAT_RGBA:
  18438. return this._gl.RGBA32F; // By default. Other possibility is RGBA16F.
  18439. default:
  18440. return this._gl.RGBA32F;
  18441. }
  18442. case Engine.TEXTURETYPE_HALF_FLOAT:
  18443. switch (format) {
  18444. case Engine.TEXTUREFORMAT_RED:
  18445. return this._gl.R16F;
  18446. case Engine.TEXTUREFORMAT_RG:
  18447. return this._gl.RG16F;
  18448. case Engine.TEXTUREFORMAT_RGB:
  18449. return this._gl.RGB16F; // By default. Other possibilities are R11F_G11F_B10F, RGB9_E5.
  18450. case Engine.TEXTUREFORMAT_RGBA:
  18451. return this._gl.RGBA16F;
  18452. default:
  18453. return this._gl.RGBA16F;
  18454. }
  18455. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:
  18456. return this._gl.RGB565;
  18457. case Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:
  18458. return this._gl.R11F_G11F_B10F;
  18459. case Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:
  18460. return this._gl.RGB9_E5;
  18461. case Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:
  18462. return this._gl.RGBA4;
  18463. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:
  18464. return this._gl.RGB5_A1;
  18465. case Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:
  18466. switch (format) {
  18467. case Engine.TEXTUREFORMAT_RGBA:
  18468. return this._gl.RGB10_A2; // By default. Other possibility is RGB5_A1.
  18469. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  18470. return this._gl.RGB10_A2UI;
  18471. default:
  18472. return this._gl.RGB10_A2;
  18473. }
  18474. }
  18475. return this._gl.RGBA8;
  18476. };
  18477. /** @hidden */
  18478. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  18479. if (type === Engine.TEXTURETYPE_FLOAT) {
  18480. return this._gl.RGBA32F;
  18481. }
  18482. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  18483. return this._gl.RGBA16F;
  18484. }
  18485. return this._gl.RGBA8;
  18486. };
  18487. /** @hidden */
  18488. Engine.prototype._loadFile = function (url, onSuccess, onProgress, offlineProvider, useArrayBuffer, onError) {
  18489. var _this = this;
  18490. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, offlineProvider, useArrayBuffer, onError);
  18491. this._activeRequests.push(request);
  18492. request.onCompleteObservable.add(function (request) {
  18493. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  18494. });
  18495. return request;
  18496. };
  18497. /** @hidden */
  18498. Engine.prototype._loadFileAsync = function (url, offlineProvider, useArrayBuffer) {
  18499. var _this = this;
  18500. return new Promise(function (resolve, reject) {
  18501. _this._loadFile(url, function (data) {
  18502. resolve(data);
  18503. }, undefined, offlineProvider, useArrayBuffer, function (request, exception) {
  18504. reject(exception);
  18505. });
  18506. });
  18507. };
  18508. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  18509. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  18510. var onload = function (data) {
  18511. loadedFiles[index] = data;
  18512. loadedFiles._internalCount++;
  18513. if (loadedFiles._internalCount === 6) {
  18514. onfinish(loadedFiles);
  18515. }
  18516. };
  18517. var onerror = function (request, exception) {
  18518. if (onErrorCallBack && request) {
  18519. onErrorCallBack(request.status + " " + request.statusText, exception);
  18520. }
  18521. };
  18522. this._loadFile(url, onload, undefined, undefined, true, onerror);
  18523. };
  18524. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  18525. if (onError === void 0) { onError = null; }
  18526. var loadedFiles = [];
  18527. loadedFiles._internalCount = 0;
  18528. for (var index = 0; index < 6; index++) {
  18529. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  18530. }
  18531. };
  18532. // Statics
  18533. /**
  18534. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  18535. * @returns true if the engine can be created
  18536. * @ignorenaming
  18537. */
  18538. Engine.isSupported = function () {
  18539. try {
  18540. var tempcanvas = document.createElement("canvas");
  18541. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  18542. return gl != null && !!window.WebGLRenderingContext;
  18543. }
  18544. catch (e) {
  18545. return false;
  18546. }
  18547. };
  18548. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  18549. Engine.ExceptionList = [
  18550. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  18551. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  18552. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  18553. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  18554. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  18555. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  18556. ];
  18557. /** Gets the list of created engines */
  18558. Engine.Instances = new Array();
  18559. /**
  18560. * Hidden
  18561. */
  18562. Engine._TextureLoaders = [];
  18563. // Const statics
  18564. /** Defines that alpha blending is disabled */
  18565. Engine.ALPHA_DISABLE = 0;
  18566. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  18567. Engine.ALPHA_ADD = 1;
  18568. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  18569. Engine.ALPHA_COMBINE = 2;
  18570. /** Defines that alpha blending to DEST - SRC * DEST */
  18571. Engine.ALPHA_SUBTRACT = 3;
  18572. /** Defines that alpha blending to SRC * DEST */
  18573. Engine.ALPHA_MULTIPLY = 4;
  18574. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  18575. Engine.ALPHA_MAXIMIZED = 5;
  18576. /** Defines that alpha blending to SRC + DEST */
  18577. Engine.ALPHA_ONEONE = 6;
  18578. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  18579. Engine.ALPHA_PREMULTIPLIED = 7;
  18580. /**
  18581. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  18582. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  18583. */
  18584. Engine.ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  18585. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  18586. Engine.ALPHA_INTERPOLATE = 9;
  18587. /**
  18588. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  18589. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  18590. */
  18591. Engine.ALPHA_SCREENMODE = 10;
  18592. /** Defines that the ressource is not delayed*/
  18593. Engine.DELAYLOADSTATE_NONE = 0;
  18594. /** Defines that the ressource was successfully delay loaded */
  18595. Engine.DELAYLOADSTATE_LOADED = 1;
  18596. /** Defines that the ressource is currently delay loading */
  18597. Engine.DELAYLOADSTATE_LOADING = 2;
  18598. /** Defines that the ressource is delayed and has not started loading */
  18599. Engine.DELAYLOADSTATE_NOTLOADED = 4;
  18600. // Depht or Stencil test Constants.
  18601. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  18602. Engine.NEVER = 0x0200;
  18603. /** 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 */
  18604. Engine.ALWAYS = 0x0207;
  18605. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  18606. Engine.LESS = 0x0201;
  18607. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  18608. Engine.EQUAL = 0x0202;
  18609. /** 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 */
  18610. Engine.LEQUAL = 0x0203;
  18611. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  18612. Engine.GREATER = 0x0204;
  18613. /** 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 */
  18614. Engine.GEQUAL = 0x0206;
  18615. /** 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 */
  18616. Engine.NOTEQUAL = 0x0205;
  18617. // Stencil Actions Constants.
  18618. /** Passed to stencilOperation to specify that stencil value must be kept */
  18619. Engine.KEEP = 0x1E00;
  18620. /** Passed to stencilOperation to specify that stencil value must be replaced */
  18621. Engine.REPLACE = 0x1E01;
  18622. /** Passed to stencilOperation to specify that stencil value must be incremented */
  18623. Engine.INCR = 0x1E02;
  18624. /** Passed to stencilOperation to specify that stencil value must be decremented */
  18625. Engine.DECR = 0x1E03;
  18626. /** Passed to stencilOperation to specify that stencil value must be inverted */
  18627. Engine.INVERT = 0x150A;
  18628. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  18629. Engine.INCR_WRAP = 0x8507;
  18630. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  18631. Engine.DECR_WRAP = 0x8508;
  18632. /** Texture is not repeating outside of 0..1 UVs */
  18633. Engine.TEXTURE_CLAMP_ADDRESSMODE = 0;
  18634. /** Texture is repeating outside of 0..1 UVs */
  18635. Engine.TEXTURE_WRAP_ADDRESSMODE = 1;
  18636. /** Texture is repeating and mirrored */
  18637. Engine.TEXTURE_MIRROR_ADDRESSMODE = 2;
  18638. /** ALPHA */
  18639. Engine.TEXTUREFORMAT_ALPHA = 0;
  18640. /** LUMINANCE */
  18641. Engine.TEXTUREFORMAT_LUMINANCE = 1;
  18642. /** LUMINANCE_ALPHA */
  18643. Engine.TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  18644. /** RGB */
  18645. Engine.TEXTUREFORMAT_RGB = 4;
  18646. /** RGBA */
  18647. Engine.TEXTUREFORMAT_RGBA = 5;
  18648. /** RED */
  18649. Engine.TEXTUREFORMAT_RED = 6;
  18650. /** RED (2nd reference) */
  18651. Engine.TEXTUREFORMAT_R = 6;
  18652. /** RG */
  18653. Engine.TEXTUREFORMAT_RG = 7;
  18654. /** RED_INTEGER */
  18655. Engine.TEXTUREFORMAT_RED_INTEGER = 8;
  18656. /** RED_INTEGER (2nd reference) */
  18657. Engine.TEXTUREFORMAT_R_INTEGER = 8;
  18658. /** RG_INTEGER */
  18659. Engine.TEXTUREFORMAT_RG_INTEGER = 9;
  18660. /** RGB_INTEGER */
  18661. Engine.TEXTUREFORMAT_RGB_INTEGER = 10;
  18662. /** RGBA_INTEGER */
  18663. Engine.TEXTUREFORMAT_RGBA_INTEGER = 11;
  18664. /** UNSIGNED_BYTE */
  18665. Engine.TEXTURETYPE_UNSIGNED_BYTE = 0;
  18666. /** UNSIGNED_BYTE (2nd reference) */
  18667. Engine.TEXTURETYPE_UNSIGNED_INT = 0;
  18668. /** FLOAT */
  18669. Engine.TEXTURETYPE_FLOAT = 1;
  18670. /** HALF_FLOAT */
  18671. Engine.TEXTURETYPE_HALF_FLOAT = 2;
  18672. /** BYTE */
  18673. Engine.TEXTURETYPE_BYTE = 3;
  18674. /** SHORT */
  18675. Engine.TEXTURETYPE_SHORT = 4;
  18676. /** UNSIGNED_SHORT */
  18677. Engine.TEXTURETYPE_UNSIGNED_SHORT = 5;
  18678. /** INT */
  18679. Engine.TEXTURETYPE_INT = 6;
  18680. /** UNSIGNED_INT */
  18681. Engine.TEXTURETYPE_UNSIGNED_INTEGER = 7;
  18682. /** UNSIGNED_SHORT_4_4_4_4 */
  18683. Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4 = 8;
  18684. /** UNSIGNED_SHORT_5_5_5_1 */
  18685. Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1 = 9;
  18686. /** UNSIGNED_SHORT_5_6_5 */
  18687. Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5 = 10;
  18688. /** UNSIGNED_INT_2_10_10_10_REV */
  18689. Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV = 11;
  18690. /** UNSIGNED_INT_24_8 */
  18691. Engine.TEXTURETYPE_UNSIGNED_INT_24_8 = 12;
  18692. /** UNSIGNED_INT_10F_11F_11F_REV */
  18693. Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV = 13;
  18694. /** UNSIGNED_INT_5_9_9_9_REV */
  18695. Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV = 14;
  18696. /** FLOAT_32_UNSIGNED_INT_24_8_REV */
  18697. Engine.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV = 15;
  18698. /** nearest is mag = nearest and min = nearest and mip = linear */
  18699. Engine.TEXTURE_NEAREST_SAMPLINGMODE = 1;
  18700. /** Bilinear is mag = linear and min = linear and mip = nearest */
  18701. Engine.TEXTURE_BILINEAR_SAMPLINGMODE = 2;
  18702. /** Trilinear is mag = linear and min = linear and mip = linear */
  18703. Engine.TEXTURE_TRILINEAR_SAMPLINGMODE = 3;
  18704. /** nearest is mag = nearest and min = nearest and mip = linear */
  18705. Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR = 1;
  18706. /** Bilinear is mag = linear and min = linear and mip = nearest */
  18707. Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST = 2;
  18708. /** Trilinear is mag = linear and min = linear and mip = linear */
  18709. Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR = 3;
  18710. /** mag = nearest and min = nearest and mip = nearest */
  18711. Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST = 4;
  18712. /** mag = nearest and min = linear and mip = nearest */
  18713. Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST = 5;
  18714. /** mag = nearest and min = linear and mip = linear */
  18715. Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR = 6;
  18716. /** mag = nearest and min = linear and mip = none */
  18717. Engine.TEXTURE_NEAREST_LINEAR = 7;
  18718. /** mag = nearest and min = nearest and mip = none */
  18719. Engine.TEXTURE_NEAREST_NEAREST = 8;
  18720. /** mag = linear and min = nearest and mip = nearest */
  18721. Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST = 9;
  18722. /** mag = linear and min = nearest and mip = linear */
  18723. Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR = 10;
  18724. /** mag = linear and min = linear and mip = none */
  18725. Engine.TEXTURE_LINEAR_LINEAR = 11;
  18726. /** mag = linear and min = nearest and mip = none */
  18727. Engine.TEXTURE_LINEAR_NEAREST = 12;
  18728. /** Explicit coordinates mode */
  18729. Engine.TEXTURE_EXPLICIT_MODE = 0;
  18730. /** Spherical coordinates mode */
  18731. Engine.TEXTURE_SPHERICAL_MODE = 1;
  18732. /** Planar coordinates mode */
  18733. Engine.TEXTURE_PLANAR_MODE = 2;
  18734. /** Cubic coordinates mode */
  18735. Engine.TEXTURE_CUBIC_MODE = 3;
  18736. /** Projection coordinates mode */
  18737. Engine.TEXTURE_PROJECTION_MODE = 4;
  18738. /** Skybox coordinates mode */
  18739. Engine.TEXTURE_SKYBOX_MODE = 5;
  18740. /** Inverse Cubic coordinates mode */
  18741. Engine.TEXTURE_INVCUBIC_MODE = 6;
  18742. /** Equirectangular coordinates mode */
  18743. Engine.TEXTURE_EQUIRECTANGULAR_MODE = 7;
  18744. /** Equirectangular Fixed coordinates mode */
  18745. Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE = 8;
  18746. /** Equirectangular Fixed Mirrored coordinates mode */
  18747. Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  18748. // Texture rescaling mode
  18749. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  18750. Engine.SCALEMODE_FLOOR = 1;
  18751. /** Defines that texture rescaling will look for the nearest power of 2 size */
  18752. Engine.SCALEMODE_NEAREST = 2;
  18753. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  18754. Engine.SCALEMODE_CEILING = 3;
  18755. // Updatable statics so stick with vars here
  18756. /**
  18757. * Gets or sets the epsilon value used by collision engine
  18758. */
  18759. Engine.CollisionsEpsilon = 0.001;
  18760. /**
  18761. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  18762. */
  18763. Engine.CodeRepository = "src/";
  18764. /**
  18765. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  18766. */
  18767. Engine.ShadersRepository = "src/Shaders/";
  18768. return Engine;
  18769. }());
  18770. BABYLON.Engine = Engine;
  18771. })(BABYLON || (BABYLON = {}));
  18772. //# sourceMappingURL=babylon.engine.js.map
  18773. var BABYLON;
  18774. (function (BABYLON) {
  18775. /**
  18776. * Node is the basic class for all scene objects (Mesh, Light, Camera.)
  18777. */
  18778. var Node = /** @class */ (function () {
  18779. /**
  18780. * Creates a new Node
  18781. * @param name the name and id to be given to this node
  18782. * @param scene the scene this node will be added to
  18783. * @param addToRootNodes the node will be added to scene.rootNodes
  18784. */
  18785. function Node(name, scene, addToRootNodes) {
  18786. if (scene === void 0) { scene = null; }
  18787. if (addToRootNodes === void 0) { addToRootNodes = true; }
  18788. /**
  18789. * Gets or sets a string used to store user defined state for the node
  18790. */
  18791. this.state = "";
  18792. /**
  18793. * Gets or sets an object used to store user defined information for the node
  18794. */
  18795. this.metadata = null;
  18796. /**
  18797. * For internal use only. Please do not use.
  18798. */
  18799. this.reservedDataStore = null;
  18800. /**
  18801. * Gets or sets a boolean used to define if the node must be serialized
  18802. */
  18803. this.doNotSerialize = false;
  18804. /** @hidden */
  18805. this._isDisposed = false;
  18806. /**
  18807. * Gets a list of Animations associated with the node
  18808. */
  18809. this.animations = new Array();
  18810. this._ranges = {};
  18811. this._isEnabled = true;
  18812. this._isParentEnabled = true;
  18813. this._isReady = true;
  18814. /** @hidden */
  18815. this._currentRenderId = -1;
  18816. this._parentRenderId = -1;
  18817. this._childRenderId = -1;
  18818. /** @hidden */
  18819. this._worldMatrix = BABYLON.Matrix.Identity();
  18820. /** @hidden */
  18821. this._worldMatrixDeterminant = 0;
  18822. /** @hidden */
  18823. this._sceneRootNodesIndex = -1;
  18824. this._animationPropertiesOverride = null;
  18825. /**
  18826. * An event triggered when the mesh is disposed
  18827. */
  18828. this.onDisposeObservable = new BABYLON.Observable();
  18829. // Behaviors
  18830. this._behaviors = new Array();
  18831. this.name = name;
  18832. this.id = name;
  18833. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  18834. this.uniqueId = this._scene.getUniqueId();
  18835. this._initCache();
  18836. if (addToRootNodes) {
  18837. this.addToSceneRootNodes();
  18838. }
  18839. }
  18840. /**
  18841. * Add a new node constructor
  18842. * @param type defines the type name of the node to construct
  18843. * @param constructorFunc defines the constructor function
  18844. */
  18845. Node.AddNodeConstructor = function (type, constructorFunc) {
  18846. this._NodeConstructors[type] = constructorFunc;
  18847. };
  18848. /**
  18849. * Returns a node constructor based on type name
  18850. * @param type defines the type name
  18851. * @param name defines the new node name
  18852. * @param scene defines the hosting scene
  18853. * @param options defines optional options to transmit to constructors
  18854. * @returns the new constructor or null
  18855. */
  18856. Node.Construct = function (type, name, scene, options) {
  18857. var constructorFunc = this._NodeConstructors[type];
  18858. if (!constructorFunc) {
  18859. return null;
  18860. }
  18861. return constructorFunc(name, scene, options);
  18862. };
  18863. /**
  18864. * Gets a boolean indicating if the node has been disposed
  18865. * @returns true if the node was disposed
  18866. */
  18867. Node.prototype.isDisposed = function () {
  18868. return this._isDisposed;
  18869. };
  18870. Object.defineProperty(Node.prototype, "parent", {
  18871. get: function () {
  18872. return this._parentNode;
  18873. },
  18874. /**
  18875. * Gets or sets the parent of the node
  18876. */
  18877. set: function (parent) {
  18878. if (this._parentNode === parent) {
  18879. return;
  18880. }
  18881. var previousParentNode = this._parentNode;
  18882. // Remove self from list of children of parent
  18883. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  18884. var index = this._parentNode._children.indexOf(this);
  18885. if (index !== -1) {
  18886. this._parentNode._children.splice(index, 1);
  18887. }
  18888. if (!parent && !this._isDisposed) {
  18889. this.addToSceneRootNodes();
  18890. }
  18891. }
  18892. // Store new parent
  18893. this._parentNode = parent;
  18894. // Add as child to new parent
  18895. if (this._parentNode) {
  18896. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  18897. this._parentNode._children = new Array();
  18898. }
  18899. this._parentNode._children.push(this);
  18900. if (!previousParentNode) {
  18901. this.removeFromSceneRootNodes();
  18902. }
  18903. }
  18904. // Enabled state
  18905. this._syncParentEnabledState();
  18906. },
  18907. enumerable: true,
  18908. configurable: true
  18909. });
  18910. Node.prototype.addToSceneRootNodes = function () {
  18911. if (this._sceneRootNodesIndex === -1) {
  18912. this._sceneRootNodesIndex = this._scene.rootNodes.length;
  18913. this._scene.rootNodes.push(this);
  18914. }
  18915. };
  18916. Node.prototype.removeFromSceneRootNodes = function () {
  18917. if (this._sceneRootNodesIndex !== -1) {
  18918. var rootNodes = this._scene.rootNodes;
  18919. var lastIdx = rootNodes.length - 1;
  18920. rootNodes[this._sceneRootNodesIndex] = rootNodes[lastIdx];
  18921. rootNodes[this._sceneRootNodesIndex]._sceneRootNodesIndex = this._sceneRootNodesIndex;
  18922. this._scene.rootNodes.pop();
  18923. this._sceneRootNodesIndex = -1;
  18924. }
  18925. };
  18926. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  18927. /**
  18928. * Gets or sets the animation properties override
  18929. */
  18930. get: function () {
  18931. if (!this._animationPropertiesOverride) {
  18932. return this._scene.animationPropertiesOverride;
  18933. }
  18934. return this._animationPropertiesOverride;
  18935. },
  18936. set: function (value) {
  18937. this._animationPropertiesOverride = value;
  18938. },
  18939. enumerable: true,
  18940. configurable: true
  18941. });
  18942. /**
  18943. * Gets a string idenfifying the name of the class
  18944. * @returns "Node" string
  18945. */
  18946. Node.prototype.getClassName = function () {
  18947. return "Node";
  18948. };
  18949. Object.defineProperty(Node.prototype, "onDispose", {
  18950. /**
  18951. * Sets a callback that will be raised when the node will be disposed
  18952. */
  18953. set: function (callback) {
  18954. if (this._onDisposeObserver) {
  18955. this.onDisposeObservable.remove(this._onDisposeObserver);
  18956. }
  18957. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  18958. },
  18959. enumerable: true,
  18960. configurable: true
  18961. });
  18962. /**
  18963. * Gets the scene of the node
  18964. * @returns a scene
  18965. */
  18966. Node.prototype.getScene = function () {
  18967. return this._scene;
  18968. };
  18969. /**
  18970. * Gets the engine of the node
  18971. * @returns a Engine
  18972. */
  18973. Node.prototype.getEngine = function () {
  18974. return this._scene.getEngine();
  18975. };
  18976. /**
  18977. * Attach a behavior to the node
  18978. * @see http://doc.babylonjs.com/features/behaviour
  18979. * @param behavior defines the behavior to attach
  18980. * @param attachImmediately defines that the behavior must be attached even if the scene is still loading
  18981. * @returns the current Node
  18982. */
  18983. Node.prototype.addBehavior = function (behavior, attachImmediately) {
  18984. var _this = this;
  18985. if (attachImmediately === void 0) { attachImmediately = false; }
  18986. var index = this._behaviors.indexOf(behavior);
  18987. if (index !== -1) {
  18988. return this;
  18989. }
  18990. behavior.init();
  18991. if (this._scene.isLoading && !attachImmediately) {
  18992. // We defer the attach when the scene will be loaded
  18993. this._scene.onDataLoadedObservable.addOnce(function () {
  18994. behavior.attach(_this);
  18995. });
  18996. }
  18997. else {
  18998. behavior.attach(this);
  18999. }
  19000. this._behaviors.push(behavior);
  19001. return this;
  19002. };
  19003. /**
  19004. * Remove an attached behavior
  19005. * @see http://doc.babylonjs.com/features/behaviour
  19006. * @param behavior defines the behavior to attach
  19007. * @returns the current Node
  19008. */
  19009. Node.prototype.removeBehavior = function (behavior) {
  19010. var index = this._behaviors.indexOf(behavior);
  19011. if (index === -1) {
  19012. return this;
  19013. }
  19014. this._behaviors[index].detach();
  19015. this._behaviors.splice(index, 1);
  19016. return this;
  19017. };
  19018. Object.defineProperty(Node.prototype, "behaviors", {
  19019. /**
  19020. * Gets the list of attached behaviors
  19021. * @see http://doc.babylonjs.com/features/behaviour
  19022. */
  19023. get: function () {
  19024. return this._behaviors;
  19025. },
  19026. enumerable: true,
  19027. configurable: true
  19028. });
  19029. /**
  19030. * Gets an attached behavior by name
  19031. * @param name defines the name of the behavior to look for
  19032. * @see http://doc.babylonjs.com/features/behaviour
  19033. * @returns null if behavior was not found else the requested behavior
  19034. */
  19035. Node.prototype.getBehaviorByName = function (name) {
  19036. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  19037. var behavior = _a[_i];
  19038. if (behavior.name === name) {
  19039. return behavior;
  19040. }
  19041. }
  19042. return null;
  19043. };
  19044. /**
  19045. * Returns the latest update of the World matrix
  19046. * @returns a Matrix
  19047. */
  19048. Node.prototype.getWorldMatrix = function () {
  19049. if (this._currentRenderId !== this._scene.getRenderId()) {
  19050. this.computeWorldMatrix();
  19051. }
  19052. return this._worldMatrix;
  19053. };
  19054. /** @hidden */
  19055. Node.prototype._getWorldMatrixDeterminant = function () {
  19056. return this._worldMatrixDeterminant;
  19057. };
  19058. Object.defineProperty(Node.prototype, "worldMatrixFromCache", {
  19059. /**
  19060. * Returns directly the latest state of the mesh World matrix.
  19061. * A Matrix is returned.
  19062. */
  19063. get: function () {
  19064. return this._worldMatrix;
  19065. },
  19066. enumerable: true,
  19067. configurable: true
  19068. });
  19069. // override it in derived class if you add new variables to the cache
  19070. // and call the parent class method
  19071. /** @hidden */
  19072. Node.prototype._initCache = function () {
  19073. this._cache = {};
  19074. this._cache.parent = undefined;
  19075. };
  19076. /** @hidden */
  19077. Node.prototype.updateCache = function (force) {
  19078. if (!force && this.isSynchronized()) {
  19079. return;
  19080. }
  19081. this._cache.parent = this.parent;
  19082. this._updateCache();
  19083. };
  19084. // override it in derived class if you add new variables to the cache
  19085. // and call the parent class method if !ignoreParentClass
  19086. /** @hidden */
  19087. Node.prototype._updateCache = function (ignoreParentClass) {
  19088. };
  19089. // override it in derived class if you add new variables to the cache
  19090. /** @hidden */
  19091. Node.prototype._isSynchronized = function () {
  19092. return true;
  19093. };
  19094. /** @hidden */
  19095. Node.prototype._markSyncedWithParent = function () {
  19096. if (this._parentNode) {
  19097. this._parentRenderId = this._parentNode._childRenderId;
  19098. }
  19099. };
  19100. /** @hidden */
  19101. Node.prototype.isSynchronizedWithParent = function () {
  19102. if (!this._parentNode) {
  19103. return true;
  19104. }
  19105. if (this._parentRenderId !== this._parentNode._childRenderId) {
  19106. return false;
  19107. }
  19108. return this._parentNode.isSynchronized();
  19109. };
  19110. /** @hidden */
  19111. Node.prototype.isSynchronized = function () {
  19112. if (this._cache.parent != this._parentNode) {
  19113. this._cache.parent = this._parentNode;
  19114. return false;
  19115. }
  19116. if (this._parentNode && !this.isSynchronizedWithParent()) {
  19117. return false;
  19118. }
  19119. return this._isSynchronized();
  19120. };
  19121. /**
  19122. * Is this node ready to be used/rendered
  19123. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  19124. * @return true if the node is ready
  19125. */
  19126. Node.prototype.isReady = function (completeCheck) {
  19127. if (completeCheck === void 0) { completeCheck = false; }
  19128. return this._isReady;
  19129. };
  19130. /**
  19131. * Is this node enabled?
  19132. * 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
  19133. * @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
  19134. * @return whether this node (and its parent) is enabled
  19135. */
  19136. Node.prototype.isEnabled = function (checkAncestors) {
  19137. if (checkAncestors === void 0) { checkAncestors = true; }
  19138. if (checkAncestors === false) {
  19139. return this._isEnabled;
  19140. }
  19141. if (!this._isEnabled) {
  19142. return false;
  19143. }
  19144. return this._isParentEnabled;
  19145. };
  19146. /** @hidden */
  19147. Node.prototype._syncParentEnabledState = function () {
  19148. this._isParentEnabled = this._parentNode ? this._parentNode.isEnabled() : true;
  19149. if (this._children) {
  19150. this._children.forEach(function (c) {
  19151. c._syncParentEnabledState(); // Force children to update accordingly
  19152. });
  19153. }
  19154. };
  19155. /**
  19156. * Set the enabled state of this node
  19157. * @param value defines the new enabled state
  19158. */
  19159. Node.prototype.setEnabled = function (value) {
  19160. this._isEnabled = value;
  19161. this._syncParentEnabledState();
  19162. };
  19163. /**
  19164. * Is this node a descendant of the given node?
  19165. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  19166. * @param ancestor defines the parent node to inspect
  19167. * @returns a boolean indicating if this node is a descendant of the given node
  19168. */
  19169. Node.prototype.isDescendantOf = function (ancestor) {
  19170. if (this.parent) {
  19171. if (this.parent === ancestor) {
  19172. return true;
  19173. }
  19174. return this.parent.isDescendantOf(ancestor);
  19175. }
  19176. return false;
  19177. };
  19178. /** @hidden */
  19179. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  19180. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  19181. if (!this._children) {
  19182. return;
  19183. }
  19184. for (var index = 0; index < this._children.length; index++) {
  19185. var item = this._children[index];
  19186. if (!predicate || predicate(item)) {
  19187. results.push(item);
  19188. }
  19189. if (!directDescendantsOnly) {
  19190. item._getDescendants(results, false, predicate);
  19191. }
  19192. }
  19193. };
  19194. /**
  19195. * Will return all nodes that have this node as ascendant
  19196. * @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
  19197. * @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
  19198. * @return all children nodes of all types
  19199. */
  19200. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  19201. var results = new Array();
  19202. this._getDescendants(results, directDescendantsOnly, predicate);
  19203. return results;
  19204. };
  19205. /**
  19206. * Get all child-meshes of this node
  19207. * @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
  19208. * @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
  19209. * @returns an array of AbstractMesh
  19210. */
  19211. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  19212. var results = [];
  19213. this._getDescendants(results, directDescendantsOnly, function (node) {
  19214. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  19215. });
  19216. return results;
  19217. };
  19218. /**
  19219. * Get all child-transformNodes of this node
  19220. * @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
  19221. * @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
  19222. * @returns an array of TransformNode
  19223. */
  19224. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  19225. var results = [];
  19226. this._getDescendants(results, directDescendantsOnly, function (node) {
  19227. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  19228. });
  19229. return results;
  19230. };
  19231. /**
  19232. * Get all direct children of this node
  19233. * @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
  19234. * @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 (Default: true)
  19235. * @returns an array of Node
  19236. */
  19237. Node.prototype.getChildren = function (predicate, directDescendantsOnly) {
  19238. if (directDescendantsOnly === void 0) { directDescendantsOnly = true; }
  19239. return this.getDescendants(directDescendantsOnly, predicate);
  19240. };
  19241. /** @hidden */
  19242. Node.prototype._setReady = function (state) {
  19243. if (state === this._isReady) {
  19244. return;
  19245. }
  19246. if (!state) {
  19247. this._isReady = false;
  19248. return;
  19249. }
  19250. if (this.onReady) {
  19251. this.onReady(this);
  19252. }
  19253. this._isReady = true;
  19254. };
  19255. /**
  19256. * Get an animation by name
  19257. * @param name defines the name of the animation to look for
  19258. * @returns null if not found else the requested animation
  19259. */
  19260. Node.prototype.getAnimationByName = function (name) {
  19261. for (var i = 0; i < this.animations.length; i++) {
  19262. var animation = this.animations[i];
  19263. if (animation.name === name) {
  19264. return animation;
  19265. }
  19266. }
  19267. return null;
  19268. };
  19269. /**
  19270. * Creates an animation range for this node
  19271. * @param name defines the name of the range
  19272. * @param from defines the starting key
  19273. * @param to defines the end key
  19274. */
  19275. Node.prototype.createAnimationRange = function (name, from, to) {
  19276. // check name not already in use
  19277. if (!this._ranges[name]) {
  19278. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  19279. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  19280. if (this.animations[i]) {
  19281. this.animations[i].createRange(name, from, to);
  19282. }
  19283. }
  19284. }
  19285. };
  19286. /**
  19287. * Delete a specific animation range
  19288. * @param name defines the name of the range to delete
  19289. * @param deleteFrames defines if animation frames from the range must be deleted as well
  19290. */
  19291. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  19292. if (deleteFrames === void 0) { deleteFrames = true; }
  19293. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  19294. if (this.animations[i]) {
  19295. this.animations[i].deleteRange(name, deleteFrames);
  19296. }
  19297. }
  19298. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  19299. };
  19300. /**
  19301. * Get an animation range by name
  19302. * @param name defines the name of the animation range to look for
  19303. * @returns null if not found else the requested animation range
  19304. */
  19305. Node.prototype.getAnimationRange = function (name) {
  19306. return this._ranges[name];
  19307. };
  19308. /**
  19309. * Will start the animation sequence
  19310. * @param name defines the range frames for animation sequence
  19311. * @param loop defines if the animation should loop (false by default)
  19312. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  19313. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  19314. * @returns the object created for this animation. If range does not exist, it will return null
  19315. */
  19316. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  19317. var range = this.getAnimationRange(name);
  19318. if (!range) {
  19319. return null;
  19320. }
  19321. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  19322. };
  19323. /**
  19324. * Serialize animation ranges into a JSON compatible object
  19325. * @returns serialization object
  19326. */
  19327. Node.prototype.serializeAnimationRanges = function () {
  19328. var serializationRanges = [];
  19329. for (var name in this._ranges) {
  19330. var localRange = this._ranges[name];
  19331. if (!localRange) {
  19332. continue;
  19333. }
  19334. var range = {};
  19335. range.name = name;
  19336. range.from = localRange.from;
  19337. range.to = localRange.to;
  19338. serializationRanges.push(range);
  19339. }
  19340. return serializationRanges;
  19341. };
  19342. /**
  19343. * Computes the world matrix of the node
  19344. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  19345. * @returns the world matrix
  19346. */
  19347. Node.prototype.computeWorldMatrix = function (force) {
  19348. if (!this._worldMatrix) {
  19349. this._worldMatrix = BABYLON.Matrix.Identity();
  19350. }
  19351. return this._worldMatrix;
  19352. };
  19353. /**
  19354. * Releases resources associated with this node.
  19355. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19356. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19357. */
  19358. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19359. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19360. this._isDisposed = true;
  19361. if (!doNotRecurse) {
  19362. var nodes = this.getDescendants(true);
  19363. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  19364. var node = nodes_1[_i];
  19365. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  19366. }
  19367. }
  19368. else {
  19369. var transformNodes = this.getChildTransformNodes(true);
  19370. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  19371. var transformNode = transformNodes_1[_a];
  19372. transformNode.parent = null;
  19373. transformNode.computeWorldMatrix(true);
  19374. }
  19375. }
  19376. if (!this.parent) {
  19377. this.removeFromSceneRootNodes();
  19378. }
  19379. else {
  19380. this.parent = null;
  19381. }
  19382. // Callback
  19383. this.onDisposeObservable.notifyObservers(this);
  19384. this.onDisposeObservable.clear();
  19385. // Behaviors
  19386. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  19387. var behavior = _c[_b];
  19388. behavior.detach();
  19389. }
  19390. this._behaviors = [];
  19391. };
  19392. /**
  19393. * Parse animation range data from a serialization object and store them into a given node
  19394. * @param node defines where to store the animation ranges
  19395. * @param parsedNode defines the serialization object to read data from
  19396. * @param scene defines the hosting scene
  19397. */
  19398. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  19399. if (parsedNode.ranges) {
  19400. for (var index = 0; index < parsedNode.ranges.length; index++) {
  19401. var data = parsedNode.ranges[index];
  19402. node.createAnimationRange(data.name, data.from, data.to);
  19403. }
  19404. }
  19405. };
  19406. Node._NodeConstructors = {};
  19407. __decorate([
  19408. BABYLON.serialize()
  19409. ], Node.prototype, "name", void 0);
  19410. __decorate([
  19411. BABYLON.serialize()
  19412. ], Node.prototype, "id", void 0);
  19413. __decorate([
  19414. BABYLON.serialize()
  19415. ], Node.prototype, "uniqueId", void 0);
  19416. __decorate([
  19417. BABYLON.serialize()
  19418. ], Node.prototype, "state", void 0);
  19419. __decorate([
  19420. BABYLON.serialize()
  19421. ], Node.prototype, "metadata", void 0);
  19422. return Node;
  19423. }());
  19424. BABYLON.Node = Node;
  19425. })(BABYLON || (BABYLON = {}));
  19426. //# sourceMappingURL=babylon.node.js.map
  19427. var BABYLON;
  19428. (function (BABYLON) {
  19429. /**
  19430. * Class used to store bounding sphere information
  19431. */
  19432. var BoundingSphere = /** @class */ (function () {
  19433. /**
  19434. * Creates a new bounding sphere
  19435. * @param min defines the minimum vector (in local space)
  19436. * @param max defines the maximum vector (in local space)
  19437. * @param worldMatrix defines the new world matrix
  19438. */
  19439. function BoundingSphere(min, max, worldMatrix) {
  19440. /**
  19441. * Gets the center of the bounding sphere in local space
  19442. */
  19443. this.center = BABYLON.Vector3.Zero();
  19444. /**
  19445. * Gets the center of the bounding sphere in world space
  19446. */
  19447. this.centerWorld = BABYLON.Vector3.Zero();
  19448. /**
  19449. * Gets the minimum vector in local space
  19450. */
  19451. this.minimum = BABYLON.Vector3.Zero();
  19452. /**
  19453. * Gets the maximum vector in local space
  19454. */
  19455. this.maximum = BABYLON.Vector3.Zero();
  19456. this.reConstruct(min, max, worldMatrix);
  19457. }
  19458. /**
  19459. * Recreates the entire bounding sphere from scratch as if we call the constructor in place
  19460. * @param min defines the new minimum vector (in local space)
  19461. * @param max defines the new maximum vector (in local space)
  19462. * @param worldMatrix defines the new world matrix
  19463. */
  19464. BoundingSphere.prototype.reConstruct = function (min, max, worldMatrix) {
  19465. this.minimum.copyFrom(min);
  19466. this.maximum.copyFrom(max);
  19467. var distance = BABYLON.Vector3.Distance(min, max);
  19468. max.addToRef(min, this.center).scaleInPlace(0.5);
  19469. this.radius = distance * 0.5;
  19470. this._update(worldMatrix || BABYLON.Matrix.IdentityReadOnly);
  19471. };
  19472. /**
  19473. * Scale the current bounding sphere by applying a scale factor
  19474. * @param factor defines the scale factor to apply
  19475. * @returns the current bounding box
  19476. */
  19477. BoundingSphere.prototype.scale = function (factor) {
  19478. var newRadius = this.radius * factor;
  19479. var tmpVectors = BoundingSphere.TmpVector3;
  19480. var tempRadiusVector = tmpVectors[0].setAll(newRadius);
  19481. var min = this.center.subtractToRef(tempRadiusVector, tmpVectors[1]);
  19482. var max = this.center.addToRef(tempRadiusVector, tmpVectors[2]);
  19483. this.reConstruct(min, max, this._worldMatrix);
  19484. return this;
  19485. };
  19486. /**
  19487. * Gets the world matrix of the bounding box
  19488. * @returns a matrix
  19489. */
  19490. BoundingSphere.prototype.getWorldMatrix = function () {
  19491. return this._worldMatrix;
  19492. };
  19493. // Methods
  19494. /** @hidden */
  19495. BoundingSphere.prototype._update = function (worldMatrix) {
  19496. if (!worldMatrix.isIdentity()) {
  19497. BABYLON.Vector3.TransformCoordinatesToRef(this.center, worldMatrix, this.centerWorld);
  19498. var tempVector = BoundingSphere.TmpVector3[0];
  19499. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, worldMatrix, tempVector);
  19500. this.radiusWorld = Math.max(Math.abs(tempVector.x), Math.abs(tempVector.y), Math.abs(tempVector.z)) * this.radius;
  19501. }
  19502. else {
  19503. this.centerWorld.copyFrom(this.center);
  19504. this.radiusWorld = this.radius;
  19505. }
  19506. };
  19507. /**
  19508. * Tests if the bounding sphere is intersecting the frustum planes
  19509. * @param frustumPlanes defines the frustum planes to test
  19510. * @returns true if there is an intersection
  19511. */
  19512. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  19513. var center = this.centerWorld;
  19514. var radius = this.radiusWorld;
  19515. for (var i = 0; i < 6; i++) {
  19516. if (frustumPlanes[i].dotCoordinate(center) <= -radius) {
  19517. return false;
  19518. }
  19519. }
  19520. return true;
  19521. };
  19522. /**
  19523. * Tests if the bounding sphere center is in between the frustum planes.
  19524. * Used for optimistic fast inclusion.
  19525. * @param frustumPlanes defines the frustum planes to test
  19526. * @returns true if the sphere center is in between the frustum planes
  19527. */
  19528. BoundingSphere.prototype.isCenterInFrustum = function (frustumPlanes) {
  19529. var center = this.centerWorld;
  19530. for (var i = 0; i < 6; i++) {
  19531. if (frustumPlanes[i].dotCoordinate(center) < 0) {
  19532. return false;
  19533. }
  19534. }
  19535. return true;
  19536. };
  19537. /**
  19538. * Tests if a point is inside the bounding sphere
  19539. * @param point defines the point to test
  19540. * @returns true if the point is inside the bounding sphere
  19541. */
  19542. BoundingSphere.prototype.intersectsPoint = function (point) {
  19543. var squareDistance = BABYLON.Vector3.DistanceSquared(this.centerWorld, point);
  19544. if (this.radiusWorld * this.radiusWorld < squareDistance) {
  19545. return false;
  19546. }
  19547. return true;
  19548. };
  19549. // Statics
  19550. /**
  19551. * Checks if two sphere intersct
  19552. * @param sphere0 sphere 0
  19553. * @param sphere1 sphere 1
  19554. * @returns true if the speres intersect
  19555. */
  19556. BoundingSphere.Intersects = function (sphere0, sphere1) {
  19557. var squareDistance = BABYLON.Vector3.DistanceSquared(sphere0.centerWorld, sphere1.centerWorld);
  19558. var radiusSum = sphere0.radiusWorld + sphere1.radiusWorld;
  19559. if (radiusSum * radiusSum < squareDistance) {
  19560. return false;
  19561. }
  19562. return true;
  19563. };
  19564. BoundingSphere.TmpVector3 = BABYLON.Tools.BuildArray(3, BABYLON.Vector3.Zero);
  19565. return BoundingSphere;
  19566. }());
  19567. BABYLON.BoundingSphere = BoundingSphere;
  19568. })(BABYLON || (BABYLON = {}));
  19569. //# sourceMappingURL=babylon.boundingSphere.js.map
  19570. var BABYLON;
  19571. (function (BABYLON) {
  19572. /**
  19573. * Class used to store bounding box information
  19574. */
  19575. var BoundingBox = /** @class */ (function () {
  19576. /**
  19577. * Creates a new bounding box
  19578. * @param min defines the minimum vector (in local space)
  19579. * @param max defines the maximum vector (in local space)
  19580. * @param worldMatrix defines the new world matrix
  19581. */
  19582. function BoundingBox(min, max, worldMatrix) {
  19583. /**
  19584. * Gets the 8 vectors representing the bounding box in local space
  19585. */
  19586. this.vectors = BABYLON.Tools.BuildArray(8, BABYLON.Vector3.Zero);
  19587. /**
  19588. * Gets the center of the bounding box in local space
  19589. */
  19590. this.center = BABYLON.Vector3.Zero();
  19591. /**
  19592. * Gets the center of the bounding box in world space
  19593. */
  19594. this.centerWorld = BABYLON.Vector3.Zero();
  19595. /**
  19596. * Gets the extend size in local space
  19597. */
  19598. this.extendSize = BABYLON.Vector3.Zero();
  19599. /**
  19600. * Gets the extend size in world space
  19601. */
  19602. this.extendSizeWorld = BABYLON.Vector3.Zero();
  19603. /**
  19604. * Gets the OBB (object bounding box) directions
  19605. */
  19606. this.directions = BABYLON.Tools.BuildArray(3, BABYLON.Vector3.Zero);
  19607. /**
  19608. * Gets the 8 vectors representing the bounding box in world space
  19609. */
  19610. this.vectorsWorld = BABYLON.Tools.BuildArray(8, BABYLON.Vector3.Zero);
  19611. /**
  19612. * Gets the minimum vector in world space
  19613. */
  19614. this.minimumWorld = BABYLON.Vector3.Zero();
  19615. /**
  19616. * Gets the maximum vector in world space
  19617. */
  19618. this.maximumWorld = BABYLON.Vector3.Zero();
  19619. /**
  19620. * Gets the minimum vector in local space
  19621. */
  19622. this.minimum = BABYLON.Vector3.Zero();
  19623. /**
  19624. * Gets the maximum vector in local space
  19625. */
  19626. this.maximum = BABYLON.Vector3.Zero();
  19627. this.reConstruct(min, max, worldMatrix);
  19628. }
  19629. // Methods
  19630. /**
  19631. * Recreates the entire bounding box from scratch as if we call the constructor in place
  19632. * @param min defines the new minimum vector (in local space)
  19633. * @param max defines the new maximum vector (in local space)
  19634. * @param worldMatrix defines the new world matrix
  19635. */
  19636. BoundingBox.prototype.reConstruct = function (min, max, worldMatrix) {
  19637. var minX = min.x, minY = min.y, minZ = min.z, maxX = max.x, maxY = max.y, maxZ = max.z;
  19638. var vectors = this.vectors;
  19639. this.minimum.copyFromFloats(minX, minY, minZ);
  19640. this.maximum.copyFromFloats(maxX, maxY, maxZ);
  19641. vectors[0].copyFromFloats(minX, minY, minZ);
  19642. vectors[1].copyFromFloats(maxX, maxY, maxZ);
  19643. vectors[2].copyFromFloats(maxX, minY, minZ);
  19644. vectors[3].copyFromFloats(minX, maxY, minZ);
  19645. vectors[4].copyFromFloats(minX, minY, maxZ);
  19646. vectors[5].copyFromFloats(maxX, maxY, minZ);
  19647. vectors[6].copyFromFloats(minX, maxY, maxZ);
  19648. vectors[7].copyFromFloats(maxX, minY, maxZ);
  19649. // OBB
  19650. max.addToRef(min, this.center).scaleInPlace(0.5);
  19651. max.subtractToRef(min, this.extendSize).scaleInPlace(0.5);
  19652. this._update(worldMatrix || BABYLON.Matrix.IdentityReadOnly);
  19653. };
  19654. /**
  19655. * Scale the current bounding box by applying a scale factor
  19656. * @param factor defines the scale factor to apply
  19657. * @returns the current bounding box
  19658. */
  19659. BoundingBox.prototype.scale = function (factor) {
  19660. var tmpVectors = BoundingBox.TmpVector3;
  19661. var diff = this.maximum.subtractToRef(this.minimum, tmpVectors[0]);
  19662. var len = diff.length();
  19663. diff.normalizeFromLength(len);
  19664. var distance = len * factor;
  19665. var newRadius = diff.scaleInPlace(distance * 0.5);
  19666. var min = this.center.subtractToRef(newRadius, tmpVectors[1]);
  19667. var max = this.center.addToRef(newRadius, tmpVectors[2]);
  19668. this.reConstruct(min, max, this._worldMatrix);
  19669. return this;
  19670. };
  19671. /**
  19672. * Gets the world matrix of the bounding box
  19673. * @returns a matrix
  19674. */
  19675. BoundingBox.prototype.getWorldMatrix = function () {
  19676. return this._worldMatrix;
  19677. };
  19678. /** @hidden */
  19679. BoundingBox.prototype._update = function (world) {
  19680. var minWorld = this.minimumWorld;
  19681. var maxWorld = this.maximumWorld;
  19682. var directions = this.directions;
  19683. var vectorsWorld = this.vectorsWorld;
  19684. var vectors = this.vectors;
  19685. if (!world.isIdentity()) {
  19686. minWorld.setAll(Number.MAX_VALUE);
  19687. maxWorld.setAll(-Number.MAX_VALUE);
  19688. for (var index = 0; index < 8; ++index) {
  19689. var v = vectorsWorld[index];
  19690. BABYLON.Vector3.TransformCoordinatesToRef(vectors[index], world, v);
  19691. minWorld.minimizeInPlace(v);
  19692. maxWorld.maximizeInPlace(v);
  19693. }
  19694. // Extend
  19695. maxWorld.subtractToRef(minWorld, this.extendSizeWorld).scaleInPlace(0.5);
  19696. maxWorld.addToRef(minWorld, this.centerWorld).scaleInPlace(0.5);
  19697. }
  19698. else {
  19699. minWorld.copyFrom(this.minimum);
  19700. maxWorld.copyFrom(this.maximum);
  19701. for (var index = 0; index < 8; ++index) {
  19702. vectorsWorld[index].copyFrom(vectors[index]);
  19703. }
  19704. // Extend
  19705. this.extendSizeWorld.copyFrom(this.extendSize);
  19706. this.centerWorld.copyFrom(this.center);
  19707. }
  19708. BABYLON.Vector3.FromArrayToRef(world.m, 0, directions[0]);
  19709. BABYLON.Vector3.FromArrayToRef(world.m, 4, directions[1]);
  19710. BABYLON.Vector3.FromArrayToRef(world.m, 8, directions[2]);
  19711. this._worldMatrix = world;
  19712. };
  19713. /**
  19714. * Tests if the bounding box is intersecting the frustum planes
  19715. * @param frustumPlanes defines the frustum planes to test
  19716. * @returns true if there is an intersection
  19717. */
  19718. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  19719. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  19720. };
  19721. /**
  19722. * Tests if the bounding box is entirely inside the frustum planes
  19723. * @param frustumPlanes defines the frustum planes to test
  19724. * @returns true if there is an inclusion
  19725. */
  19726. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  19727. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  19728. };
  19729. /**
  19730. * Tests if a point is inside the bounding box
  19731. * @param point defines the point to test
  19732. * @returns true if the point is inside the bounding box
  19733. */
  19734. BoundingBox.prototype.intersectsPoint = function (point) {
  19735. var min = this.minimumWorld;
  19736. var max = this.maximumWorld;
  19737. var minX = min.x, minY = min.y, minZ = min.z, maxX = max.x, maxY = max.y, maxZ = max.z;
  19738. var pointX = point.x, pointY = point.y, pointZ = point.z;
  19739. var delta = -BABYLON.Epsilon;
  19740. if (maxX - pointX < delta || delta > pointX - minX) {
  19741. return false;
  19742. }
  19743. if (maxY - pointY < delta || delta > pointY - minY) {
  19744. return false;
  19745. }
  19746. if (maxZ - pointZ < delta || delta > pointZ - minZ) {
  19747. return false;
  19748. }
  19749. return true;
  19750. };
  19751. /**
  19752. * Tests if the bounding box intersects with a bounding sphere
  19753. * @param sphere defines the sphere to test
  19754. * @returns true if there is an intersection
  19755. */
  19756. BoundingBox.prototype.intersectsSphere = function (sphere) {
  19757. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  19758. };
  19759. /**
  19760. * Tests if the bounding box intersects with a box defined by a min and max vectors
  19761. * @param min defines the min vector to use
  19762. * @param max defines the max vector to use
  19763. * @returns true if there is an intersection
  19764. */
  19765. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  19766. var myMin = this.minimumWorld;
  19767. var myMax = this.maximumWorld;
  19768. var myMinX = myMin.x, myMinY = myMin.y, myMinZ = myMin.z, myMaxX = myMax.x, myMaxY = myMax.y, myMaxZ = myMax.z;
  19769. var minX = min.x, minY = min.y, minZ = min.z, maxX = max.x, maxY = max.y, maxZ = max.z;
  19770. if (myMaxX < minX || myMinX > maxX) {
  19771. return false;
  19772. }
  19773. if (myMaxY < minY || myMinY > maxY) {
  19774. return false;
  19775. }
  19776. if (myMaxZ < minZ || myMinZ > maxZ) {
  19777. return false;
  19778. }
  19779. return true;
  19780. };
  19781. // Statics
  19782. /**
  19783. * Tests if two bounding boxes are intersections
  19784. * @param box0 defines the first box to test
  19785. * @param box1 defines the second box to test
  19786. * @returns true if there is an intersection
  19787. */
  19788. BoundingBox.Intersects = function (box0, box1) {
  19789. return box0.intersectsMinMax(box1.minimumWorld, box1.maximumWorld);
  19790. };
  19791. /**
  19792. * Tests if a bounding box defines by a min/max vectors intersects a sphere
  19793. * @param minPoint defines the minimum vector of the bounding box
  19794. * @param maxPoint defines the maximum vector of the bounding box
  19795. * @param sphereCenter defines the sphere center
  19796. * @param sphereRadius defines the sphere radius
  19797. * @returns true if there is an intersection
  19798. */
  19799. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  19800. var vector = BoundingBox.TmpVector3[0];
  19801. BABYLON.Vector3.ClampToRef(sphereCenter, minPoint, maxPoint, vector);
  19802. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  19803. return (num <= (sphereRadius * sphereRadius));
  19804. };
  19805. /**
  19806. * Tests if a bounding box defined with 8 vectors is entirely inside frustum planes
  19807. * @param boundingVectors defines an array of 8 vectors representing a bounding box
  19808. * @param frustumPlanes defines the frustum planes to test
  19809. * @return true if there is an inclusion
  19810. */
  19811. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  19812. for (var p = 0; p < 6; ++p) {
  19813. var frustumPlane = frustumPlanes[p];
  19814. for (var i = 0; i < 8; ++i) {
  19815. if (frustumPlane.dotCoordinate(boundingVectors[i]) < 0) {
  19816. return false;
  19817. }
  19818. }
  19819. }
  19820. return true;
  19821. };
  19822. /**
  19823. * Tests if a bounding box defined with 8 vectors intersects frustum planes
  19824. * @param boundingVectors defines an array of 8 vectors representing a bounding box
  19825. * @param frustumPlanes defines the frustum planes to test
  19826. * @return true if there is an intersection
  19827. */
  19828. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  19829. for (var p = 0; p < 6; ++p) {
  19830. var canReturnFalse = true;
  19831. var frustumPlane = frustumPlanes[p];
  19832. for (var i = 0; i < 8; ++i) {
  19833. if (frustumPlane.dotCoordinate(boundingVectors[i]) >= 0) {
  19834. canReturnFalse = false;
  19835. break;
  19836. }
  19837. }
  19838. if (canReturnFalse) {
  19839. return false;
  19840. }
  19841. }
  19842. return true;
  19843. };
  19844. BoundingBox.TmpVector3 = BABYLON.Tools.BuildArray(3, BABYLON.Vector3.Zero);
  19845. return BoundingBox;
  19846. }());
  19847. BABYLON.BoundingBox = BoundingBox;
  19848. })(BABYLON || (BABYLON = {}));
  19849. //# sourceMappingURL=babylon.boundingBox.js.map
  19850. var BABYLON;
  19851. (function (BABYLON) {
  19852. var _result0 = { min: 0, max: 0 };
  19853. var _result1 = { min: 0, max: 0 };
  19854. var computeBoxExtents = function (axis, box, result) {
  19855. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  19856. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  19857. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  19858. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  19859. var r = r0 + r1 + r2;
  19860. result.min = p - r;
  19861. result.max = p + r;
  19862. };
  19863. var axisOverlap = function (axis, box0, box1) {
  19864. computeBoxExtents(axis, box0, _result0);
  19865. computeBoxExtents(axis, box1, _result1);
  19866. return !(_result0.min > _result1.max || _result1.min > _result0.max);
  19867. };
  19868. /**
  19869. * Info for a bounding data of a mesh
  19870. */
  19871. var BoundingInfo = /** @class */ (function () {
  19872. /**
  19873. * Constructs bounding info
  19874. * @param minimum min vector of the bounding box/sphere
  19875. * @param maximum max vector of the bounding box/sphere
  19876. * @param worldMatrix defines the new world matrix
  19877. */
  19878. function BoundingInfo(minimum, maximum, worldMatrix) {
  19879. this._isLocked = false;
  19880. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum, worldMatrix);
  19881. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum, worldMatrix);
  19882. }
  19883. /**
  19884. * Recreates the entire bounding info from scratch as if we call the constructor in place
  19885. * @param min defines the new minimum vector (in local space)
  19886. * @param max defines the new maximum vector (in local space)
  19887. * @param worldMatrix defines the new world matrix
  19888. */
  19889. BoundingInfo.prototype.reConstruct = function (min, max, worldMatrix) {
  19890. this.boundingBox.reConstruct(min, max, worldMatrix);
  19891. this.boundingSphere.reConstruct(min, max, worldMatrix);
  19892. };
  19893. Object.defineProperty(BoundingInfo.prototype, "minimum", {
  19894. /**
  19895. * min vector of the bounding box/sphere
  19896. */
  19897. get: function () {
  19898. return this.boundingBox.minimum;
  19899. },
  19900. enumerable: true,
  19901. configurable: true
  19902. });
  19903. Object.defineProperty(BoundingInfo.prototype, "maximum", {
  19904. /**
  19905. * max vector of the bounding box/sphere
  19906. */
  19907. get: function () {
  19908. return this.boundingBox.maximum;
  19909. },
  19910. enumerable: true,
  19911. configurable: true
  19912. });
  19913. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  19914. /**
  19915. * If the info is locked and won't be updated to avoid perf overhead
  19916. */
  19917. get: function () {
  19918. return this._isLocked;
  19919. },
  19920. set: function (value) {
  19921. this._isLocked = value;
  19922. },
  19923. enumerable: true,
  19924. configurable: true
  19925. });
  19926. // Methods
  19927. /**
  19928. * Updates the bounding sphere and box
  19929. * @param world world matrix to be used to update
  19930. */
  19931. BoundingInfo.prototype.update = function (world) {
  19932. if (this._isLocked) {
  19933. return;
  19934. }
  19935. this.boundingBox._update(world);
  19936. this.boundingSphere._update(world);
  19937. };
  19938. /**
  19939. * Recreate the bounding info to be centered around a specific point given a specific extend.
  19940. * @param center New center of the bounding info
  19941. * @param extend New extend of the bounding info
  19942. * @returns the current bounding info
  19943. */
  19944. BoundingInfo.prototype.centerOn = function (center, extend) {
  19945. var minimum = BoundingInfo.TmpVector3[0].copyFrom(center).subtractInPlace(extend);
  19946. var maximum = BoundingInfo.TmpVector3[1].copyFrom(center).addInPlace(extend);
  19947. this.boundingBox.reConstruct(minimum, maximum, this.boundingBox.getWorldMatrix());
  19948. this.boundingSphere.reConstruct(minimum, maximum, this.boundingBox.getWorldMatrix());
  19949. return this;
  19950. };
  19951. /**
  19952. * Scale the current bounding info by applying a scale factor
  19953. * @param factor defines the scale factor to apply
  19954. * @returns the current bounding info
  19955. */
  19956. BoundingInfo.prototype.scale = function (factor) {
  19957. this.boundingBox.scale(factor);
  19958. this.boundingSphere.scale(factor);
  19959. return this;
  19960. };
  19961. /**
  19962. * Returns `true` if the bounding info is within the frustum defined by the passed array of planes.
  19963. * @param frustumPlanes defines the frustum to test
  19964. * @param strategy defines the strategy to use for the culling (default is BABYLON.AbstractMesh.CULLINGSTRATEGY_STANDARD)
  19965. * @returns true if the bounding info is in the frustum planes
  19966. */
  19967. BoundingInfo.prototype.isInFrustum = function (frustumPlanes, strategy) {
  19968. if (strategy === void 0) { strategy = BABYLON.AbstractMesh.CULLINGSTRATEGY_STANDARD; }
  19969. var inclusionTest = (strategy === BABYLON.AbstractMesh.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION || strategy === BABYLON.AbstractMesh.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY);
  19970. if (inclusionTest) {
  19971. if (this.boundingSphere.isCenterInFrustum(frustumPlanes)) {
  19972. return true;
  19973. }
  19974. }
  19975. if (!this.boundingSphere.isInFrustum(frustumPlanes)) {
  19976. return false;
  19977. }
  19978. var bSphereOnlyTest = (strategy === BABYLON.AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY || strategy === BABYLON.AbstractMesh.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY);
  19979. if (bSphereOnlyTest) {
  19980. return true;
  19981. }
  19982. return this.boundingBox.isInFrustum(frustumPlanes);
  19983. };
  19984. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  19985. /**
  19986. * Gets the world distance between the min and max points of the bounding box
  19987. */
  19988. get: function () {
  19989. var boundingBox = this.boundingBox;
  19990. var diag = boundingBox.maximumWorld.subtractToRef(boundingBox.minimumWorld, BoundingInfo.TmpVector3[0]);
  19991. return diag.length();
  19992. },
  19993. enumerable: true,
  19994. configurable: true
  19995. });
  19996. /**
  19997. * Checks if a cullable object (mesh...) is in the camera frustum
  19998. * Unlike isInFrustum this cheks the full bounding box
  19999. * @param frustumPlanes Camera near/planes
  20000. * @returns true if the object is in frustum otherwise false
  20001. */
  20002. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  20003. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  20004. };
  20005. /** @hidden */
  20006. BoundingInfo.prototype._checkCollision = function (collider) {
  20007. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  20008. };
  20009. /**
  20010. * Checks if a point is inside the bounding box and bounding sphere or the mesh
  20011. * @see https://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  20012. * @param point the point to check intersection with
  20013. * @returns if the point intersects
  20014. */
  20015. BoundingInfo.prototype.intersectsPoint = function (point) {
  20016. if (!this.boundingSphere.centerWorld) {
  20017. return false;
  20018. }
  20019. if (!this.boundingSphere.intersectsPoint(point)) {
  20020. return false;
  20021. }
  20022. if (!this.boundingBox.intersectsPoint(point)) {
  20023. return false;
  20024. }
  20025. return true;
  20026. };
  20027. /**
  20028. * Checks if another bounding info intersects the bounding box and bounding sphere or the mesh
  20029. * @see https://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  20030. * @param boundingInfo the bounding info to check intersection with
  20031. * @param precise if the intersection should be done using OBB
  20032. * @returns if the bounding info intersects
  20033. */
  20034. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  20035. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  20036. return false;
  20037. }
  20038. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  20039. return false;
  20040. }
  20041. if (!precise) {
  20042. return true;
  20043. }
  20044. var box0 = this.boundingBox;
  20045. var box1 = boundingInfo.boundingBox;
  20046. if (!axisOverlap(box0.directions[0], box0, box1)) {
  20047. return false;
  20048. }
  20049. if (!axisOverlap(box0.directions[1], box0, box1)) {
  20050. return false;
  20051. }
  20052. if (!axisOverlap(box0.directions[2], box0, box1)) {
  20053. return false;
  20054. }
  20055. if (!axisOverlap(box1.directions[0], box0, box1)) {
  20056. return false;
  20057. }
  20058. if (!axisOverlap(box1.directions[1], box0, box1)) {
  20059. return false;
  20060. }
  20061. if (!axisOverlap(box1.directions[2], box0, box1)) {
  20062. return false;
  20063. }
  20064. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1)) {
  20065. return false;
  20066. }
  20067. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1)) {
  20068. return false;
  20069. }
  20070. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1)) {
  20071. return false;
  20072. }
  20073. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1)) {
  20074. return false;
  20075. }
  20076. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1)) {
  20077. return false;
  20078. }
  20079. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1)) {
  20080. return false;
  20081. }
  20082. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1)) {
  20083. return false;
  20084. }
  20085. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1)) {
  20086. return false;
  20087. }
  20088. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1)) {
  20089. return false;
  20090. }
  20091. return true;
  20092. };
  20093. BoundingInfo.TmpVector3 = BABYLON.Tools.BuildArray(2, BABYLON.Vector3.Zero);
  20094. return BoundingInfo;
  20095. }());
  20096. BABYLON.BoundingInfo = BoundingInfo;
  20097. })(BABYLON || (BABYLON = {}));
  20098. //# sourceMappingURL=babylon.boundingInfo.js.map
  20099. var BABYLON;
  20100. (function (BABYLON) {
  20101. /**
  20102. * 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.
  20103. * @see https://doc.babylonjs.com/how_to/transformnode
  20104. */
  20105. var TransformNode = /** @class */ (function (_super) {
  20106. __extends(TransformNode, _super);
  20107. function TransformNode(name, scene, isPure) {
  20108. if (scene === void 0) { scene = null; }
  20109. if (isPure === void 0) { isPure = true; }
  20110. var _this = _super.call(this, name, scene) || this;
  20111. _this._forward = new BABYLON.Vector3(0, 0, 1);
  20112. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  20113. _this._up = new BABYLON.Vector3(0, 1, 0);
  20114. _this._right = new BABYLON.Vector3(1, 0, 0);
  20115. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  20116. // Properties
  20117. _this._position = BABYLON.Vector3.Zero();
  20118. _this._rotation = BABYLON.Vector3.Zero();
  20119. _this._scaling = BABYLON.Vector3.One();
  20120. _this._isDirty = false;
  20121. /**
  20122. * Set the billboard mode. Default is 0.
  20123. *
  20124. * | Value | Type | Description |
  20125. * | --- | --- | --- |
  20126. * | 0 | BILLBOARDMODE_NONE | |
  20127. * | 1 | BILLBOARDMODE_X | |
  20128. * | 2 | BILLBOARDMODE_Y | |
  20129. * | 4 | BILLBOARDMODE_Z | |
  20130. * | 7 | BILLBOARDMODE_ALL | |
  20131. *
  20132. */
  20133. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  20134. /**
  20135. * 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
  20136. */
  20137. _this.scalingDeterminant = 1;
  20138. /**
  20139. * Sets the distance of the object to max, often used by skybox
  20140. */
  20141. _this.infiniteDistance = false;
  20142. /**
  20143. * Gets or sets a boolean indicating that non uniform scaling (when at least one component is different from others) should be ignored.
  20144. * By default the system will update normals to compensate
  20145. */
  20146. _this.ignoreNonUniformScaling = false;
  20147. /** @hidden */
  20148. _this._localMatrix = BABYLON.Matrix.Zero();
  20149. _this._absolutePosition = BABYLON.Vector3.Zero();
  20150. _this._pivotMatrix = BABYLON.Matrix.Identity();
  20151. _this._postMultiplyPivotMatrix = false;
  20152. _this._isWorldMatrixFrozen = false;
  20153. /** @hidden */
  20154. _this._indexInSceneTransformNodesArray = -1;
  20155. /**
  20156. * An event triggered after the world matrix is updated
  20157. */
  20158. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  20159. _this._nonUniformScaling = false;
  20160. if (isPure) {
  20161. _this.getScene().addTransformNode(_this);
  20162. }
  20163. return _this;
  20164. }
  20165. /**
  20166. * Gets a string identifying the name of the class
  20167. * @returns "TransformNode" string
  20168. */
  20169. TransformNode.prototype.getClassName = function () {
  20170. return "TransformNode";
  20171. };
  20172. Object.defineProperty(TransformNode.prototype, "position", {
  20173. /**
  20174. * Gets or set the node position (default is (0.0, 0.0, 0.0))
  20175. */
  20176. get: function () {
  20177. return this._position;
  20178. },
  20179. set: function (newPosition) {
  20180. this._position = newPosition;
  20181. this._isDirty = true;
  20182. },
  20183. enumerable: true,
  20184. configurable: true
  20185. });
  20186. Object.defineProperty(TransformNode.prototype, "rotation", {
  20187. /**
  20188. * 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)).
  20189. * If rotation quaternion is set, this Vector3 will be ignored and copy from the quaternion
  20190. */
  20191. get: function () {
  20192. return this._rotation;
  20193. },
  20194. set: function (newRotation) {
  20195. this._rotation = newRotation;
  20196. this._isDirty = true;
  20197. },
  20198. enumerable: true,
  20199. configurable: true
  20200. });
  20201. Object.defineProperty(TransformNode.prototype, "scaling", {
  20202. /**
  20203. * 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)).
  20204. */
  20205. get: function () {
  20206. return this._scaling;
  20207. },
  20208. set: function (newScaling) {
  20209. this._scaling = newScaling;
  20210. this._isDirty = true;
  20211. },
  20212. enumerable: true,
  20213. configurable: true
  20214. });
  20215. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  20216. /**
  20217. * Gets or sets the rotation Quaternion property : this a Quaternion object defining the node rotation by using a unit quaternion (null by default).
  20218. * If set, only the rotationQuaternion is then used to compute the node rotation (ie. node.rotation will be ignored)
  20219. */
  20220. get: function () {
  20221. return this._rotationQuaternion;
  20222. },
  20223. set: function (quaternion) {
  20224. this._rotationQuaternion = quaternion;
  20225. //reset the rotation vector.
  20226. if (quaternion) {
  20227. this.rotation.setAll(0.0);
  20228. }
  20229. },
  20230. enumerable: true,
  20231. configurable: true
  20232. });
  20233. Object.defineProperty(TransformNode.prototype, "forward", {
  20234. /**
  20235. * The forward direction of that transform in world space.
  20236. */
  20237. get: function () {
  20238. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  20239. },
  20240. enumerable: true,
  20241. configurable: true
  20242. });
  20243. Object.defineProperty(TransformNode.prototype, "up", {
  20244. /**
  20245. * The up direction of that transform in world space.
  20246. */
  20247. get: function () {
  20248. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  20249. },
  20250. enumerable: true,
  20251. configurable: true
  20252. });
  20253. Object.defineProperty(TransformNode.prototype, "right", {
  20254. /**
  20255. * The right direction of that transform in world space.
  20256. */
  20257. get: function () {
  20258. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  20259. },
  20260. enumerable: true,
  20261. configurable: true
  20262. });
  20263. /**
  20264. * Copies the parameter passed Matrix into the mesh Pose matrix.
  20265. * @param matrix the matrix to copy the pose from
  20266. * @returns this TransformNode.
  20267. */
  20268. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  20269. this._poseMatrix.copyFrom(matrix);
  20270. return this;
  20271. };
  20272. /**
  20273. * Returns the mesh Pose matrix.
  20274. * @returns the pose matrix
  20275. */
  20276. TransformNode.prototype.getPoseMatrix = function () {
  20277. return this._poseMatrix;
  20278. };
  20279. /** @hidden */
  20280. TransformNode.prototype._isSynchronized = function () {
  20281. if (this._isDirty) {
  20282. return false;
  20283. }
  20284. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  20285. return false;
  20286. }
  20287. if (this._cache.pivotMatrixUpdated) {
  20288. return false;
  20289. }
  20290. if (this.infiniteDistance) {
  20291. return false;
  20292. }
  20293. if (!this._cache.position.equals(this._position)) {
  20294. return false;
  20295. }
  20296. if (this._rotationQuaternion) {
  20297. if (!this._cache.rotationQuaternion.equals(this._rotationQuaternion)) {
  20298. return false;
  20299. }
  20300. }
  20301. if (!this._cache.rotation.equals(this._rotation)) {
  20302. return false;
  20303. }
  20304. if (!this._cache.scaling.equals(this._scaling)) {
  20305. return false;
  20306. }
  20307. return true;
  20308. };
  20309. /** @hidden */
  20310. TransformNode.prototype._initCache = function () {
  20311. _super.prototype._initCache.call(this);
  20312. this._cache.localMatrixUpdated = false;
  20313. this._cache.position = BABYLON.Vector3.Zero();
  20314. this._cache.scaling = BABYLON.Vector3.Zero();
  20315. this._cache.rotation = BABYLON.Vector3.Zero();
  20316. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  20317. this._cache.billboardMode = -1;
  20318. this._cache.infiniteDistance = false;
  20319. };
  20320. /**
  20321. * Flag the transform node as dirty (Forcing it to update everything)
  20322. * @param property if set to "rotation" the objects rotationQuaternion will be set to null
  20323. * @returns this transform node
  20324. */
  20325. TransformNode.prototype.markAsDirty = function (property) {
  20326. if (property === "rotation") {
  20327. this.rotationQuaternion = null;
  20328. }
  20329. this._currentRenderId = Number.MAX_VALUE;
  20330. this._isDirty = true;
  20331. return this;
  20332. };
  20333. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  20334. /**
  20335. * Returns the current mesh absolute position.
  20336. * Returns a Vector3.
  20337. */
  20338. get: function () {
  20339. return this._absolutePosition;
  20340. },
  20341. enumerable: true,
  20342. configurable: true
  20343. });
  20344. /**
  20345. * Sets a new matrix to apply before all other transformation
  20346. * @param matrix defines the transform matrix
  20347. * @returns the current TransformNode
  20348. */
  20349. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  20350. return this.setPivotMatrix(matrix, false);
  20351. };
  20352. /**
  20353. * Sets a new pivot matrix to the current node
  20354. * @param matrix defines the new pivot matrix to use
  20355. * @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
  20356. * @returns the current TransformNode
  20357. */
  20358. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  20359. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  20360. this._pivotMatrix.copyFrom(matrix);
  20361. this._cache.pivotMatrixUpdated = true;
  20362. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  20363. if (this._postMultiplyPivotMatrix) {
  20364. if (!this._pivotMatrixInverse) {
  20365. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  20366. }
  20367. else {
  20368. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  20369. }
  20370. }
  20371. return this;
  20372. };
  20373. /**
  20374. * Returns the mesh pivot matrix.
  20375. * Default : Identity.
  20376. * @returns the matrix
  20377. */
  20378. TransformNode.prototype.getPivotMatrix = function () {
  20379. return this._pivotMatrix;
  20380. };
  20381. /**
  20382. * Prevents the World matrix to be computed any longer.
  20383. * @returns the TransformNode.
  20384. */
  20385. TransformNode.prototype.freezeWorldMatrix = function () {
  20386. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  20387. this.computeWorldMatrix(true);
  20388. this._isWorldMatrixFrozen = true;
  20389. return this;
  20390. };
  20391. /**
  20392. * Allows back the World matrix computation.
  20393. * @returns the TransformNode.
  20394. */
  20395. TransformNode.prototype.unfreezeWorldMatrix = function () {
  20396. this._isWorldMatrixFrozen = false;
  20397. this.computeWorldMatrix(true);
  20398. return this;
  20399. };
  20400. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  20401. /**
  20402. * True if the World matrix has been frozen.
  20403. */
  20404. get: function () {
  20405. return this._isWorldMatrixFrozen;
  20406. },
  20407. enumerable: true,
  20408. configurable: true
  20409. });
  20410. /**
  20411. * Retuns the mesh absolute position in the World.
  20412. * @returns a Vector3.
  20413. */
  20414. TransformNode.prototype.getAbsolutePosition = function () {
  20415. this.computeWorldMatrix();
  20416. return this._absolutePosition;
  20417. };
  20418. /**
  20419. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  20420. * @param absolutePosition the absolute position to set
  20421. * @returns the TransformNode.
  20422. */
  20423. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  20424. if (!absolutePosition) {
  20425. return this;
  20426. }
  20427. var absolutePositionX;
  20428. var absolutePositionY;
  20429. var absolutePositionZ;
  20430. if (absolutePosition.x === undefined) {
  20431. if (arguments.length < 3) {
  20432. return this;
  20433. }
  20434. absolutePositionX = arguments[0];
  20435. absolutePositionY = arguments[1];
  20436. absolutePositionZ = arguments[2];
  20437. }
  20438. else {
  20439. absolutePositionX = absolutePosition.x;
  20440. absolutePositionY = absolutePosition.y;
  20441. absolutePositionZ = absolutePosition.z;
  20442. }
  20443. if (this.parent) {
  20444. var invertParentWorldMatrix = BABYLON.Tmp.Matrix[0];
  20445. this.parent.getWorldMatrix().invertToRef(invertParentWorldMatrix);
  20446. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(absolutePositionX, absolutePositionY, absolutePositionZ, invertParentWorldMatrix, this.position);
  20447. }
  20448. else {
  20449. this.position.x = absolutePositionX;
  20450. this.position.y = absolutePositionY;
  20451. this.position.z = absolutePositionZ;
  20452. }
  20453. return this;
  20454. };
  20455. /**
  20456. * Sets the mesh position in its local space.
  20457. * @param vector3 the position to set in localspace
  20458. * @returns the TransformNode.
  20459. */
  20460. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  20461. this.computeWorldMatrix();
  20462. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localMatrix);
  20463. return this;
  20464. };
  20465. /**
  20466. * Returns the mesh position in the local space from the current World matrix values.
  20467. * @returns a new Vector3.
  20468. */
  20469. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  20470. this.computeWorldMatrix();
  20471. var invLocalWorldMatrix = BABYLON.Tmp.Matrix[0];
  20472. this._localMatrix.invertToRef(invLocalWorldMatrix);
  20473. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  20474. };
  20475. /**
  20476. * Translates the mesh along the passed Vector3 in its local space.
  20477. * @param vector3 the distance to translate in localspace
  20478. * @returns the TransformNode.
  20479. */
  20480. TransformNode.prototype.locallyTranslate = function (vector3) {
  20481. this.computeWorldMatrix(true);
  20482. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localMatrix);
  20483. return this;
  20484. };
  20485. /**
  20486. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  20487. * @param targetPoint the position (must be in same space as current mesh) to look at
  20488. * @param yawCor optional yaw (y-axis) correction in radians
  20489. * @param pitchCor optional pitch (x-axis) correction in radians
  20490. * @param rollCor optional roll (z-axis) correction in radians
  20491. * @param space the choosen space of the target
  20492. * @returns the TransformNode.
  20493. */
  20494. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  20495. if (yawCor === void 0) { yawCor = 0; }
  20496. if (pitchCor === void 0) { pitchCor = 0; }
  20497. if (rollCor === void 0) { rollCor = 0; }
  20498. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  20499. var dv = TransformNode._lookAtVectorCache;
  20500. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  20501. targetPoint.subtractToRef(pos, dv);
  20502. this.setDirection(dv, yawCor, pitchCor, rollCor);
  20503. // Correct for parent's rotation offset
  20504. if (space === BABYLON.Space.WORLD && this.parent) {
  20505. if (this.rotationQuaternion) {
  20506. // Get local rotation matrix of the looking object
  20507. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  20508. this.rotationQuaternion.toRotationMatrix(rotationMatrix);
  20509. // Offset rotation by parent's inverted rotation matrix to correct in world space
  20510. var parentRotationMatrix = BABYLON.Tmp.Matrix[1];
  20511. this.parent.getWorldMatrix().getRotationMatrixToRef(parentRotationMatrix);
  20512. parentRotationMatrix.invert();
  20513. rotationMatrix.multiplyToRef(parentRotationMatrix, rotationMatrix);
  20514. this.rotationQuaternion.fromRotationMatrix(rotationMatrix);
  20515. }
  20516. else {
  20517. // Get local rotation matrix of the looking object
  20518. var quaternionRotation = BABYLON.Tmp.Quaternion[0];
  20519. BABYLON.Quaternion.FromEulerVectorToRef(this.rotation, quaternionRotation);
  20520. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  20521. quaternionRotation.toRotationMatrix(rotationMatrix);
  20522. // Offset rotation by parent's inverted rotation matrix to correct in world space
  20523. var parentRotationMatrix = BABYLON.Tmp.Matrix[1];
  20524. this.parent.getWorldMatrix().getRotationMatrixToRef(parentRotationMatrix);
  20525. parentRotationMatrix.invert();
  20526. rotationMatrix.multiplyToRef(parentRotationMatrix, rotationMatrix);
  20527. quaternionRotation.fromRotationMatrix(rotationMatrix);
  20528. quaternionRotation.toEulerAnglesToRef(this.rotation);
  20529. }
  20530. }
  20531. return this;
  20532. };
  20533. /**
  20534. * Returns a new Vector3 that is the localAxis, expressed in the mesh local space, rotated like the mesh.
  20535. * This Vector3 is expressed in the World space.
  20536. * @param localAxis axis to rotate
  20537. * @returns a new Vector3 that is the localAxis, expressed in the mesh local space, rotated like the mesh.
  20538. */
  20539. TransformNode.prototype.getDirection = function (localAxis) {
  20540. var result = BABYLON.Vector3.Zero();
  20541. this.getDirectionToRef(localAxis, result);
  20542. return result;
  20543. };
  20544. /**
  20545. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  20546. * localAxis is expressed in the mesh local space.
  20547. * result is computed in the Wordl space from the mesh World matrix.
  20548. * @param localAxis axis to rotate
  20549. * @param result the resulting transformnode
  20550. * @returns this TransformNode.
  20551. */
  20552. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  20553. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  20554. return this;
  20555. };
  20556. /**
  20557. * Sets this transform node rotation to the given local axis.
  20558. * @param localAxis the axis in local space
  20559. * @param yawCor optional yaw (y-axis) correction in radians
  20560. * @param pitchCor optional pitch (x-axis) correction in radians
  20561. * @param rollCor optional roll (z-axis) correction in radians
  20562. * @returns this TransformNode
  20563. */
  20564. TransformNode.prototype.setDirection = function (localAxis, yawCor, pitchCor, rollCor) {
  20565. if (yawCor === void 0) { yawCor = 0; }
  20566. if (pitchCor === void 0) { pitchCor = 0; }
  20567. if (rollCor === void 0) { rollCor = 0; }
  20568. var yaw = -Math.atan2(localAxis.z, localAxis.x) + Math.PI / 2;
  20569. var len = Math.sqrt(localAxis.x * localAxis.x + localAxis.z * localAxis.z);
  20570. var pitch = -Math.atan2(localAxis.y, len);
  20571. if (this.rotationQuaternion) {
  20572. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  20573. }
  20574. else {
  20575. this.rotation.x = pitch + pitchCor;
  20576. this.rotation.y = yaw + yawCor;
  20577. this.rotation.z = rollCor;
  20578. }
  20579. return this;
  20580. };
  20581. /**
  20582. * Sets a new pivot point to the current node
  20583. * @param point defines the new pivot point to use
  20584. * @param space defines if the point is in world or local space (local by default)
  20585. * @returns the current TransformNode
  20586. */
  20587. TransformNode.prototype.setPivotPoint = function (point, space) {
  20588. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  20589. if (this.getScene().getRenderId() == 0) {
  20590. this.computeWorldMatrix(true);
  20591. }
  20592. var wm = this.getWorldMatrix();
  20593. if (space == BABYLON.Space.WORLD) {
  20594. var tmat = BABYLON.Tmp.Matrix[0];
  20595. wm.invertToRef(tmat);
  20596. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  20597. }
  20598. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  20599. };
  20600. /**
  20601. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  20602. * @returns the pivot point
  20603. */
  20604. TransformNode.prototype.getPivotPoint = function () {
  20605. var point = BABYLON.Vector3.Zero();
  20606. this.getPivotPointToRef(point);
  20607. return point;
  20608. };
  20609. /**
  20610. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  20611. * @param result the vector3 to store the result
  20612. * @returns this TransformNode.
  20613. */
  20614. TransformNode.prototype.getPivotPointToRef = function (result) {
  20615. result.x = -this._pivotMatrix.m[12];
  20616. result.y = -this._pivotMatrix.m[13];
  20617. result.z = -this._pivotMatrix.m[14];
  20618. return this;
  20619. };
  20620. /**
  20621. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  20622. * @returns a new Vector3 set with the mesh pivot point World coordinates.
  20623. */
  20624. TransformNode.prototype.getAbsolutePivotPoint = function () {
  20625. var point = BABYLON.Vector3.Zero();
  20626. this.getAbsolutePivotPointToRef(point);
  20627. return point;
  20628. };
  20629. /**
  20630. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  20631. * @param result vector3 to store the result
  20632. * @returns this TransformNode.
  20633. */
  20634. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  20635. result.x = this._pivotMatrix.m[12];
  20636. result.y = this._pivotMatrix.m[13];
  20637. result.z = this._pivotMatrix.m[14];
  20638. this.getPivotPointToRef(result);
  20639. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  20640. return this;
  20641. };
  20642. /**
  20643. * Defines the passed node as the parent of the current node.
  20644. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  20645. * @param node the node ot set as the parent
  20646. * @returns this TransformNode.
  20647. */
  20648. TransformNode.prototype.setParent = function (node) {
  20649. if (!node && !this.parent) {
  20650. return this;
  20651. }
  20652. var quatRotation = BABYLON.Tmp.Quaternion[0];
  20653. var position = BABYLON.Tmp.Vector3[0];
  20654. var scale = BABYLON.Tmp.Vector3[1];
  20655. if (!node) {
  20656. if (this.parent && this.parent.computeWorldMatrix) {
  20657. this.parent.computeWorldMatrix(true);
  20658. }
  20659. this.computeWorldMatrix(true);
  20660. this.getWorldMatrix().decompose(scale, quatRotation, position);
  20661. }
  20662. else {
  20663. var diffMatrix = BABYLON.Tmp.Matrix[0];
  20664. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  20665. this.computeWorldMatrix(true);
  20666. node.computeWorldMatrix(true);
  20667. node.getWorldMatrix().invertToRef(invParentMatrix);
  20668. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  20669. diffMatrix.decompose(scale, quatRotation, position);
  20670. }
  20671. if (this.rotationQuaternion) {
  20672. this.rotationQuaternion.copyFrom(quatRotation);
  20673. }
  20674. else {
  20675. quatRotation.toEulerAnglesToRef(this.rotation);
  20676. }
  20677. this.scaling.copyFrom(scale);
  20678. this.position.copyFrom(position);
  20679. this.parent = node;
  20680. return this;
  20681. };
  20682. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  20683. /**
  20684. * True if the scaling property of this object is non uniform eg. (1,2,1)
  20685. */
  20686. get: function () {
  20687. return this._nonUniformScaling;
  20688. },
  20689. enumerable: true,
  20690. configurable: true
  20691. });
  20692. /** @hidden */
  20693. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  20694. if (this._nonUniformScaling === value) {
  20695. return false;
  20696. }
  20697. this._nonUniformScaling = value;
  20698. return true;
  20699. };
  20700. /**
  20701. * Attach the current TransformNode to another TransformNode associated with a bone
  20702. * @param bone Bone affecting the TransformNode
  20703. * @param affectedTransformNode TransformNode associated with the bone
  20704. * @returns this object
  20705. */
  20706. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  20707. this._transformToBoneReferal = affectedTransformNode;
  20708. this.parent = bone;
  20709. if (bone.getWorldMatrix().determinant() < 0) {
  20710. this.scalingDeterminant *= -1;
  20711. }
  20712. return this;
  20713. };
  20714. /**
  20715. * Detach the transform node if its associated with a bone
  20716. * @returns this object
  20717. */
  20718. TransformNode.prototype.detachFromBone = function () {
  20719. if (!this.parent) {
  20720. return this;
  20721. }
  20722. if (this.parent.getWorldMatrix().determinant() < 0) {
  20723. this.scalingDeterminant *= -1;
  20724. }
  20725. this._transformToBoneReferal = null;
  20726. this.parent = null;
  20727. return this;
  20728. };
  20729. /**
  20730. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  20731. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  20732. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  20733. * The passed axis is also normalized.
  20734. * @param axis the axis to rotate around
  20735. * @param amount the amount to rotate in radians
  20736. * @param space Space to rotate in (Default: local)
  20737. * @returns the TransformNode.
  20738. */
  20739. TransformNode.prototype.rotate = function (axis, amount, space) {
  20740. axis.normalize();
  20741. if (!this.rotationQuaternion) {
  20742. this.rotationQuaternion = this.rotation.toQuaternion();
  20743. this.rotation.setAll(0);
  20744. }
  20745. var rotationQuaternion;
  20746. if (!space || space === BABYLON.Space.LOCAL) {
  20747. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  20748. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  20749. }
  20750. else {
  20751. if (this.parent) {
  20752. var invertParentWorldMatrix = BABYLON.Tmp.Matrix[0];
  20753. this.parent.getWorldMatrix().invertToRef(invertParentWorldMatrix);
  20754. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  20755. }
  20756. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  20757. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  20758. }
  20759. return this;
  20760. };
  20761. /**
  20762. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  20763. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  20764. * The passed axis is also normalized. .
  20765. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  20766. * @param point the point to rotate around
  20767. * @param axis the axis to rotate around
  20768. * @param amount the amount to rotate in radians
  20769. * @returns the TransformNode
  20770. */
  20771. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  20772. axis.normalize();
  20773. if (!this.rotationQuaternion) {
  20774. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  20775. this.rotation.setAll(0);
  20776. }
  20777. var tmpVector = BABYLON.Tmp.Vector3[0];
  20778. var finalScale = BABYLON.Tmp.Vector3[1];
  20779. var finalTranslation = BABYLON.Tmp.Vector3[2];
  20780. var finalRotation = BABYLON.Tmp.Quaternion[0];
  20781. var translationMatrix = BABYLON.Tmp.Matrix[0]; // T
  20782. var translationMatrixInv = BABYLON.Tmp.Matrix[1]; // T'
  20783. var rotationMatrix = BABYLON.Tmp.Matrix[2]; // R
  20784. var finalMatrix = BABYLON.Tmp.Matrix[3]; // T' x R x T
  20785. point.subtractToRef(this.position, tmpVector);
  20786. BABYLON.Matrix.TranslationToRef(tmpVector.x, tmpVector.y, tmpVector.z, translationMatrix); // T
  20787. BABYLON.Matrix.TranslationToRef(-tmpVector.x, -tmpVector.y, -tmpVector.z, translationMatrixInv); // T'
  20788. BABYLON.Matrix.RotationAxisToRef(axis, amount, rotationMatrix); // R
  20789. translationMatrixInv.multiplyToRef(rotationMatrix, finalMatrix); // T' x R
  20790. finalMatrix.multiplyToRef(translationMatrix, finalMatrix); // T' x R x T
  20791. finalMatrix.decompose(finalScale, finalRotation, finalTranslation);
  20792. this.position.addInPlace(finalTranslation);
  20793. finalRotation.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  20794. return this;
  20795. };
  20796. /**
  20797. * Translates the mesh along the axis vector for the passed distance in the given space.
  20798. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  20799. * @param axis the axis to translate in
  20800. * @param distance the distance to translate
  20801. * @param space Space to rotate in (Default: local)
  20802. * @returns the TransformNode.
  20803. */
  20804. TransformNode.prototype.translate = function (axis, distance, space) {
  20805. var displacementVector = axis.scale(distance);
  20806. if (!space || space === BABYLON.Space.LOCAL) {
  20807. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  20808. this.setPositionWithLocalVector(tempV3);
  20809. }
  20810. else {
  20811. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  20812. }
  20813. return this;
  20814. };
  20815. /**
  20816. * Adds a rotation step to the mesh current rotation.
  20817. * x, y, z are Euler angles expressed in radians.
  20818. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  20819. * This means this rotation is made in the mesh local space only.
  20820. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  20821. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  20822. * ```javascript
  20823. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  20824. * ```
  20825. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  20826. * 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.
  20827. * @param x Rotation to add
  20828. * @param y Rotation to add
  20829. * @param z Rotation to add
  20830. * @returns the TransformNode.
  20831. */
  20832. TransformNode.prototype.addRotation = function (x, y, z) {
  20833. var rotationQuaternion;
  20834. if (this.rotationQuaternion) {
  20835. rotationQuaternion = this.rotationQuaternion;
  20836. }
  20837. else {
  20838. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  20839. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  20840. }
  20841. var accumulation = BABYLON.Tmp.Quaternion[0];
  20842. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  20843. rotationQuaternion.multiplyInPlace(accumulation);
  20844. if (!this.rotationQuaternion) {
  20845. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  20846. }
  20847. return this;
  20848. };
  20849. /**
  20850. * Computes the world matrix of the node
  20851. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  20852. * @returns the world matrix
  20853. */
  20854. TransformNode.prototype.computeWorldMatrix = function (force) {
  20855. if (this._isWorldMatrixFrozen) {
  20856. return this._worldMatrix;
  20857. }
  20858. if (!force && this.isSynchronized()) {
  20859. this._currentRenderId = this.getScene().getRenderId();
  20860. return this._worldMatrix;
  20861. }
  20862. this._updateCache();
  20863. this._cache.position.copyFrom(this.position);
  20864. this._cache.scaling.copyFrom(this.scaling);
  20865. this._cache.pivotMatrixUpdated = false;
  20866. this._cache.billboardMode = this.billboardMode;
  20867. this._cache.infiniteDistance = this.infiniteDistance;
  20868. this._currentRenderId = this.getScene().getRenderId();
  20869. this._childRenderId = this.getScene().getRenderId();
  20870. this._isDirty = false;
  20871. // Scaling
  20872. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  20873. // Rotation
  20874. //rotate, if quaternion is set and rotation was used
  20875. if (this.rotationQuaternion) {
  20876. var len = this.rotation.length();
  20877. if (len) {
  20878. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  20879. this.rotation.copyFromFloats(0, 0, 0);
  20880. }
  20881. }
  20882. if (this.rotationQuaternion) {
  20883. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  20884. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  20885. }
  20886. else {
  20887. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  20888. this._cache.rotation.copyFrom(this.rotation);
  20889. }
  20890. // Translation
  20891. var camera = this.getScene().activeCamera;
  20892. if (this.infiniteDistance && !this.parent && camera) {
  20893. var cameraWorldMatrix = camera.getWorldMatrix();
  20894. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  20895. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  20896. }
  20897. else {
  20898. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  20899. }
  20900. // Composing transformations
  20901. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  20902. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  20903. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  20904. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  20905. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  20906. // Need to decompose each rotation here
  20907. var currentPosition = BABYLON.Tmp.Vector3[3];
  20908. if (this.parent && this.parent.getWorldMatrix) {
  20909. if (this._transformToBoneReferal) {
  20910. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  20911. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  20912. }
  20913. else {
  20914. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  20915. }
  20916. }
  20917. else {
  20918. currentPosition.copyFrom(this.position);
  20919. }
  20920. currentPosition.subtractInPlace(camera.globalPosition);
  20921. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  20922. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  20923. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  20924. }
  20925. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  20926. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  20927. }
  20928. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  20929. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  20930. }
  20931. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  20932. }
  20933. else {
  20934. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  20935. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  20936. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  20937. }
  20938. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  20939. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  20940. }
  20941. // Post multiply inverse of pivotMatrix
  20942. if (this._postMultiplyPivotMatrix) {
  20943. BABYLON.Tmp.Matrix[5].multiplyToRef(this._pivotMatrixInverse, BABYLON.Tmp.Matrix[5]);
  20944. }
  20945. // Local world
  20946. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localMatrix);
  20947. // Parent
  20948. if (this.parent && this.parent.getWorldMatrix) {
  20949. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  20950. if (this._transformToBoneReferal) {
  20951. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  20952. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  20953. }
  20954. else {
  20955. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  20956. }
  20957. this._localMatrix.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  20958. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  20959. this._worldMatrix.copyFrom(this._localMatrix);
  20960. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  20961. }
  20962. else {
  20963. if (this._transformToBoneReferal) {
  20964. this._localMatrix.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  20965. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  20966. }
  20967. else {
  20968. this._localMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  20969. }
  20970. }
  20971. this._markSyncedWithParent();
  20972. }
  20973. else {
  20974. this._worldMatrix.copyFrom(this._localMatrix);
  20975. }
  20976. // Normal matrix
  20977. if (!this.ignoreNonUniformScaling) {
  20978. if (this.scaling.isNonUniform) {
  20979. this._updateNonUniformScalingState(true);
  20980. }
  20981. else if (this.parent && this.parent._nonUniformScaling) {
  20982. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  20983. }
  20984. else {
  20985. this._updateNonUniformScalingState(false);
  20986. }
  20987. }
  20988. else {
  20989. this._updateNonUniformScalingState(false);
  20990. }
  20991. this._afterComputeWorldMatrix();
  20992. // Absolute position
  20993. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  20994. // Callbacks
  20995. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  20996. if (!this._poseMatrix) {
  20997. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  20998. }
  20999. // Cache the determinant
  21000. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  21001. return this._worldMatrix;
  21002. };
  21003. TransformNode.prototype._afterComputeWorldMatrix = function () {
  21004. };
  21005. /**
  21006. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  21007. * @param func callback function to add
  21008. *
  21009. * @returns the TransformNode.
  21010. */
  21011. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  21012. this.onAfterWorldMatrixUpdateObservable.add(func);
  21013. return this;
  21014. };
  21015. /**
  21016. * Removes a registered callback function.
  21017. * @param func callback function to remove
  21018. * @returns the TransformNode.
  21019. */
  21020. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  21021. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  21022. return this;
  21023. };
  21024. /**
  21025. * Gets the position of the current mesh in camera space
  21026. * @param camera defines the camera to use
  21027. * @returns a position
  21028. */
  21029. TransformNode.prototype.getPositionInCameraSpace = function (camera) {
  21030. if (camera === void 0) { camera = null; }
  21031. if (!camera) {
  21032. camera = this.getScene().activeCamera;
  21033. }
  21034. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  21035. };
  21036. /**
  21037. * Returns the distance from the mesh to the active camera
  21038. * @param camera defines the camera to use
  21039. * @returns the distance
  21040. */
  21041. TransformNode.prototype.getDistanceToCamera = function (camera) {
  21042. if (camera === void 0) { camera = null; }
  21043. if (!camera) {
  21044. camera = this.getScene().activeCamera;
  21045. }
  21046. return this.absolutePosition.subtract(camera.position).length();
  21047. };
  21048. /**
  21049. * Clone the current transform node
  21050. * @param name Name of the new clone
  21051. * @param newParent New parent for the clone
  21052. * @param doNotCloneChildren Do not clone children hierarchy
  21053. * @returns the new transform node
  21054. */
  21055. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  21056. var _this = this;
  21057. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  21058. result.name = name;
  21059. result.id = name;
  21060. if (newParent) {
  21061. result.parent = newParent;
  21062. }
  21063. if (!doNotCloneChildren) {
  21064. // Children
  21065. var directDescendants = this.getDescendants(true);
  21066. for (var index = 0; index < directDescendants.length; index++) {
  21067. var child = directDescendants[index];
  21068. if (child.clone) {
  21069. child.clone(name + "." + child.name, result);
  21070. }
  21071. }
  21072. }
  21073. return result;
  21074. };
  21075. /**
  21076. * Serializes the objects information.
  21077. * @param currentSerializationObject defines the object to serialize in
  21078. * @returns the serialized object
  21079. */
  21080. TransformNode.prototype.serialize = function (currentSerializationObject) {
  21081. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  21082. serializationObject.type = this.getClassName();
  21083. // Parent
  21084. if (this.parent) {
  21085. serializationObject.parentId = this.parent.id;
  21086. }
  21087. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  21088. serializationObject.tags = BABYLON.Tags.GetTags(this);
  21089. }
  21090. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  21091. serializationObject.isEnabled = this.isEnabled();
  21092. // Parent
  21093. if (this.parent) {
  21094. serializationObject.parentId = this.parent.id;
  21095. }
  21096. return serializationObject;
  21097. };
  21098. // Statics
  21099. /**
  21100. * Returns a new TransformNode object parsed from the source provided.
  21101. * @param parsedTransformNode is the source.
  21102. * @param scene the scne the object belongs to
  21103. * @param rootUrl is a string, it's the root URL to prefix the `delayLoadingFile` property with
  21104. * @returns a new TransformNode object parsed from the source provided.
  21105. */
  21106. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  21107. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  21108. if (BABYLON.Tags) {
  21109. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  21110. }
  21111. if (parsedTransformNode.localMatrix) {
  21112. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  21113. }
  21114. else if (parsedTransformNode.pivotMatrix) {
  21115. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  21116. }
  21117. transformNode.setEnabled(parsedTransformNode.isEnabled);
  21118. // Parent
  21119. if (parsedTransformNode.parentId) {
  21120. transformNode._waitingParentId = parsedTransformNode.parentId;
  21121. }
  21122. return transformNode;
  21123. };
  21124. /**
  21125. * Releases resources associated with this transform node.
  21126. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21127. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21128. */
  21129. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21130. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21131. // Animations
  21132. this.getScene().stopAnimation(this);
  21133. // Remove from scene
  21134. this.getScene().removeTransformNode(this);
  21135. this.onAfterWorldMatrixUpdateObservable.clear();
  21136. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21137. };
  21138. // Statics
  21139. /**
  21140. * Object will not rotate to face the camera
  21141. */
  21142. TransformNode.BILLBOARDMODE_NONE = 0;
  21143. /**
  21144. * Object will rotate to face the camera but only on the x axis
  21145. */
  21146. TransformNode.BILLBOARDMODE_X = 1;
  21147. /**
  21148. * Object will rotate to face the camera but only on the y axis
  21149. */
  21150. TransformNode.BILLBOARDMODE_Y = 2;
  21151. /**
  21152. * Object will rotate to face the camera but only on the z axis
  21153. */
  21154. TransformNode.BILLBOARDMODE_Z = 4;
  21155. /**
  21156. * Object will rotate to face the camera
  21157. */
  21158. TransformNode.BILLBOARDMODE_ALL = 7;
  21159. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  21160. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  21161. __decorate([
  21162. BABYLON.serializeAsVector3("position")
  21163. ], TransformNode.prototype, "_position", void 0);
  21164. __decorate([
  21165. BABYLON.serializeAsVector3("rotation")
  21166. ], TransformNode.prototype, "_rotation", void 0);
  21167. __decorate([
  21168. BABYLON.serializeAsQuaternion("rotationQuaternion")
  21169. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  21170. __decorate([
  21171. BABYLON.serializeAsVector3("scaling")
  21172. ], TransformNode.prototype, "_scaling", void 0);
  21173. __decorate([
  21174. BABYLON.serialize()
  21175. ], TransformNode.prototype, "billboardMode", void 0);
  21176. __decorate([
  21177. BABYLON.serialize()
  21178. ], TransformNode.prototype, "scalingDeterminant", void 0);
  21179. __decorate([
  21180. BABYLON.serialize()
  21181. ], TransformNode.prototype, "infiniteDistance", void 0);
  21182. __decorate([
  21183. BABYLON.serialize()
  21184. ], TransformNode.prototype, "ignoreNonUniformScaling", void 0);
  21185. return TransformNode;
  21186. }(BABYLON.Node));
  21187. BABYLON.TransformNode = TransformNode;
  21188. })(BABYLON || (BABYLON = {}));
  21189. //# sourceMappingURL=babylon.transformNode.js.map
  21190. var BABYLON;
  21191. (function (BABYLON) {
  21192. /** @hidden */
  21193. var _FacetDataStorage = /** @class */ (function () {
  21194. function _FacetDataStorage() {
  21195. this.facetNb = 0; // facet number
  21196. this.partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  21197. this.partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  21198. this.facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  21199. this.facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  21200. this.bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  21201. this.subDiv = {
  21202. max: 1,
  21203. X: 1,
  21204. Y: 1,
  21205. Z: 1
  21206. };
  21207. this.facetDepthSort = false; // is the facet depth sort to be computed
  21208. this.facetDepthSortEnabled = false; // is the facet depth sort initialized
  21209. }
  21210. return _FacetDataStorage;
  21211. }());
  21212. /**
  21213. * Class used to store all common mesh properties
  21214. */
  21215. var AbstractMesh = /** @class */ (function (_super) {
  21216. __extends(AbstractMesh, _super);
  21217. // Constructor
  21218. /**
  21219. * Creates a new AbstractMesh
  21220. * @param name defines the name of the mesh
  21221. * @param scene defines the hosting scene
  21222. */
  21223. function AbstractMesh(name, scene) {
  21224. if (scene === void 0) { scene = null; }
  21225. var _this = _super.call(this, name, scene, false) || this;
  21226. _this._facetData = new _FacetDataStorage();
  21227. /**
  21228. * The culling strategy to use to check whether the mesh must be rendered or not.
  21229. * This value can be changed at any time and will be used on the next render mesh selection.
  21230. * The possible values are :
  21231. * - AbstractMesh.CULLINGSTRATEGY_STANDARD
  21232. * - AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY
  21233. * - AbstractMesh.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION
  21234. * - AbstractMesh.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY
  21235. * Please read each static variable documentation to get details about the culling process.
  21236. * */
  21237. _this.cullingStrategy = AbstractMesh.CULLINGSTRATEGY_STANDARD;
  21238. // Events
  21239. /**
  21240. * An event triggered when this mesh collides with another one
  21241. */
  21242. _this.onCollideObservable = new BABYLON.Observable();
  21243. /**
  21244. * An event triggered when the collision's position changes
  21245. */
  21246. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  21247. /**
  21248. * An event triggered when material is changed
  21249. */
  21250. _this.onMaterialChangedObservable = new BABYLON.Observable();
  21251. // Properties
  21252. /**
  21253. * Gets or sets the orientation for POV movement & rotation
  21254. */
  21255. _this.definedFacingForward = true;
  21256. _this._visibility = 1.0;
  21257. /** Gets or sets the alpha index used to sort transparent meshes
  21258. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index
  21259. */
  21260. _this.alphaIndex = Number.MAX_VALUE;
  21261. /**
  21262. * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true
  21263. */
  21264. _this.isVisible = true;
  21265. /**
  21266. * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true
  21267. */
  21268. _this.isPickable = true;
  21269. /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */
  21270. _this.showSubMeshesBoundingBox = false;
  21271. /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default)
  21272. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  21273. */
  21274. _this.isBlocker = false;
  21275. /**
  21276. * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default)
  21277. */
  21278. _this.enablePointerMoveEvents = false;
  21279. /**
  21280. * Specifies the rendering group id for this mesh (0 by default)
  21281. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups
  21282. */
  21283. _this.renderingGroupId = 0;
  21284. _this._receiveShadows = false;
  21285. /** Defines color to use when rendering outline */
  21286. _this.outlineColor = BABYLON.Color3.Red();
  21287. /** Define width to use when rendering outline */
  21288. _this.outlineWidth = 0.02;
  21289. /** Defines color to use when rendering overlay */
  21290. _this.overlayColor = BABYLON.Color3.Red();
  21291. /** Defines alpha to use when rendering overlay */
  21292. _this.overlayAlpha = 0.5;
  21293. _this._hasVertexAlpha = false;
  21294. _this._useVertexColors = true;
  21295. _this._computeBonesUsingShaders = true;
  21296. _this._numBoneInfluencers = 4;
  21297. _this._applyFog = true;
  21298. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */
  21299. _this.useOctreeForRenderingSelection = true;
  21300. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */
  21301. _this.useOctreeForPicking = true;
  21302. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */
  21303. _this.useOctreeForCollisions = true;
  21304. _this._layerMask = 0x0FFFFFFF;
  21305. /**
  21306. * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase)
  21307. */
  21308. _this.alwaysSelectAsActiveMesh = false;
  21309. /**
  21310. * Gets or sets the current action manager
  21311. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  21312. */
  21313. _this.actionManager = null;
  21314. // Collisions
  21315. _this._checkCollisions = false;
  21316. _this._collisionMask = -1;
  21317. _this._collisionGroup = -1;
  21318. /**
  21319. * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5))
  21320. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  21321. */
  21322. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  21323. /**
  21324. * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0))
  21325. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  21326. */
  21327. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  21328. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  21329. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  21330. // Edges
  21331. /**
  21332. * Defines edge width used when edgesRenderer is enabled
  21333. * @see https://www.babylonjs-playground.com/#10OJSG#13
  21334. */
  21335. _this.edgesWidth = 1;
  21336. /**
  21337. * Defines edge color used when edgesRenderer is enabled
  21338. * @see https://www.babylonjs-playground.com/#10OJSG#13
  21339. */
  21340. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  21341. /** @hidden */
  21342. _this._renderId = 0;
  21343. /** @hidden */
  21344. _this._intersectionsInProgress = new Array();
  21345. /** @hidden */
  21346. _this._unIndexed = false;
  21347. /** @hidden */
  21348. _this._lightSources = new Array();
  21349. /**
  21350. * An event triggered when the mesh is rebuilt.
  21351. */
  21352. _this.onRebuildObservable = new BABYLON.Observable();
  21353. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  21354. if (collidedMesh === void 0) { collidedMesh = null; }
  21355. //TODO move this to the collision coordinator!
  21356. if (_this.getScene().workerCollisions) {
  21357. newPosition.multiplyInPlace(_this._collider._radius);
  21358. }
  21359. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  21360. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  21361. _this.position.addInPlace(_this._diffPositionForCollisions);
  21362. }
  21363. if (collidedMesh) {
  21364. _this.onCollideObservable.notifyObservers(collidedMesh);
  21365. }
  21366. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  21367. };
  21368. _this.getScene().addMesh(_this);
  21369. _this._resyncLightSources();
  21370. return _this;
  21371. }
  21372. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  21373. /**
  21374. * No billboard
  21375. */
  21376. get: function () {
  21377. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  21378. },
  21379. enumerable: true,
  21380. configurable: true
  21381. });
  21382. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  21383. /** Billboard on X axis */
  21384. get: function () {
  21385. return BABYLON.TransformNode.BILLBOARDMODE_X;
  21386. },
  21387. enumerable: true,
  21388. configurable: true
  21389. });
  21390. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  21391. /** Billboard on Y axis */
  21392. get: function () {
  21393. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  21394. },
  21395. enumerable: true,
  21396. configurable: true
  21397. });
  21398. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  21399. /** Billboard on Z axis */
  21400. get: function () {
  21401. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  21402. },
  21403. enumerable: true,
  21404. configurable: true
  21405. });
  21406. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  21407. /** Billboard on all axes */
  21408. get: function () {
  21409. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  21410. },
  21411. enumerable: true,
  21412. configurable: true
  21413. });
  21414. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  21415. /**
  21416. * Gets the number of facets in the mesh
  21417. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  21418. */
  21419. get: function () {
  21420. return this._facetData.facetNb;
  21421. },
  21422. enumerable: true,
  21423. configurable: true
  21424. });
  21425. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  21426. /**
  21427. * Gets or set the number (integer) of subdivisions per axis in the partioning space
  21428. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  21429. */
  21430. get: function () {
  21431. return this._facetData.partitioningSubdivisions;
  21432. },
  21433. set: function (nb) {
  21434. this._facetData.partitioningSubdivisions = nb;
  21435. },
  21436. enumerable: true,
  21437. configurable: true
  21438. });
  21439. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  21440. /**
  21441. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  21442. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box
  21443. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  21444. */
  21445. get: function () {
  21446. return this._facetData.partitioningBBoxRatio;
  21447. },
  21448. set: function (ratio) {
  21449. this._facetData.partitioningBBoxRatio = ratio;
  21450. },
  21451. enumerable: true,
  21452. configurable: true
  21453. });
  21454. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  21455. /**
  21456. * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`.
  21457. * Works only for updatable meshes.
  21458. * Doesn't work with multi-materials
  21459. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  21460. */
  21461. get: function () {
  21462. return this._facetData.facetDepthSort;
  21463. },
  21464. set: function (sort) {
  21465. this._facetData.facetDepthSort = sort;
  21466. },
  21467. enumerable: true,
  21468. configurable: true
  21469. });
  21470. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  21471. /**
  21472. * The location (Vector3) where the facet depth sort must be computed from.
  21473. * By default, the active camera position.
  21474. * Used only when facet depth sort is enabled
  21475. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  21476. */
  21477. get: function () {
  21478. return this._facetData.facetDepthSortFrom;
  21479. },
  21480. set: function (location) {
  21481. this._facetData.facetDepthSortFrom = location;
  21482. },
  21483. enumerable: true,
  21484. configurable: true
  21485. });
  21486. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  21487. /**
  21488. * gets a boolean indicating if facetData is enabled
  21489. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  21490. */
  21491. get: function () {
  21492. return this._facetData.facetDataEnabled;
  21493. },
  21494. enumerable: true,
  21495. configurable: true
  21496. });
  21497. /** @hidden */
  21498. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  21499. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  21500. return false;
  21501. }
  21502. this._markSubMeshesAsMiscDirty();
  21503. return true;
  21504. };
  21505. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  21506. /** Set a function to call when this mesh collides with another one */
  21507. set: function (callback) {
  21508. if (this._onCollideObserver) {
  21509. this.onCollideObservable.remove(this._onCollideObserver);
  21510. }
  21511. this._onCollideObserver = this.onCollideObservable.add(callback);
  21512. },
  21513. enumerable: true,
  21514. configurable: true
  21515. });
  21516. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  21517. /** Set a function to call when the collision's position changes */
  21518. set: function (callback) {
  21519. if (this._onCollisionPositionChangeObserver) {
  21520. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  21521. }
  21522. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  21523. },
  21524. enumerable: true,
  21525. configurable: true
  21526. });
  21527. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  21528. /**
  21529. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  21530. */
  21531. get: function () {
  21532. return this._visibility;
  21533. },
  21534. /**
  21535. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  21536. */
  21537. set: function (value) {
  21538. if (this._visibility === value) {
  21539. return;
  21540. }
  21541. this._visibility = value;
  21542. this._markSubMeshesAsMiscDirty();
  21543. },
  21544. enumerable: true,
  21545. configurable: true
  21546. });
  21547. Object.defineProperty(AbstractMesh.prototype, "material", {
  21548. /** Gets or sets current material */
  21549. get: function () {
  21550. return this._material;
  21551. },
  21552. set: function (value) {
  21553. if (this._material === value) {
  21554. return;
  21555. }
  21556. // remove from material mesh map id needed
  21557. if (this._material && this._material.meshMap) {
  21558. this._material.meshMap[this.uniqueId] = undefined;
  21559. }
  21560. this._material = value;
  21561. if (value && value.meshMap) {
  21562. value.meshMap[this.uniqueId] = this;
  21563. }
  21564. if (this.onMaterialChangedObservable.hasObservers) {
  21565. this.onMaterialChangedObservable.notifyObservers(this);
  21566. }
  21567. if (!this.subMeshes) {
  21568. return;
  21569. }
  21570. this._unBindEffect();
  21571. },
  21572. enumerable: true,
  21573. configurable: true
  21574. });
  21575. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  21576. /**
  21577. * Gets or sets a boolean indicating that this mesh can receive realtime shadows
  21578. * @see http://doc.babylonjs.com/babylon101/shadows
  21579. */
  21580. get: function () {
  21581. return this._receiveShadows;
  21582. },
  21583. set: function (value) {
  21584. if (this._receiveShadows === value) {
  21585. return;
  21586. }
  21587. this._receiveShadows = value;
  21588. this._markSubMeshesAsLightDirty();
  21589. },
  21590. enumerable: true,
  21591. configurable: true
  21592. });
  21593. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  21594. /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */
  21595. get: function () {
  21596. return this._hasVertexAlpha;
  21597. },
  21598. set: function (value) {
  21599. if (this._hasVertexAlpha === value) {
  21600. return;
  21601. }
  21602. this._hasVertexAlpha = value;
  21603. this._markSubMeshesAsAttributesDirty();
  21604. this._markSubMeshesAsMiscDirty();
  21605. },
  21606. enumerable: true,
  21607. configurable: true
  21608. });
  21609. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  21610. /** 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) */
  21611. get: function () {
  21612. return this._useVertexColors;
  21613. },
  21614. set: function (value) {
  21615. if (this._useVertexColors === value) {
  21616. return;
  21617. }
  21618. this._useVertexColors = value;
  21619. this._markSubMeshesAsAttributesDirty();
  21620. },
  21621. enumerable: true,
  21622. configurable: true
  21623. });
  21624. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  21625. /**
  21626. * Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default)
  21627. */
  21628. get: function () {
  21629. return this._computeBonesUsingShaders;
  21630. },
  21631. set: function (value) {
  21632. if (this._computeBonesUsingShaders === value) {
  21633. return;
  21634. }
  21635. this._computeBonesUsingShaders = value;
  21636. this._markSubMeshesAsAttributesDirty();
  21637. },
  21638. enumerable: true,
  21639. configurable: true
  21640. });
  21641. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  21642. /** Gets or sets the number of allowed bone influences per vertex (4 by default) */
  21643. get: function () {
  21644. return this._numBoneInfluencers;
  21645. },
  21646. set: function (value) {
  21647. if (this._numBoneInfluencers === value) {
  21648. return;
  21649. }
  21650. this._numBoneInfluencers = value;
  21651. this._markSubMeshesAsAttributesDirty();
  21652. },
  21653. enumerable: true,
  21654. configurable: true
  21655. });
  21656. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  21657. /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */
  21658. get: function () {
  21659. return this._applyFog;
  21660. },
  21661. set: function (value) {
  21662. if (this._applyFog === value) {
  21663. return;
  21664. }
  21665. this._applyFog = value;
  21666. this._markSubMeshesAsMiscDirty();
  21667. },
  21668. enumerable: true,
  21669. configurable: true
  21670. });
  21671. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  21672. /**
  21673. * Gets or sets the current layer mask (default is 0x0FFFFFFF)
  21674. * @see http://doc.babylonjs.com/how_to/layermasks_and_multi-cam_textures
  21675. */
  21676. get: function () {
  21677. return this._layerMask;
  21678. },
  21679. set: function (value) {
  21680. if (value === this._layerMask) {
  21681. return;
  21682. }
  21683. this._layerMask = value;
  21684. this._resyncLightSources();
  21685. },
  21686. enumerable: true,
  21687. configurable: true
  21688. });
  21689. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  21690. /**
  21691. * Gets or sets a collision mask used to mask collisions (default is -1).
  21692. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  21693. */
  21694. get: function () {
  21695. return this._collisionMask;
  21696. },
  21697. set: function (mask) {
  21698. this._collisionMask = !isNaN(mask) ? mask : -1;
  21699. },
  21700. enumerable: true,
  21701. configurable: true
  21702. });
  21703. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  21704. /**
  21705. * Gets or sets the current collision group mask (-1 by default).
  21706. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  21707. */
  21708. get: function () {
  21709. return this._collisionGroup;
  21710. },
  21711. set: function (mask) {
  21712. this._collisionGroup = !isNaN(mask) ? mask : -1;
  21713. },
  21714. enumerable: true,
  21715. configurable: true
  21716. });
  21717. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  21718. /** @hidden */
  21719. get: function () {
  21720. return null;
  21721. },
  21722. enumerable: true,
  21723. configurable: true
  21724. });
  21725. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  21726. get: function () {
  21727. return this._skeleton;
  21728. },
  21729. /**
  21730. * Gets or sets a skeleton to apply skining transformations
  21731. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  21732. */
  21733. set: function (value) {
  21734. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  21735. this._skeleton._unregisterMeshWithPoseMatrix(this);
  21736. }
  21737. if (value && value.needInitialSkinMatrix) {
  21738. value._registerMeshWithPoseMatrix(this);
  21739. }
  21740. this._skeleton = value;
  21741. if (!this._skeleton) {
  21742. this._bonesTransformMatrices = null;
  21743. }
  21744. this._markSubMeshesAsAttributesDirty();
  21745. },
  21746. enumerable: true,
  21747. configurable: true
  21748. });
  21749. /**
  21750. * Returns the string "AbstractMesh"
  21751. * @returns "AbstractMesh"
  21752. */
  21753. AbstractMesh.prototype.getClassName = function () {
  21754. return "AbstractMesh";
  21755. };
  21756. /**
  21757. * Gets a string representation of the current mesh
  21758. * @param fullDetails defines a boolean indicating if full details must be included
  21759. * @returns a string representation of the current mesh
  21760. */
  21761. AbstractMesh.prototype.toString = function (fullDetails) {
  21762. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  21763. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  21764. if (this._skeleton) {
  21765. ret += ", skeleton: " + this._skeleton.name;
  21766. }
  21767. if (fullDetails) {
  21768. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  21769. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  21770. }
  21771. return ret;
  21772. };
  21773. /** @hidden */
  21774. AbstractMesh.prototype._rebuild = function () {
  21775. this.onRebuildObservable.notifyObservers(this);
  21776. if (this._occlusionQuery) {
  21777. this._occlusionQuery = null;
  21778. }
  21779. if (!this.subMeshes) {
  21780. return;
  21781. }
  21782. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  21783. var subMesh = _a[_i];
  21784. subMesh._rebuild();
  21785. }
  21786. };
  21787. /** @hidden */
  21788. AbstractMesh.prototype._resyncLightSources = function () {
  21789. this._lightSources.length = 0;
  21790. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  21791. var light = _a[_i];
  21792. if (!light.isEnabled()) {
  21793. continue;
  21794. }
  21795. if (light.canAffectMesh(this)) {
  21796. this._lightSources.push(light);
  21797. }
  21798. }
  21799. this._markSubMeshesAsLightDirty();
  21800. };
  21801. /** @hidden */
  21802. AbstractMesh.prototype._resyncLighSource = function (light) {
  21803. var isIn = light.isEnabled() && light.canAffectMesh(this);
  21804. var index = this._lightSources.indexOf(light);
  21805. if (index === -1) {
  21806. if (!isIn) {
  21807. return;
  21808. }
  21809. this._lightSources.push(light);
  21810. }
  21811. else {
  21812. if (isIn) {
  21813. return;
  21814. }
  21815. this._lightSources.splice(index, 1);
  21816. }
  21817. this._markSubMeshesAsLightDirty();
  21818. };
  21819. /** @hidden */
  21820. AbstractMesh.prototype._unBindEffect = function () {
  21821. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  21822. var subMesh = _a[_i];
  21823. subMesh.setEffect(null);
  21824. }
  21825. };
  21826. /** @hidden */
  21827. AbstractMesh.prototype._removeLightSource = function (light) {
  21828. var index = this._lightSources.indexOf(light);
  21829. if (index === -1) {
  21830. return;
  21831. }
  21832. this._lightSources.splice(index, 1);
  21833. this._markSubMeshesAsLightDirty();
  21834. };
  21835. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  21836. if (!this.subMeshes) {
  21837. return;
  21838. }
  21839. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  21840. var subMesh = _a[_i];
  21841. if (subMesh._materialDefines) {
  21842. func(subMesh._materialDefines);
  21843. }
  21844. }
  21845. };
  21846. /** @hidden */
  21847. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  21848. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  21849. };
  21850. /** @hidden */
  21851. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  21852. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  21853. };
  21854. /** @hidden */
  21855. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  21856. if (!this.subMeshes) {
  21857. return;
  21858. }
  21859. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  21860. var subMesh = _a[_i];
  21861. var material = subMesh.getMaterial();
  21862. if (material) {
  21863. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  21864. }
  21865. }
  21866. };
  21867. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  21868. /**
  21869. * Gets or sets a Vector3 depicting the mesh scaling along each local axis X, Y, Z. Default is (1.0, 1.0, 1.0)
  21870. */
  21871. get: function () {
  21872. return this._scaling;
  21873. },
  21874. set: function (newScaling) {
  21875. this._scaling = newScaling;
  21876. if (this.physicsImpostor) {
  21877. this.physicsImpostor.forceUpdate();
  21878. }
  21879. },
  21880. enumerable: true,
  21881. configurable: true
  21882. });
  21883. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  21884. // Methods
  21885. /**
  21886. * Returns true if the mesh is blocked. Implemented by child classes
  21887. */
  21888. get: function () {
  21889. return false;
  21890. },
  21891. enumerable: true,
  21892. configurable: true
  21893. });
  21894. /**
  21895. * Returns the mesh itself by default. Implemented by child classes
  21896. * @param camera defines the camera to use to pick the right LOD level
  21897. * @returns the currentAbstractMesh
  21898. */
  21899. AbstractMesh.prototype.getLOD = function (camera) {
  21900. return this;
  21901. };
  21902. /**
  21903. * Returns 0 by default. Implemented by child classes
  21904. * @returns an integer
  21905. */
  21906. AbstractMesh.prototype.getTotalVertices = function () {
  21907. return 0;
  21908. };
  21909. /**
  21910. * Returns a positive integer : the total number of indices in this mesh geometry.
  21911. * @returns the numner of indices or zero if the mesh has no geometry.
  21912. */
  21913. AbstractMesh.prototype.getTotalIndices = function () {
  21914. return 0;
  21915. };
  21916. /**
  21917. * Returns null by default. Implemented by child classes
  21918. * @returns null
  21919. */
  21920. AbstractMesh.prototype.getIndices = function () {
  21921. return null;
  21922. };
  21923. /**
  21924. * Returns the array of the requested vertex data kind. Implemented by child classes
  21925. * @param kind defines the vertex data kind to use
  21926. * @returns null
  21927. */
  21928. AbstractMesh.prototype.getVerticesData = function (kind) {
  21929. return null;
  21930. };
  21931. /**
  21932. * Sets the vertex data of the mesh geometry for the requested `kind`.
  21933. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  21934. * Note that a new underlying VertexBuffer object is created each call.
  21935. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  21936. * @param kind defines vertex data kind:
  21937. * * BABYLON.VertexBuffer.PositionKind
  21938. * * BABYLON.VertexBuffer.UVKind
  21939. * * BABYLON.VertexBuffer.UV2Kind
  21940. * * BABYLON.VertexBuffer.UV3Kind
  21941. * * BABYLON.VertexBuffer.UV4Kind
  21942. * * BABYLON.VertexBuffer.UV5Kind
  21943. * * BABYLON.VertexBuffer.UV6Kind
  21944. * * BABYLON.VertexBuffer.ColorKind
  21945. * * BABYLON.VertexBuffer.MatricesIndicesKind
  21946. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21947. * * BABYLON.VertexBuffer.MatricesWeightsKind
  21948. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21949. * @param data defines the data source
  21950. * @param updatable defines if the data must be flagged as updatable (or static)
  21951. * @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
  21952. * @returns the current mesh
  21953. */
  21954. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  21955. return this;
  21956. };
  21957. /**
  21958. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  21959. * If the mesh has no geometry, it is simply returned as it is.
  21960. * @param kind defines vertex data kind:
  21961. * * BABYLON.VertexBuffer.PositionKind
  21962. * * BABYLON.VertexBuffer.UVKind
  21963. * * BABYLON.VertexBuffer.UV2Kind
  21964. * * BABYLON.VertexBuffer.UV3Kind
  21965. * * BABYLON.VertexBuffer.UV4Kind
  21966. * * BABYLON.VertexBuffer.UV5Kind
  21967. * * BABYLON.VertexBuffer.UV6Kind
  21968. * * BABYLON.VertexBuffer.ColorKind
  21969. * * BABYLON.VertexBuffer.MatricesIndicesKind
  21970. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21971. * * BABYLON.VertexBuffer.MatricesWeightsKind
  21972. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21973. * @param data defines the data source
  21974. * @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
  21975. * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh
  21976. * @returns the current mesh
  21977. */
  21978. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  21979. return this;
  21980. };
  21981. /**
  21982. * Sets the mesh indices,
  21983. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  21984. * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  21985. * @param totalVertices Defines the total number of vertices
  21986. * @returns the current mesh
  21987. */
  21988. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  21989. return this;
  21990. };
  21991. /**
  21992. * Gets a boolean indicating if specific vertex data is present
  21993. * @param kind defines the vertex data kind to use
  21994. * @returns true is data kind is present
  21995. */
  21996. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  21997. return false;
  21998. };
  21999. /**
  22000. * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined
  22001. * @returns a BoundingInfo
  22002. */
  22003. AbstractMesh.prototype.getBoundingInfo = function () {
  22004. if (this._masterMesh) {
  22005. return this._masterMesh.getBoundingInfo();
  22006. }
  22007. if (!this._boundingInfo) {
  22008. // this._boundingInfo is being created here
  22009. this._updateBoundingInfo();
  22010. }
  22011. // cannot be null.
  22012. return this._boundingInfo;
  22013. };
  22014. /**
  22015. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)
  22016. * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box
  22017. * @returns the current mesh
  22018. */
  22019. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  22020. if (includeDescendants === void 0) { includeDescendants = true; }
  22021. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  22022. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  22023. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  22024. if (maxDimension === 0) {
  22025. return this;
  22026. }
  22027. var scale = 1 / maxDimension;
  22028. this.scaling.scaleInPlace(scale);
  22029. return this;
  22030. };
  22031. /**
  22032. * Overwrite the current bounding info
  22033. * @param boundingInfo defines the new bounding info
  22034. * @returns the current mesh
  22035. */
  22036. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  22037. this._boundingInfo = boundingInfo;
  22038. return this;
  22039. };
  22040. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  22041. /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */
  22042. get: function () {
  22043. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  22044. },
  22045. enumerable: true,
  22046. configurable: true
  22047. });
  22048. /** @hidden */
  22049. AbstractMesh.prototype._preActivate = function () {
  22050. };
  22051. /** @hidden */
  22052. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  22053. };
  22054. /** @hidden */
  22055. AbstractMesh.prototype._activate = function (renderId) {
  22056. this._renderId = renderId;
  22057. };
  22058. /**
  22059. * Gets the current world matrix
  22060. * @returns a Matrix
  22061. */
  22062. AbstractMesh.prototype.getWorldMatrix = function () {
  22063. if (this._masterMesh) {
  22064. return this._masterMesh.getWorldMatrix();
  22065. }
  22066. return _super.prototype.getWorldMatrix.call(this);
  22067. };
  22068. /** @hidden */
  22069. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  22070. if (this._masterMesh) {
  22071. return this._masterMesh._getWorldMatrixDeterminant();
  22072. }
  22073. return _super.prototype._getWorldMatrixDeterminant.call(this);
  22074. };
  22075. // ================================== Point of View Movement =================================
  22076. /**
  22077. * Perform relative position change from the point of view of behind the front of the mesh.
  22078. * This is performed taking into account the meshes current rotation, so you do not have to care.
  22079. * Supports definition of mesh facing forward or backward
  22080. * @param amountRight defines the distance on the right axis
  22081. * @param amountUp defines the distance on the up axis
  22082. * @param amountForward defines the distance on the forward axis
  22083. * @returns the current mesh
  22084. */
  22085. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  22086. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  22087. return this;
  22088. };
  22089. /**
  22090. * Calculate relative position change from the point of view of behind the front of the mesh.
  22091. * This is performed taking into account the meshes current rotation, so you do not have to care.
  22092. * Supports definition of mesh facing forward or backward
  22093. * @param amountRight defines the distance on the right axis
  22094. * @param amountUp defines the distance on the up axis
  22095. * @param amountForward defines the distance on the forward axis
  22096. * @returns the new displacement vector
  22097. */
  22098. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  22099. var rotMatrix = new BABYLON.Matrix();
  22100. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  22101. rotQuaternion.toRotationMatrix(rotMatrix);
  22102. var translationDelta = BABYLON.Vector3.Zero();
  22103. var defForwardMult = this.definedFacingForward ? -1 : 1;
  22104. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  22105. return translationDelta;
  22106. };
  22107. // ================================== Point of View Rotation =================================
  22108. /**
  22109. * Perform relative rotation change from the point of view of behind the front of the mesh.
  22110. * Supports definition of mesh facing forward or backward
  22111. * @param flipBack defines the flip
  22112. * @param twirlClockwise defines the twirl
  22113. * @param tiltRight defines the tilt
  22114. * @returns the current mesh
  22115. */
  22116. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  22117. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  22118. return this;
  22119. };
  22120. /**
  22121. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  22122. * Supports definition of mesh facing forward or backward.
  22123. * @param flipBack defines the flip
  22124. * @param twirlClockwise defines the twirl
  22125. * @param tiltRight defines the tilt
  22126. * @returns the new rotation vector
  22127. */
  22128. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  22129. var defForwardMult = this.definedFacingForward ? 1 : -1;
  22130. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  22131. };
  22132. /**
  22133. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  22134. * @param includeDescendants Include bounding info from descendants as well (true by default)
  22135. * @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
  22136. * @returns the new bounding vectors
  22137. */
  22138. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants, predicate) {
  22139. if (includeDescendants === void 0) { includeDescendants = true; }
  22140. if (predicate === void 0) { predicate = null; }
  22141. // Ensures that all world matrix will be recomputed.
  22142. this.getScene().incrementRenderId();
  22143. this.computeWorldMatrix(true);
  22144. var min;
  22145. var max;
  22146. var boundingInfo = this.getBoundingInfo();
  22147. if (!this.subMeshes) {
  22148. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22149. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  22150. }
  22151. else {
  22152. min = boundingInfo.boundingBox.minimumWorld;
  22153. max = boundingInfo.boundingBox.maximumWorld;
  22154. }
  22155. if (includeDescendants) {
  22156. var descendants = this.getDescendants(false);
  22157. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  22158. var descendant = descendants_1[_i];
  22159. var childMesh = descendant;
  22160. childMesh.computeWorldMatrix(true);
  22161. // Filters meshes based on custom predicate function.
  22162. if (predicate && !predicate(childMesh)) {
  22163. continue;
  22164. }
  22165. //make sure we have the needed params to get mix and max
  22166. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  22167. continue;
  22168. }
  22169. var childBoundingInfo = childMesh.getBoundingInfo();
  22170. var boundingBox = childBoundingInfo.boundingBox;
  22171. var minBox = boundingBox.minimumWorld;
  22172. var maxBox = boundingBox.maximumWorld;
  22173. BABYLON.Tools.CheckExtends(minBox, min, max);
  22174. BABYLON.Tools.CheckExtends(maxBox, min, max);
  22175. }
  22176. }
  22177. return {
  22178. min: min,
  22179. max: max
  22180. };
  22181. };
  22182. /**
  22183. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  22184. * This means the mesh underlying bounding box and sphere are recomputed.
  22185. * @param applySkeleton defines whether to apply the skeleton before computing the bounding info
  22186. * @returns the current mesh
  22187. */
  22188. AbstractMesh.prototype.refreshBoundingInfo = function (applySkeleton) {
  22189. if (applySkeleton === void 0) { applySkeleton = false; }
  22190. if (this._boundingInfo && this._boundingInfo.isLocked) {
  22191. return this;
  22192. }
  22193. this._refreshBoundingInfo(this._getPositionData(applySkeleton), null);
  22194. return this;
  22195. };
  22196. /** @hidden */
  22197. AbstractMesh.prototype._refreshBoundingInfo = function (data, bias) {
  22198. if (data) {
  22199. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices(), bias);
  22200. if (this._boundingInfo) {
  22201. this._boundingInfo.reConstruct(extend.minimum, extend.maximum);
  22202. }
  22203. else {
  22204. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  22205. }
  22206. }
  22207. if (this.subMeshes) {
  22208. for (var index = 0; index < this.subMeshes.length; index++) {
  22209. this.subMeshes[index].refreshBoundingInfo();
  22210. }
  22211. }
  22212. this._updateBoundingInfo();
  22213. };
  22214. /** @hidden */
  22215. AbstractMesh.prototype._getPositionData = function (applySkeleton) {
  22216. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22217. if (data && applySkeleton && this.skeleton) {
  22218. data = BABYLON.Tools.Slice(data);
  22219. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  22220. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  22221. if (matricesWeightsData && matricesIndicesData) {
  22222. var needExtras = this.numBoneInfluencers > 4;
  22223. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  22224. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  22225. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  22226. var tempVector = BABYLON.Tmp.Vector3[0];
  22227. var finalMatrix = BABYLON.Tmp.Matrix[0];
  22228. var tempMatrix = BABYLON.Tmp.Matrix[1];
  22229. var matWeightIdx = 0;
  22230. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  22231. finalMatrix.reset();
  22232. var inf;
  22233. var weight;
  22234. for (inf = 0; inf < 4; inf++) {
  22235. weight = matricesWeightsData[matWeightIdx + inf];
  22236. if (weight > 0) {
  22237. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  22238. finalMatrix.addToSelf(tempMatrix);
  22239. }
  22240. }
  22241. if (needExtras) {
  22242. for (inf = 0; inf < 4; inf++) {
  22243. weight = matricesWeightsExtraData[matWeightIdx + inf];
  22244. if (weight > 0) {
  22245. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  22246. finalMatrix.addToSelf(tempMatrix);
  22247. }
  22248. }
  22249. }
  22250. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  22251. tempVector.toArray(data, index);
  22252. }
  22253. }
  22254. }
  22255. return data;
  22256. };
  22257. /** @hidden */
  22258. AbstractMesh.prototype._updateBoundingInfo = function () {
  22259. var effectiveMesh = (this.skeleton && this.skeleton.overrideMesh) || this;
  22260. if (this._boundingInfo) {
  22261. this._boundingInfo.update(effectiveMesh.worldMatrixFromCache);
  22262. }
  22263. else {
  22264. this._boundingInfo = new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition, effectiveMesh.worldMatrixFromCache);
  22265. }
  22266. this._updateSubMeshesBoundingInfo(effectiveMesh.worldMatrixFromCache);
  22267. return this;
  22268. };
  22269. /** @hidden */
  22270. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  22271. if (!this.subMeshes) {
  22272. return this;
  22273. }
  22274. var count = this.subMeshes.length;
  22275. for (var subIndex = 0; subIndex < count; subIndex++) {
  22276. var subMesh = this.subMeshes[subIndex];
  22277. if (count > 1 || !subMesh.IsGlobal) {
  22278. subMesh.updateBoundingInfo(matrix);
  22279. }
  22280. }
  22281. return this;
  22282. };
  22283. /** @hidden */
  22284. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  22285. // Bounding info
  22286. this._updateBoundingInfo();
  22287. };
  22288. /**
  22289. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  22290. * A mesh is in the frustum if its bounding box intersects the frustum
  22291. * @param frustumPlanes defines the frustum to test
  22292. * @returns true if the mesh is in the frustum planes
  22293. */
  22294. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  22295. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes, this.cullingStrategy);
  22296. };
  22297. /**
  22298. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  22299. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  22300. * @param frustumPlanes defines the frustum to test
  22301. * @returns true if the mesh is completely in the frustum planes
  22302. */
  22303. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  22304. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  22305. };
  22306. /**
  22307. * True if the mesh intersects another mesh or a SolidParticle object
  22308. * @param mesh defines a target mesh or SolidParticle to test
  22309. * @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)
  22310. * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  22311. * @returns true if there is an intersection
  22312. */
  22313. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  22314. if (precise === void 0) { precise = false; }
  22315. if (!this._boundingInfo || !mesh._boundingInfo) {
  22316. return false;
  22317. }
  22318. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  22319. return true;
  22320. }
  22321. if (includeDescendants) {
  22322. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  22323. var child = _a[_i];
  22324. if (child.intersectsMesh(mesh, precise, true)) {
  22325. return true;
  22326. }
  22327. }
  22328. }
  22329. return false;
  22330. };
  22331. /**
  22332. * Returns true if the passed point (Vector3) is inside the mesh bounding box
  22333. * @param point defines the point to test
  22334. * @returns true if there is an intersection
  22335. */
  22336. AbstractMesh.prototype.intersectsPoint = function (point) {
  22337. if (!this._boundingInfo) {
  22338. return false;
  22339. }
  22340. return this._boundingInfo.intersectsPoint(point);
  22341. };
  22342. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  22343. // Collisions
  22344. /**
  22345. * Gets or sets a boolean indicating that this mesh can be used in the collision engine
  22346. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  22347. */
  22348. get: function () {
  22349. return this._checkCollisions;
  22350. },
  22351. set: function (collisionEnabled) {
  22352. this._checkCollisions = collisionEnabled;
  22353. if (this.getScene().workerCollisions) {
  22354. this.getScene().collisionCoordinator.onMeshUpdated(this);
  22355. }
  22356. },
  22357. enumerable: true,
  22358. configurable: true
  22359. });
  22360. Object.defineProperty(AbstractMesh.prototype, "collider", {
  22361. /**
  22362. * Gets Collider object used to compute collisions (not physics)
  22363. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  22364. */
  22365. get: function () {
  22366. return this._collider;
  22367. },
  22368. enumerable: true,
  22369. configurable: true
  22370. });
  22371. /**
  22372. * Move the mesh using collision engine
  22373. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  22374. * @param displacement defines the requested displacement vector
  22375. * @returns the current mesh
  22376. */
  22377. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  22378. var globalPosition = this.getAbsolutePosition();
  22379. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  22380. if (!this._collider) {
  22381. this._collider = new BABYLON.Collider();
  22382. }
  22383. this._collider._radius = this.ellipsoid;
  22384. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  22385. return this;
  22386. };
  22387. // Collisions
  22388. /** @hidden */
  22389. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  22390. this._generatePointsArray();
  22391. if (!this._positions) {
  22392. return this;
  22393. }
  22394. // Transformation
  22395. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  22396. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  22397. subMesh._lastColliderWorldVertices = [];
  22398. subMesh._trianglePlanes = [];
  22399. var start = subMesh.verticesStart;
  22400. var end = (subMesh.verticesStart + subMesh.verticesCount);
  22401. for (var i = start; i < end; i++) {
  22402. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  22403. }
  22404. }
  22405. // Collide
  22406. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  22407. if (collider.collisionFound) {
  22408. collider.collidedMesh = this;
  22409. }
  22410. return this;
  22411. };
  22412. /** @hidden */
  22413. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  22414. var subMeshes = this._scene.getCollidingSubMeshCandidates(this, collider);
  22415. var len = subMeshes.length;
  22416. for (var index = 0; index < len; index++) {
  22417. var subMesh = subMeshes.data[index];
  22418. // Bounding test
  22419. if (len > 1 && !subMesh._checkCollision(collider)) {
  22420. continue;
  22421. }
  22422. this._collideForSubMesh(subMesh, transformMatrix, collider);
  22423. }
  22424. return this;
  22425. };
  22426. /** @hidden */
  22427. AbstractMesh.prototype._checkCollision = function (collider) {
  22428. // Bounding box test
  22429. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider)) {
  22430. return this;
  22431. }
  22432. // Transformation matrix
  22433. var collisionsScalingMatrix = BABYLON.Tmp.Matrix[0];
  22434. var collisionsTransformMatrix = BABYLON.Tmp.Matrix[1];
  22435. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, collisionsScalingMatrix);
  22436. this.worldMatrixFromCache.multiplyToRef(collisionsScalingMatrix, collisionsTransformMatrix);
  22437. this._processCollisionsForSubMeshes(collider, collisionsTransformMatrix);
  22438. return this;
  22439. };
  22440. // Picking
  22441. /** @hidden */
  22442. AbstractMesh.prototype._generatePointsArray = function () {
  22443. return false;
  22444. };
  22445. /**
  22446. * Checks if the passed Ray intersects with the mesh
  22447. * @param ray defines the ray to use
  22448. * @param fastCheck defines if fast mode (but less precise) must be used (false by default)
  22449. * @returns the picking info
  22450. * @see http://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  22451. */
  22452. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  22453. var pickingInfo = new BABYLON.PickingInfo();
  22454. var intersectionThreshold = this.getClassName() === "InstancedLinesMesh" || this.getClassName() === "LinesMesh" ? this.intersectionThreshold : 0;
  22455. var boundingInfo = this._boundingInfo;
  22456. if (!this.subMeshes || !boundingInfo || !ray.intersectsSphere(boundingInfo.boundingSphere, intersectionThreshold) || !ray.intersectsBox(boundingInfo.boundingBox, intersectionThreshold)) {
  22457. return pickingInfo;
  22458. }
  22459. if (!this._generatePointsArray()) {
  22460. return pickingInfo;
  22461. }
  22462. var intersectInfo = null;
  22463. var subMeshes = this._scene.getIntersectingSubMeshCandidates(this, ray);
  22464. var len = subMeshes.length;
  22465. for (var index = 0; index < len; index++) {
  22466. var subMesh = subMeshes.data[index];
  22467. // Bounding test
  22468. if (len > 1 && !subMesh.canIntersects(ray)) {
  22469. continue;
  22470. }
  22471. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  22472. if (currentIntersectInfo) {
  22473. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  22474. intersectInfo = currentIntersectInfo;
  22475. intersectInfo.subMeshId = index;
  22476. if (fastCheck) {
  22477. break;
  22478. }
  22479. }
  22480. }
  22481. }
  22482. if (intersectInfo) {
  22483. // Get picked point
  22484. var world = this.getWorldMatrix();
  22485. var worldOrigin = BABYLON.Tmp.Vector3[0];
  22486. var direction = BABYLON.Tmp.Vector3[1];
  22487. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, world, worldOrigin);
  22488. ray.direction.scaleToRef(intersectInfo.distance, direction);
  22489. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  22490. var pickedPoint = worldDirection.addInPlace(worldOrigin);
  22491. // Return result
  22492. pickingInfo.hit = true;
  22493. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  22494. pickingInfo.pickedPoint = pickedPoint;
  22495. pickingInfo.pickedMesh = this;
  22496. pickingInfo.bu = intersectInfo.bu || 0;
  22497. pickingInfo.bv = intersectInfo.bv || 0;
  22498. pickingInfo.faceId = intersectInfo.faceId;
  22499. pickingInfo.subMeshId = intersectInfo.subMeshId;
  22500. return pickingInfo;
  22501. }
  22502. return pickingInfo;
  22503. };
  22504. /**
  22505. * Clones the current mesh
  22506. * @param name defines the mesh name
  22507. * @param newParent defines the new mesh parent
  22508. * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default)
  22509. * @returns the new mesh
  22510. */
  22511. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  22512. return null;
  22513. };
  22514. /**
  22515. * Disposes all the submeshes of the current meshnp
  22516. * @returns the current mesh
  22517. */
  22518. AbstractMesh.prototype.releaseSubMeshes = function () {
  22519. if (this.subMeshes) {
  22520. while (this.subMeshes.length) {
  22521. this.subMeshes[0].dispose();
  22522. }
  22523. }
  22524. else {
  22525. this.subMeshes = new Array();
  22526. }
  22527. return this;
  22528. };
  22529. /**
  22530. * Releases resources associated with this abstract mesh.
  22531. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22532. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22533. */
  22534. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22535. var _this = this;
  22536. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22537. var index;
  22538. // Smart Array Retainers.
  22539. this.getScene().freeActiveMeshes();
  22540. this.getScene().freeRenderingGroups();
  22541. // Action manager
  22542. if (this.actionManager !== undefined && this.actionManager !== null) {
  22543. this.actionManager.dispose();
  22544. this.actionManager = null;
  22545. }
  22546. // Skeleton
  22547. this._skeleton = null;
  22548. // Intersections in progress
  22549. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  22550. var other = this._intersectionsInProgress[index];
  22551. var pos = other._intersectionsInProgress.indexOf(this);
  22552. other._intersectionsInProgress.splice(pos, 1);
  22553. }
  22554. this._intersectionsInProgress = [];
  22555. // Lights
  22556. var lights = this.getScene().lights;
  22557. lights.forEach(function (light) {
  22558. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  22559. if (meshIndex !== -1) {
  22560. light.includedOnlyMeshes.splice(meshIndex, 1);
  22561. }
  22562. meshIndex = light.excludedMeshes.indexOf(_this);
  22563. if (meshIndex !== -1) {
  22564. light.excludedMeshes.splice(meshIndex, 1);
  22565. }
  22566. // Shadow generators
  22567. var generator = light.getShadowGenerator();
  22568. if (generator) {
  22569. var shadowMap = generator.getShadowMap();
  22570. if (shadowMap && shadowMap.renderList) {
  22571. meshIndex = shadowMap.renderList.indexOf(_this);
  22572. if (meshIndex !== -1) {
  22573. shadowMap.renderList.splice(meshIndex, 1);
  22574. }
  22575. }
  22576. }
  22577. });
  22578. // SubMeshes
  22579. if (this.getClassName() !== "InstancedMesh" || this.getClassName() !== "InstancedLinesMesh") {
  22580. this.releaseSubMeshes();
  22581. }
  22582. // Query
  22583. var engine = this.getScene().getEngine();
  22584. if (this._occlusionQuery) {
  22585. this.isOcclusionQueryInProgress = false;
  22586. engine.deleteQuery(this._occlusionQuery);
  22587. this._occlusionQuery = null;
  22588. }
  22589. // Engine
  22590. engine.wipeCaches();
  22591. // Remove from scene
  22592. this.getScene().removeMesh(this);
  22593. if (disposeMaterialAndTextures) {
  22594. if (this.material) {
  22595. this.material.dispose(false, true);
  22596. }
  22597. }
  22598. if (!doNotRecurse) {
  22599. // Particles
  22600. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  22601. if (this.getScene().particleSystems[index].emitter === this) {
  22602. this.getScene().particleSystems[index].dispose();
  22603. index--;
  22604. }
  22605. }
  22606. }
  22607. // facet data
  22608. if (this._facetData.facetDataEnabled) {
  22609. this.disableFacetData();
  22610. }
  22611. this.onAfterWorldMatrixUpdateObservable.clear();
  22612. this.onCollideObservable.clear();
  22613. this.onCollisionPositionChangeObservable.clear();
  22614. this.onRebuildObservable.clear();
  22615. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22616. };
  22617. /**
  22618. * Adds the passed mesh as a child to the current mesh
  22619. * @param mesh defines the child mesh
  22620. * @returns the current mesh
  22621. */
  22622. AbstractMesh.prototype.addChild = function (mesh) {
  22623. mesh.setParent(this);
  22624. return this;
  22625. };
  22626. /**
  22627. * Removes the passed mesh from the current mesh children list
  22628. * @param mesh defines the child mesh
  22629. * @returns the current mesh
  22630. */
  22631. AbstractMesh.prototype.removeChild = function (mesh) {
  22632. mesh.setParent(null);
  22633. return this;
  22634. };
  22635. // Facet data
  22636. /** @hidden */
  22637. AbstractMesh.prototype._initFacetData = function () {
  22638. var data = this._facetData;
  22639. if (!data.facetNormals) {
  22640. data.facetNormals = new Array();
  22641. }
  22642. if (!data.facetPositions) {
  22643. data.facetPositions = new Array();
  22644. }
  22645. if (!data.facetPartitioning) {
  22646. data.facetPartitioning = new Array();
  22647. }
  22648. data.facetNb = (this.getIndices().length / 3) | 0;
  22649. data.partitioningSubdivisions = (data.partitioningSubdivisions) ? data.partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  22650. data.partitioningBBoxRatio = (data.partitioningBBoxRatio) ? data.partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  22651. for (var f = 0; f < data.facetNb; f++) {
  22652. data.facetNormals[f] = BABYLON.Vector3.Zero();
  22653. data.facetPositions[f] = BABYLON.Vector3.Zero();
  22654. }
  22655. data.facetDataEnabled = true;
  22656. return this;
  22657. };
  22658. /**
  22659. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  22660. * This method can be called within the render loop.
  22661. * 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
  22662. * @returns the current mesh
  22663. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22664. */
  22665. AbstractMesh.prototype.updateFacetData = function () {
  22666. var data = this._facetData;
  22667. if (!data.facetDataEnabled) {
  22668. this._initFacetData();
  22669. }
  22670. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22671. var indices = this.getIndices();
  22672. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22673. var bInfo = this.getBoundingInfo();
  22674. if (data.facetDepthSort && !data.facetDepthSortEnabled) {
  22675. // init arrays, matrix and sort function on first call
  22676. data.facetDepthSortEnabled = true;
  22677. if (indices instanceof Uint16Array) {
  22678. data.depthSortedIndices = new Uint16Array(indices);
  22679. }
  22680. else if (indices instanceof Uint32Array) {
  22681. data.depthSortedIndices = new Uint32Array(indices);
  22682. }
  22683. else {
  22684. var needs32bits = false;
  22685. for (var i = 0; i < indices.length; i++) {
  22686. if (indices[i] > 65535) {
  22687. needs32bits = true;
  22688. break;
  22689. }
  22690. }
  22691. if (needs32bits) {
  22692. data.depthSortedIndices = new Uint32Array(indices);
  22693. }
  22694. else {
  22695. data.depthSortedIndices = new Uint16Array(indices);
  22696. }
  22697. }
  22698. data.facetDepthSortFunction = function (f1, f2) {
  22699. return (f2.sqDistance - f1.sqDistance);
  22700. };
  22701. if (!data.facetDepthSortFrom) {
  22702. var camera = this.getScene().activeCamera;
  22703. data.facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  22704. }
  22705. data.depthSortedFacets = [];
  22706. for (var f = 0; f < data.facetNb; f++) {
  22707. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  22708. data.depthSortedFacets.push(depthSortedFacet);
  22709. }
  22710. data.invertedMatrix = BABYLON.Matrix.Identity();
  22711. data.facetDepthSortOrigin = BABYLON.Vector3.Zero();
  22712. }
  22713. data.bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  22714. data.bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  22715. data.bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  22716. var bbSizeMax = (data.bbSize.x > data.bbSize.y) ? data.bbSize.x : data.bbSize.y;
  22717. bbSizeMax = (bbSizeMax > data.bbSize.z) ? bbSizeMax : data.bbSize.z;
  22718. data.subDiv.max = data.partitioningSubdivisions;
  22719. data.subDiv.X = Math.floor(data.subDiv.max * data.bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  22720. data.subDiv.Y = Math.floor(data.subDiv.max * data.bbSize.y / bbSizeMax); // according to each bbox size per axis
  22721. data.subDiv.Z = Math.floor(data.subDiv.max * data.bbSize.z / bbSizeMax);
  22722. data.subDiv.X = data.subDiv.X < 1 ? 1 : data.subDiv.X; // at least one subdivision
  22723. data.subDiv.Y = data.subDiv.Y < 1 ? 1 : data.subDiv.Y;
  22724. data.subDiv.Z = data.subDiv.Z < 1 ? 1 : data.subDiv.Z;
  22725. // set the parameters for ComputeNormals()
  22726. data.facetParameters.facetNormals = this.getFacetLocalNormals();
  22727. data.facetParameters.facetPositions = this.getFacetLocalPositions();
  22728. data.facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  22729. data.facetParameters.bInfo = bInfo;
  22730. data.facetParameters.bbSize = data.bbSize;
  22731. data.facetParameters.subDiv = data.subDiv;
  22732. data.facetParameters.ratio = this.partitioningBBoxRatio;
  22733. data.facetParameters.depthSort = data.facetDepthSort;
  22734. if (data.facetDepthSort && data.facetDepthSortEnabled) {
  22735. this.computeWorldMatrix(true);
  22736. this._worldMatrix.invertToRef(data.invertedMatrix);
  22737. BABYLON.Vector3.TransformCoordinatesToRef(data.facetDepthSortFrom, data.invertedMatrix, data.facetDepthSortOrigin);
  22738. data.facetParameters.distanceTo = data.facetDepthSortOrigin;
  22739. }
  22740. data.facetParameters.depthSortedFacets = data.depthSortedFacets;
  22741. BABYLON.VertexData.ComputeNormals(positions, indices, normals, data.facetParameters);
  22742. if (data.facetDepthSort && data.facetDepthSortEnabled) {
  22743. data.depthSortedFacets.sort(data.facetDepthSortFunction);
  22744. var l = (data.depthSortedIndices.length / 3) | 0;
  22745. for (var f = 0; f < l; f++) {
  22746. var sind = data.depthSortedFacets[f].ind;
  22747. data.depthSortedIndices[f * 3] = indices[sind];
  22748. data.depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  22749. data.depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  22750. }
  22751. this.updateIndices(data.depthSortedIndices);
  22752. }
  22753. return this;
  22754. };
  22755. /**
  22756. * Returns the facetLocalNormals array.
  22757. * The normals are expressed in the mesh local spac
  22758. * @returns an array of Vector3
  22759. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22760. */
  22761. AbstractMesh.prototype.getFacetLocalNormals = function () {
  22762. if (!this._facetData.facetNormals) {
  22763. this.updateFacetData();
  22764. }
  22765. return this._facetData.facetNormals;
  22766. };
  22767. /**
  22768. * Returns the facetLocalPositions array.
  22769. * The facet positions are expressed in the mesh local space
  22770. * @returns an array of Vector3
  22771. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22772. */
  22773. AbstractMesh.prototype.getFacetLocalPositions = function () {
  22774. if (!this._facetData.facetPositions) {
  22775. this.updateFacetData();
  22776. }
  22777. return this._facetData.facetPositions;
  22778. };
  22779. /**
  22780. * Returns the facetLocalPartioning array
  22781. * @returns an array of array of numbers
  22782. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22783. */
  22784. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  22785. if (!this._facetData.facetPartitioning) {
  22786. this.updateFacetData();
  22787. }
  22788. return this._facetData.facetPartitioning;
  22789. };
  22790. /**
  22791. * Returns the i-th facet position in the world system.
  22792. * This method allocates a new Vector3 per call
  22793. * @param i defines the facet index
  22794. * @returns a new Vector3
  22795. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22796. */
  22797. AbstractMesh.prototype.getFacetPosition = function (i) {
  22798. var pos = BABYLON.Vector3.Zero();
  22799. this.getFacetPositionToRef(i, pos);
  22800. return pos;
  22801. };
  22802. /**
  22803. * Sets the reference Vector3 with the i-th facet position in the world system
  22804. * @param i defines the facet index
  22805. * @param ref defines the target vector
  22806. * @returns the current mesh
  22807. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22808. */
  22809. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  22810. var localPos = (this.getFacetLocalPositions())[i];
  22811. var world = this.getWorldMatrix();
  22812. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  22813. return this;
  22814. };
  22815. /**
  22816. * Returns the i-th facet normal in the world system.
  22817. * This method allocates a new Vector3 per call
  22818. * @param i defines the facet index
  22819. * @returns a new Vector3
  22820. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22821. */
  22822. AbstractMesh.prototype.getFacetNormal = function (i) {
  22823. var norm = BABYLON.Vector3.Zero();
  22824. this.getFacetNormalToRef(i, norm);
  22825. return norm;
  22826. };
  22827. /**
  22828. * Sets the reference Vector3 with the i-th facet normal in the world system
  22829. * @param i defines the facet index
  22830. * @param ref defines the target vector
  22831. * @returns the current mesh
  22832. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22833. */
  22834. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  22835. var localNorm = (this.getFacetLocalNormals())[i];
  22836. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  22837. return this;
  22838. };
  22839. /**
  22840. * 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)
  22841. * @param x defines x coordinate
  22842. * @param y defines y coordinate
  22843. * @param z defines z coordinate
  22844. * @returns the array of facet indexes
  22845. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22846. */
  22847. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  22848. var bInfo = this.getBoundingInfo();
  22849. var data = this._facetData;
  22850. var ox = Math.floor((x - bInfo.minimum.x * data.partitioningBBoxRatio) * data.subDiv.X * data.partitioningBBoxRatio / data.bbSize.x);
  22851. var oy = Math.floor((y - bInfo.minimum.y * data.partitioningBBoxRatio) * data.subDiv.Y * data.partitioningBBoxRatio / data.bbSize.y);
  22852. var oz = Math.floor((z - bInfo.minimum.z * data.partitioningBBoxRatio) * data.subDiv.Z * data.partitioningBBoxRatio / data.bbSize.z);
  22853. if (ox < 0 || ox > data.subDiv.max || oy < 0 || oy > data.subDiv.max || oz < 0 || oz > data.subDiv.max) {
  22854. return null;
  22855. }
  22856. return data.facetPartitioning[ox + data.subDiv.max * oy + data.subDiv.max * data.subDiv.max * oz];
  22857. };
  22858. /**
  22859. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found
  22860. * @param projected sets as the (x,y,z) world projection on the facet
  22861. * @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
  22862. * @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
  22863. * @param x defines x coordinate
  22864. * @param y defines y coordinate
  22865. * @param z defines z coordinate
  22866. * @returns the face index if found (or null instead)
  22867. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22868. */
  22869. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  22870. if (checkFace === void 0) { checkFace = false; }
  22871. if (facing === void 0) { facing = true; }
  22872. var world = this.getWorldMatrix();
  22873. var invMat = BABYLON.Tmp.Matrix[5];
  22874. world.invertToRef(invMat);
  22875. var invVect = BABYLON.Tmp.Vector3[8];
  22876. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  22877. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  22878. if (projected) {
  22879. // tranform the local computed projected vector to world coordinates
  22880. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  22881. }
  22882. return closest;
  22883. };
  22884. /**
  22885. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found
  22886. * @param projected sets as the (x,y,z) local projection on the facet
  22887. * @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
  22888. * @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
  22889. * @param x defines x coordinate
  22890. * @param y defines y coordinate
  22891. * @param z defines z coordinate
  22892. * @returns the face index if found (or null instead)
  22893. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22894. */
  22895. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  22896. if (checkFace === void 0) { checkFace = false; }
  22897. if (facing === void 0) { facing = true; }
  22898. var closest = null;
  22899. var tmpx = 0.0;
  22900. var tmpy = 0.0;
  22901. var tmpz = 0.0;
  22902. var d = 0.0; // tmp dot facet normal * facet position
  22903. var t0 = 0.0;
  22904. var projx = 0.0;
  22905. var projy = 0.0;
  22906. var projz = 0.0;
  22907. // Get all the facets in the same partitioning block than (x, y, z)
  22908. var facetPositions = this.getFacetLocalPositions();
  22909. var facetNormals = this.getFacetLocalNormals();
  22910. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  22911. if (!facetsInBlock) {
  22912. return null;
  22913. }
  22914. // Get the closest facet to (x, y, z)
  22915. var shortest = Number.MAX_VALUE; // init distance vars
  22916. var tmpDistance = shortest;
  22917. var fib; // current facet in the block
  22918. var norm; // current facet normal
  22919. var p0; // current facet barycenter position
  22920. // loop on all the facets in the current partitioning block
  22921. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  22922. fib = facetsInBlock[idx];
  22923. norm = facetNormals[fib];
  22924. p0 = facetPositions[fib];
  22925. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  22926. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  22927. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  22928. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  22929. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  22930. projx = x + norm.x * t0;
  22931. projy = y + norm.y * t0;
  22932. projz = z + norm.z * t0;
  22933. tmpx = projx - x;
  22934. tmpy = projy - y;
  22935. tmpz = projz - z;
  22936. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  22937. if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
  22938. shortest = tmpDistance;
  22939. closest = fib;
  22940. if (projected) {
  22941. projected.x = projx;
  22942. projected.y = projy;
  22943. projected.z = projz;
  22944. }
  22945. }
  22946. }
  22947. }
  22948. return closest;
  22949. };
  22950. /**
  22951. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  22952. * @returns the parameters
  22953. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22954. */
  22955. AbstractMesh.prototype.getFacetDataParameters = function () {
  22956. return this._facetData.facetParameters;
  22957. };
  22958. /**
  22959. * Disables the feature FacetData and frees the related memory
  22960. * @returns the current mesh
  22961. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22962. */
  22963. AbstractMesh.prototype.disableFacetData = function () {
  22964. if (this._facetData.facetDataEnabled) {
  22965. this._facetData.facetDataEnabled = false;
  22966. this._facetData.facetPositions = new Array();
  22967. this._facetData.facetNormals = new Array();
  22968. this._facetData.facetPartitioning = new Array();
  22969. this._facetData.facetParameters = null;
  22970. this._facetData.depthSortedIndices = new Uint32Array(0);
  22971. }
  22972. return this;
  22973. };
  22974. /**
  22975. * Updates the AbstractMesh indices array
  22976. * @param indices defines the data source
  22977. * @returns the current mesh
  22978. */
  22979. AbstractMesh.prototype.updateIndices = function (indices) {
  22980. return this;
  22981. };
  22982. /**
  22983. * Creates new normals data for the mesh
  22984. * @param updatable defines if the normal vertex buffer must be flagged as updatable
  22985. * @returns the current mesh
  22986. */
  22987. AbstractMesh.prototype.createNormals = function (updatable) {
  22988. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22989. var indices = this.getIndices();
  22990. var normals;
  22991. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  22992. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22993. }
  22994. else {
  22995. normals = [];
  22996. }
  22997. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  22998. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  22999. return this;
  23000. };
  23001. /**
  23002. * Align the mesh with a normal
  23003. * @param normal defines the normal to use
  23004. * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default)
  23005. * @returns the current mesh
  23006. */
  23007. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  23008. if (!upDirection) {
  23009. upDirection = BABYLON.Axis.Y;
  23010. }
  23011. var axisX = BABYLON.Tmp.Vector3[0];
  23012. var axisZ = BABYLON.Tmp.Vector3[1];
  23013. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  23014. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  23015. if (this.rotationQuaternion) {
  23016. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  23017. }
  23018. else {
  23019. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  23020. }
  23021. return this;
  23022. };
  23023. /** @hidden */
  23024. AbstractMesh.prototype._checkOcclusionQuery = function () {
  23025. return false;
  23026. };
  23027. /** No occlusion */
  23028. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  23029. /** Occlusion set to optimisitic */
  23030. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  23031. /** Occlusion set to strict */
  23032. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  23033. /** Use an accurante occlusion algorithm */
  23034. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  23035. /** Use a conservative occlusion algorithm */
  23036. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  23037. /** Default culling strategy : this is an exclusion test and it's the more accurate.
  23038. * Test order :
  23039. * Is the bounding sphere outside the frustum ?
  23040. * If not, are the bounding box vertices outside the frustum ?
  23041. * It not, then the cullable object is in the frustum.
  23042. */
  23043. AbstractMesh.CULLINGSTRATEGY_STANDARD = 0;
  23044. /** Culling strategy : Bounding Sphere Only.
  23045. * This is an exclusion test. It's faster than the standard strategy because the bounding box is not tested.
  23046. * It's also less accurate than the standard because some not visible objects can still be selected.
  23047. * Test : is the bounding sphere outside the frustum ?
  23048. * If not, then the cullable object is in the frustum.
  23049. */
  23050. AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY = 1;
  23051. /** Culling strategy : Optimistic Inclusion.
  23052. * This in an inclusion test first, then the standard exclusion test.
  23053. * This can be faster when a cullable object is expected to be almost always in the camera frustum.
  23054. * This could also be a little slower than the standard test when the tested object center is not the frustum but one of its bounding box vertex is still inside.
  23055. * Anyway, it's as accurate as the standard strategy.
  23056. * Test :
  23057. * Is the cullable object bounding sphere center in the frustum ?
  23058. * If not, apply the default culling strategy.
  23059. */
  23060. AbstractMesh.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION = 2;
  23061. /** Culling strategy : Optimistic Inclusion then Bounding Sphere Only.
  23062. * This in an inclusion test first, then the bounding sphere only exclusion test.
  23063. * This can be the fastest test when a cullable object is expected to be almost always in the camera frustum.
  23064. * This could also be a little slower than the BoundingSphereOnly strategy when the tested object center is not in the frustum but its bounding sphere still intersects it.
  23065. * It's less accurate than the standard strategy and as accurate as the BoundingSphereOnly strategy.
  23066. * Test :
  23067. * Is the cullable object bounding sphere center in the frustum ?
  23068. * If not, apply the Bounding Sphere Only strategy. No Bounding Box is tested here.
  23069. */
  23070. AbstractMesh.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY = 3;
  23071. return AbstractMesh;
  23072. }(BABYLON.TransformNode));
  23073. BABYLON.AbstractMesh = AbstractMesh;
  23074. })(BABYLON || (BABYLON = {}));
  23075. //# sourceMappingURL=babylon.abstractMesh.js.map
  23076. var BABYLON;
  23077. (function (BABYLON) {
  23078. /**
  23079. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  23080. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  23081. * 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.
  23082. */
  23083. var Light = /** @class */ (function (_super) {
  23084. __extends(Light, _super);
  23085. /**
  23086. * Creates a Light object in the scene.
  23087. * Documentation : https://doc.babylonjs.com/babylon101/lights
  23088. * @param name The firendly name of the light
  23089. * @param scene The scene the light belongs too
  23090. */
  23091. function Light(name, scene) {
  23092. var _this = _super.call(this, name, scene) || this;
  23093. /**
  23094. * Diffuse gives the basic color to an object.
  23095. */
  23096. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  23097. /**
  23098. * Specular produces a highlight color on an object.
  23099. * Note: This is note affecting PBR materials.
  23100. */
  23101. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  23102. /**
  23103. * Defines the falloff type for this light. This lets overrriding how punctual light are
  23104. * falling off base on range or angle.
  23105. * This can be set to any values in Light.FALLOFF_x.
  23106. *
  23107. * Note: This is only useful for PBR Materials at the moment. This could be extended if required to
  23108. * other types of materials.
  23109. */
  23110. _this.falloffType = Light.FALLOFF_DEFAULT;
  23111. /**
  23112. * Strength of the light.
  23113. * Note: By default it is define in the framework own unit.
  23114. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  23115. */
  23116. _this.intensity = 1.0;
  23117. _this._range = Number.MAX_VALUE;
  23118. _this._inverseSquaredRange = 0;
  23119. /**
  23120. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  23121. * of light.
  23122. */
  23123. _this._photometricScale = 1.0;
  23124. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  23125. _this._radius = 0.00001;
  23126. /**
  23127. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  23128. * exceeding the number allowed of the materials.
  23129. */
  23130. _this.renderPriority = 0;
  23131. _this._shadowEnabled = true;
  23132. _this._excludeWithLayerMask = 0;
  23133. _this._includeOnlyWithLayerMask = 0;
  23134. _this._lightmapMode = 0;
  23135. /**
  23136. * @hidden Internal use only.
  23137. */
  23138. _this._excludedMeshesIds = new Array();
  23139. /**
  23140. * @hidden Internal use only.
  23141. */
  23142. _this._includedOnlyMeshesIds = new Array();
  23143. _this.getScene().addLight(_this);
  23144. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  23145. _this._buildUniformLayout();
  23146. _this.includedOnlyMeshes = new Array();
  23147. _this.excludedMeshes = new Array();
  23148. _this._resyncMeshes();
  23149. return _this;
  23150. }
  23151. Object.defineProperty(Light.prototype, "range", {
  23152. /**
  23153. * Defines how far from the source the light is impacting in scene units.
  23154. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  23155. */
  23156. get: function () {
  23157. return this._range;
  23158. },
  23159. /**
  23160. * Defines how far from the source the light is impacting in scene units.
  23161. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  23162. */
  23163. set: function (value) {
  23164. this._range = value;
  23165. this._inverseSquaredRange = 1.0 / (this.range * this.range);
  23166. },
  23167. enumerable: true,
  23168. configurable: true
  23169. });
  23170. Object.defineProperty(Light.prototype, "intensityMode", {
  23171. /**
  23172. * Gets the photometric scale used to interpret the intensity.
  23173. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  23174. */
  23175. get: function () {
  23176. return this._intensityMode;
  23177. },
  23178. /**
  23179. * Sets the photometric scale used to interpret the intensity.
  23180. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  23181. */
  23182. set: function (value) {
  23183. this._intensityMode = value;
  23184. this._computePhotometricScale();
  23185. },
  23186. enumerable: true,
  23187. configurable: true
  23188. });
  23189. Object.defineProperty(Light.prototype, "radius", {
  23190. /**
  23191. * Gets the light radius used by PBR Materials to simulate soft area lights.
  23192. */
  23193. get: function () {
  23194. return this._radius;
  23195. },
  23196. /**
  23197. * sets the light radius used by PBR Materials to simulate soft area lights.
  23198. */
  23199. set: function (value) {
  23200. this._radius = value;
  23201. this._computePhotometricScale();
  23202. },
  23203. enumerable: true,
  23204. configurable: true
  23205. });
  23206. Object.defineProperty(Light.prototype, "shadowEnabled", {
  23207. /**
  23208. * Gets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  23209. * the current shadow generator.
  23210. */
  23211. get: function () {
  23212. return this._shadowEnabled;
  23213. },
  23214. /**
  23215. * Sets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  23216. * the current shadow generator.
  23217. */
  23218. set: function (value) {
  23219. if (this._shadowEnabled === value) {
  23220. return;
  23221. }
  23222. this._shadowEnabled = value;
  23223. this._markMeshesAsLightDirty();
  23224. },
  23225. enumerable: true,
  23226. configurable: true
  23227. });
  23228. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  23229. /**
  23230. * Gets the only meshes impacted by this light.
  23231. */
  23232. get: function () {
  23233. return this._includedOnlyMeshes;
  23234. },
  23235. /**
  23236. * Sets the only meshes impacted by this light.
  23237. */
  23238. set: function (value) {
  23239. this._includedOnlyMeshes = value;
  23240. this._hookArrayForIncludedOnly(value);
  23241. },
  23242. enumerable: true,
  23243. configurable: true
  23244. });
  23245. Object.defineProperty(Light.prototype, "excludedMeshes", {
  23246. /**
  23247. * Gets the meshes not impacted by this light.
  23248. */
  23249. get: function () {
  23250. return this._excludedMeshes;
  23251. },
  23252. /**
  23253. * Sets the meshes not impacted by this light.
  23254. */
  23255. set: function (value) {
  23256. this._excludedMeshes = value;
  23257. this._hookArrayForExcluded(value);
  23258. },
  23259. enumerable: true,
  23260. configurable: true
  23261. });
  23262. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  23263. /**
  23264. * Gets the layer id use to find what meshes are not impacted by the light.
  23265. * Inactive if 0
  23266. */
  23267. get: function () {
  23268. return this._excludeWithLayerMask;
  23269. },
  23270. /**
  23271. * Sets the layer id use to find what meshes are not impacted by the light.
  23272. * Inactive if 0
  23273. */
  23274. set: function (value) {
  23275. this._excludeWithLayerMask = value;
  23276. this._resyncMeshes();
  23277. },
  23278. enumerable: true,
  23279. configurable: true
  23280. });
  23281. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  23282. /**
  23283. * Gets the layer id use to find what meshes are impacted by the light.
  23284. * Inactive if 0
  23285. */
  23286. get: function () {
  23287. return this._includeOnlyWithLayerMask;
  23288. },
  23289. /**
  23290. * Sets the layer id use to find what meshes are impacted by the light.
  23291. * Inactive if 0
  23292. */
  23293. set: function (value) {
  23294. this._includeOnlyWithLayerMask = value;
  23295. this._resyncMeshes();
  23296. },
  23297. enumerable: true,
  23298. configurable: true
  23299. });
  23300. Object.defineProperty(Light.prototype, "lightmapMode", {
  23301. /**
  23302. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  23303. */
  23304. get: function () {
  23305. return this._lightmapMode;
  23306. },
  23307. /**
  23308. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  23309. */
  23310. set: function (value) {
  23311. if (this._lightmapMode === value) {
  23312. return;
  23313. }
  23314. this._lightmapMode = value;
  23315. this._markMeshesAsLightDirty();
  23316. },
  23317. enumerable: true,
  23318. configurable: true
  23319. });
  23320. /**
  23321. * Returns the string "Light".
  23322. * @returns the class name
  23323. */
  23324. Light.prototype.getClassName = function () {
  23325. return "Light";
  23326. };
  23327. /**
  23328. * Converts the light information to a readable string for debug purpose.
  23329. * @param fullDetails Supports for multiple levels of logging within scene loading
  23330. * @returns the human readable light info
  23331. */
  23332. Light.prototype.toString = function (fullDetails) {
  23333. var ret = "Name: " + this.name;
  23334. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  23335. if (this.animations) {
  23336. for (var i = 0; i < this.animations.length; i++) {
  23337. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  23338. }
  23339. }
  23340. if (fullDetails) {
  23341. }
  23342. return ret;
  23343. };
  23344. /** @hidden */
  23345. Light.prototype._syncParentEnabledState = function () {
  23346. _super.prototype._syncParentEnabledState.call(this);
  23347. this._resyncMeshes();
  23348. };
  23349. /**
  23350. * Set the enabled state of this node.
  23351. * @param value - the new enabled state
  23352. */
  23353. Light.prototype.setEnabled = function (value) {
  23354. _super.prototype.setEnabled.call(this, value);
  23355. this._resyncMeshes();
  23356. };
  23357. /**
  23358. * Returns the Light associated shadow generator if any.
  23359. * @return the associated shadow generator.
  23360. */
  23361. Light.prototype.getShadowGenerator = function () {
  23362. return this._shadowGenerator;
  23363. };
  23364. /**
  23365. * Returns a Vector3, the absolute light position in the World.
  23366. * @returns the world space position of the light
  23367. */
  23368. Light.prototype.getAbsolutePosition = function () {
  23369. return BABYLON.Vector3.Zero();
  23370. };
  23371. /**
  23372. * Specifies if the light will affect the passed mesh.
  23373. * @param mesh The mesh to test against the light
  23374. * @return true the mesh is affected otherwise, false.
  23375. */
  23376. Light.prototype.canAffectMesh = function (mesh) {
  23377. if (!mesh) {
  23378. return true;
  23379. }
  23380. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  23381. return false;
  23382. }
  23383. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  23384. return false;
  23385. }
  23386. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  23387. return false;
  23388. }
  23389. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  23390. return false;
  23391. }
  23392. return true;
  23393. };
  23394. /**
  23395. * Sort function to order lights for rendering.
  23396. * @param a First Light object to compare to second.
  23397. * @param b Second Light object to compare first.
  23398. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  23399. */
  23400. Light.CompareLightsPriority = function (a, b) {
  23401. //shadow-casting lights have priority over non-shadow-casting lights
  23402. //the renderPrioirty is a secondary sort criterion
  23403. if (a.shadowEnabled !== b.shadowEnabled) {
  23404. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  23405. }
  23406. return b.renderPriority - a.renderPriority;
  23407. };
  23408. /**
  23409. * Releases resources associated with this node.
  23410. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  23411. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  23412. */
  23413. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  23414. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  23415. if (this._shadowGenerator) {
  23416. this._shadowGenerator.dispose();
  23417. this._shadowGenerator = null;
  23418. }
  23419. // Animations
  23420. this.getScene().stopAnimation(this);
  23421. // Remove from meshes
  23422. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  23423. var mesh = _a[_i];
  23424. mesh._removeLightSource(this);
  23425. }
  23426. this._uniformBuffer.dispose();
  23427. // Remove from scene
  23428. this.getScene().removeLight(this);
  23429. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  23430. };
  23431. /**
  23432. * Returns the light type ID (integer).
  23433. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  23434. */
  23435. Light.prototype.getTypeID = function () {
  23436. return 0;
  23437. };
  23438. /**
  23439. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  23440. * @returns the scaled intensity in intensity mode unit
  23441. */
  23442. Light.prototype.getScaledIntensity = function () {
  23443. return this._photometricScale * this.intensity;
  23444. };
  23445. /**
  23446. * Returns a new Light object, named "name", from the current one.
  23447. * @param name The name of the cloned light
  23448. * @returns the new created light
  23449. */
  23450. Light.prototype.clone = function (name) {
  23451. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  23452. if (!constructor) {
  23453. return null;
  23454. }
  23455. return BABYLON.SerializationHelper.Clone(constructor, this);
  23456. };
  23457. /**
  23458. * Serializes the current light into a Serialization object.
  23459. * @returns the serialized object.
  23460. */
  23461. Light.prototype.serialize = function () {
  23462. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  23463. // Type
  23464. serializationObject.type = this.getTypeID();
  23465. // Parent
  23466. if (this.parent) {
  23467. serializationObject.parentId = this.parent.id;
  23468. }
  23469. // Inclusion / exclusions
  23470. if (this.excludedMeshes.length > 0) {
  23471. serializationObject.excludedMeshesIds = [];
  23472. this.excludedMeshes.forEach(function (mesh) {
  23473. serializationObject.excludedMeshesIds.push(mesh.id);
  23474. });
  23475. }
  23476. if (this.includedOnlyMeshes.length > 0) {
  23477. serializationObject.includedOnlyMeshesIds = [];
  23478. this.includedOnlyMeshes.forEach(function (mesh) {
  23479. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  23480. });
  23481. }
  23482. // Animations
  23483. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  23484. serializationObject.ranges = this.serializeAnimationRanges();
  23485. return serializationObject;
  23486. };
  23487. /**
  23488. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  23489. * This new light is named "name" and added to the passed scene.
  23490. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  23491. * @param name The friendly name of the light
  23492. * @param scene The scene the new light will belong to
  23493. * @returns the constructor function
  23494. */
  23495. Light.GetConstructorFromName = function (type, name, scene) {
  23496. var constructorFunc = BABYLON.Node.Construct("Light_Type_" + type, name, scene);
  23497. if (constructorFunc) {
  23498. return constructorFunc;
  23499. }
  23500. // Default to no light for none present once.
  23501. return null;
  23502. };
  23503. /**
  23504. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  23505. * @param parsedLight The JSON representation of the light
  23506. * @param scene The scene to create the parsed light in
  23507. * @returns the created light after parsing
  23508. */
  23509. Light.Parse = function (parsedLight, scene) {
  23510. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  23511. if (!constructor) {
  23512. return null;
  23513. }
  23514. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  23515. // Inclusion / exclusions
  23516. if (parsedLight.excludedMeshesIds) {
  23517. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  23518. }
  23519. if (parsedLight.includedOnlyMeshesIds) {
  23520. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  23521. }
  23522. // Parent
  23523. if (parsedLight.parentId) {
  23524. light._waitingParentId = parsedLight.parentId;
  23525. }
  23526. // Animations
  23527. if (parsedLight.animations) {
  23528. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  23529. var parsedAnimation = parsedLight.animations[animationIndex];
  23530. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  23531. }
  23532. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  23533. }
  23534. if (parsedLight.autoAnimate) {
  23535. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  23536. }
  23537. return light;
  23538. };
  23539. Light.prototype._hookArrayForExcluded = function (array) {
  23540. var _this = this;
  23541. var oldPush = array.push;
  23542. array.push = function () {
  23543. var items = [];
  23544. for (var _i = 0; _i < arguments.length; _i++) {
  23545. items[_i] = arguments[_i];
  23546. }
  23547. var result = oldPush.apply(array, items);
  23548. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  23549. var item = items_1[_a];
  23550. item._resyncLighSource(_this);
  23551. }
  23552. return result;
  23553. };
  23554. var oldSplice = array.splice;
  23555. array.splice = function (index, deleteCount) {
  23556. var deleted = oldSplice.apply(array, [index, deleteCount]);
  23557. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  23558. var item = deleted_1[_i];
  23559. item._resyncLighSource(_this);
  23560. }
  23561. return deleted;
  23562. };
  23563. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  23564. var item = array_1[_i];
  23565. item._resyncLighSource(this);
  23566. }
  23567. };
  23568. Light.prototype._hookArrayForIncludedOnly = function (array) {
  23569. var _this = this;
  23570. var oldPush = array.push;
  23571. array.push = function () {
  23572. var items = [];
  23573. for (var _i = 0; _i < arguments.length; _i++) {
  23574. items[_i] = arguments[_i];
  23575. }
  23576. var result = oldPush.apply(array, items);
  23577. _this._resyncMeshes();
  23578. return result;
  23579. };
  23580. var oldSplice = array.splice;
  23581. array.splice = function (index, deleteCount) {
  23582. var deleted = oldSplice.apply(array, [index, deleteCount]);
  23583. _this._resyncMeshes();
  23584. return deleted;
  23585. };
  23586. this._resyncMeshes();
  23587. };
  23588. Light.prototype._resyncMeshes = function () {
  23589. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  23590. var mesh = _a[_i];
  23591. mesh._resyncLighSource(this);
  23592. }
  23593. };
  23594. /**
  23595. * Forces the meshes to update their light related information in their rendering used effects
  23596. * @hidden Internal Use Only
  23597. */
  23598. Light.prototype._markMeshesAsLightDirty = function () {
  23599. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  23600. var mesh = _a[_i];
  23601. if (mesh._lightSources.indexOf(this) !== -1) {
  23602. mesh._markSubMeshesAsLightDirty();
  23603. }
  23604. }
  23605. };
  23606. /**
  23607. * Recomputes the cached photometric scale if needed.
  23608. */
  23609. Light.prototype._computePhotometricScale = function () {
  23610. this._photometricScale = this._getPhotometricScale();
  23611. this.getScene().resetCachedMaterial();
  23612. };
  23613. /**
  23614. * Returns the Photometric Scale according to the light type and intensity mode.
  23615. */
  23616. Light.prototype._getPhotometricScale = function () {
  23617. var photometricScale = 0.0;
  23618. var lightTypeID = this.getTypeID();
  23619. //get photometric mode
  23620. var photometricMode = this.intensityMode;
  23621. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  23622. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  23623. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  23624. }
  23625. else {
  23626. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  23627. }
  23628. }
  23629. //compute photometric scale
  23630. switch (lightTypeID) {
  23631. case Light.LIGHTTYPEID_POINTLIGHT:
  23632. case Light.LIGHTTYPEID_SPOTLIGHT:
  23633. switch (photometricMode) {
  23634. case Light.INTENSITYMODE_LUMINOUSPOWER:
  23635. photometricScale = 1.0 / (4.0 * Math.PI);
  23636. break;
  23637. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  23638. photometricScale = 1.0;
  23639. break;
  23640. case Light.INTENSITYMODE_LUMINANCE:
  23641. photometricScale = this.radius * this.radius;
  23642. break;
  23643. }
  23644. break;
  23645. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  23646. switch (photometricMode) {
  23647. case Light.INTENSITYMODE_ILLUMINANCE:
  23648. photometricScale = 1.0;
  23649. break;
  23650. case Light.INTENSITYMODE_LUMINANCE:
  23651. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  23652. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  23653. var apexAngleRadians = this.radius;
  23654. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  23655. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  23656. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  23657. photometricScale = solidAngle;
  23658. break;
  23659. }
  23660. break;
  23661. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  23662. // No fall off in hemisperic light.
  23663. photometricScale = 1.0;
  23664. break;
  23665. }
  23666. return photometricScale;
  23667. };
  23668. /**
  23669. * Reorder the light in the scene according to their defined priority.
  23670. * @hidden Internal Use Only
  23671. */
  23672. Light.prototype._reorderLightsInScene = function () {
  23673. var scene = this.getScene();
  23674. if (this._renderPriority != 0) {
  23675. scene.requireLightSorting = true;
  23676. }
  23677. this.getScene().sortLightsByPriority();
  23678. };
  23679. /**
  23680. * Falloff Default: light is falling off following the material specification:
  23681. * standard material is using standard falloff whereas pbr material can request special falloff per materials.
  23682. */
  23683. Light.FALLOFF_DEFAULT = 0;
  23684. /**
  23685. * Falloff Physical: light is falling off following the inverse squared distance law.
  23686. */
  23687. Light.FALLOFF_PHYSICAL = 1;
  23688. /**
  23689. * Falloff gltf: light is falling off as described in the gltf moving to PBR document
  23690. * to enhance interoperability with other engines.
  23691. */
  23692. Light.FALLOFF_GLTF = 2;
  23693. /**
  23694. * Falloff Standard: light is falling off like in the standard material
  23695. * to enhance interoperability with other materials.
  23696. */
  23697. Light.FALLOFF_STANDARD = 3;
  23698. //lightmapMode Consts
  23699. /**
  23700. * If every light affecting the material is in this lightmapMode,
  23701. * material.lightmapTexture adds or multiplies
  23702. * (depends on material.useLightmapAsShadowmap)
  23703. * after every other light calculations.
  23704. */
  23705. Light.LIGHTMAP_DEFAULT = 0;
  23706. /**
  23707. * material.lightmapTexture as only diffuse lighting from this light
  23708. * adds only specular lighting from this light
  23709. * adds dynamic shadows
  23710. */
  23711. Light.LIGHTMAP_SPECULAR = 1;
  23712. /**
  23713. * material.lightmapTexture as only lighting
  23714. * no light calculation from this light
  23715. * only adds dynamic shadows from this light
  23716. */
  23717. Light.LIGHTMAP_SHADOWSONLY = 2;
  23718. // Intensity Mode Consts
  23719. /**
  23720. * Each light type uses the default quantity according to its type:
  23721. * point/spot lights use luminous intensity
  23722. * directional lights use illuminance
  23723. */
  23724. Light.INTENSITYMODE_AUTOMATIC = 0;
  23725. /**
  23726. * lumen (lm)
  23727. */
  23728. Light.INTENSITYMODE_LUMINOUSPOWER = 1;
  23729. /**
  23730. * candela (lm/sr)
  23731. */
  23732. Light.INTENSITYMODE_LUMINOUSINTENSITY = 2;
  23733. /**
  23734. * lux (lm/m^2)
  23735. */
  23736. Light.INTENSITYMODE_ILLUMINANCE = 3;
  23737. /**
  23738. * nit (cd/m^2)
  23739. */
  23740. Light.INTENSITYMODE_LUMINANCE = 4;
  23741. // Light types ids const.
  23742. /**
  23743. * Light type const id of the point light.
  23744. */
  23745. Light.LIGHTTYPEID_POINTLIGHT = 0;
  23746. /**
  23747. * Light type const id of the directional light.
  23748. */
  23749. Light.LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  23750. /**
  23751. * Light type const id of the spot light.
  23752. */
  23753. Light.LIGHTTYPEID_SPOTLIGHT = 2;
  23754. /**
  23755. * Light type const id of the hemispheric light.
  23756. */
  23757. Light.LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  23758. __decorate([
  23759. BABYLON.serializeAsColor3()
  23760. ], Light.prototype, "diffuse", void 0);
  23761. __decorate([
  23762. BABYLON.serializeAsColor3()
  23763. ], Light.prototype, "specular", void 0);
  23764. __decorate([
  23765. BABYLON.serialize()
  23766. ], Light.prototype, "falloffType", void 0);
  23767. __decorate([
  23768. BABYLON.serialize()
  23769. ], Light.prototype, "intensity", void 0);
  23770. __decorate([
  23771. BABYLON.serialize()
  23772. ], Light.prototype, "range", null);
  23773. __decorate([
  23774. BABYLON.serialize()
  23775. ], Light.prototype, "intensityMode", null);
  23776. __decorate([
  23777. BABYLON.serialize()
  23778. ], Light.prototype, "radius", null);
  23779. __decorate([
  23780. BABYLON.serialize()
  23781. ], Light.prototype, "_renderPriority", void 0);
  23782. __decorate([
  23783. BABYLON.expandToProperty("_reorderLightsInScene")
  23784. ], Light.prototype, "renderPriority", void 0);
  23785. __decorate([
  23786. BABYLON.serialize("shadowEnabled")
  23787. ], Light.prototype, "_shadowEnabled", void 0);
  23788. __decorate([
  23789. BABYLON.serialize("excludeWithLayerMask")
  23790. ], Light.prototype, "_excludeWithLayerMask", void 0);
  23791. __decorate([
  23792. BABYLON.serialize("includeOnlyWithLayerMask")
  23793. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  23794. __decorate([
  23795. BABYLON.serialize("lightmapMode")
  23796. ], Light.prototype, "_lightmapMode", void 0);
  23797. return Light;
  23798. }(BABYLON.Node));
  23799. BABYLON.Light = Light;
  23800. })(BABYLON || (BABYLON = {}));
  23801. //# sourceMappingURL=babylon.light.js.map
  23802. var BABYLON;
  23803. (function (BABYLON) {
  23804. /**
  23805. * This is the base class of all the camera used in the application.
  23806. * @see http://doc.babylonjs.com/features/cameras
  23807. */
  23808. var Camera = /** @class */ (function (_super) {
  23809. __extends(Camera, _super);
  23810. /**
  23811. * Instantiates a new camera object.
  23812. * This should not be used directly but through the inherited cameras: ArcRotate, Free...
  23813. * @see http://doc.babylonjs.com/features/cameras
  23814. * @param name Defines the name of the camera in the scene
  23815. * @param position Defines the position of the camera
  23816. * @param scene Defines the scene the camera belongs too
  23817. * @param setActiveOnSceneIfNoneActive Defines if the camera should be set as active after creation if no other camera have been defined in the scene
  23818. */
  23819. function Camera(name, position, scene, setActiveOnSceneIfNoneActive) {
  23820. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  23821. var _this = _super.call(this, name, scene) || this;
  23822. /**
  23823. * The vector the camera should consider as up.
  23824. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  23825. */
  23826. _this.upVector = BABYLON.Vector3.Up();
  23827. /**
  23828. * Define the current limit on the left side for an orthographic camera
  23829. * In scene unit
  23830. */
  23831. _this.orthoLeft = null;
  23832. /**
  23833. * Define the current limit on the right side for an orthographic camera
  23834. * In scene unit
  23835. */
  23836. _this.orthoRight = null;
  23837. /**
  23838. * Define the current limit on the bottom side for an orthographic camera
  23839. * In scene unit
  23840. */
  23841. _this.orthoBottom = null;
  23842. /**
  23843. * Define the current limit on the top side for an orthographic camera
  23844. * In scene unit
  23845. */
  23846. _this.orthoTop = null;
  23847. /**
  23848. * Field Of View is set in Radians. (default is 0.8)
  23849. */
  23850. _this.fov = 0.8;
  23851. /**
  23852. * Define the minimum distance the camera can see from.
  23853. * This is important to note that the depth buffer are not infinite and the closer it starts
  23854. * the more your scene might encounter depth fighting issue.
  23855. */
  23856. _this.minZ = 1;
  23857. /**
  23858. * Define the maximum distance the camera can see to.
  23859. * This is important to note that the depth buffer are not infinite and the further it end
  23860. * the more your scene might encounter depth fighting issue.
  23861. */
  23862. _this.maxZ = 10000.0;
  23863. /**
  23864. * Define the default inertia of the camera.
  23865. * This helps giving a smooth feeling to the camera movement.
  23866. */
  23867. _this.inertia = 0.9;
  23868. /**
  23869. * Define the mode of the camera (Camera.PERSPECTIVE_CAMERA or Camera.PERSPECTIVE_ORTHOGRAPHIC)
  23870. */
  23871. _this.mode = Camera.PERSPECTIVE_CAMERA;
  23872. /**
  23873. * Define wether the camera is intermediate.
  23874. * This is useful to not present the output directly to the screen in case of rig without post process for instance
  23875. */
  23876. _this.isIntermediate = false;
  23877. /**
  23878. * Define the viewport of the camera.
  23879. * This correspond to the portion of the screen the camera will render to in normalized 0 to 1 unit.
  23880. */
  23881. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  23882. /**
  23883. * Restricts the camera to viewing objects with the same layerMask.
  23884. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  23885. */
  23886. _this.layerMask = 0x0FFFFFFF;
  23887. /**
  23888. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  23889. */
  23890. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  23891. /**
  23892. * Rig mode of the camera.
  23893. * This is useful to create the camera with two "eyes" instead of one to create VR or stereoscopic scenes.
  23894. * This is normally controlled byt the camera themselves as internal use.
  23895. */
  23896. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  23897. /**
  23898. * Defines the list of custom render target which are rendered to and then used as the input to this camera's render. Eg. display another camera view on a TV in the main scene
  23899. * This is pretty helpfull if you wish to make a camera render to a texture you could reuse somewhere
  23900. * else in the scene.
  23901. */
  23902. _this.customRenderTargets = new Array();
  23903. /**
  23904. * When set, the camera will render to this render target instead of the default canvas
  23905. */
  23906. _this.outputRenderTarget = null;
  23907. /**
  23908. * Observable triggered when the camera view matrix has changed.
  23909. */
  23910. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  23911. /**
  23912. * Observable triggered when the camera Projection matrix has changed.
  23913. */
  23914. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  23915. /**
  23916. * Observable triggered when the inputs have been processed.
  23917. */
  23918. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  23919. /**
  23920. * Observable triggered when reset has been called and applied to the camera.
  23921. */
  23922. _this.onRestoreStateObservable = new BABYLON.Observable();
  23923. /** @hidden */
  23924. _this._rigCameras = new Array();
  23925. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  23926. /** @hidden */
  23927. _this._skipRendering = false;
  23928. /** @hidden */
  23929. _this._projectionMatrix = new BABYLON.Matrix();
  23930. /** @hidden */
  23931. _this._postProcesses = new Array();
  23932. /** @hidden */
  23933. _this._activeMeshes = new BABYLON.SmartArray(256);
  23934. _this._globalPosition = BABYLON.Vector3.Zero();
  23935. /** hidden */
  23936. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  23937. _this._doNotComputeProjectionMatrix = false;
  23938. _this._transformMatrix = BABYLON.Matrix.Zero();
  23939. _this._refreshFrustumPlanes = true;
  23940. _this.getScene().addCamera(_this);
  23941. if (setActiveOnSceneIfNoneActive && !_this.getScene().activeCamera) {
  23942. _this.getScene().activeCamera = _this;
  23943. }
  23944. _this.position = position;
  23945. return _this;
  23946. }
  23947. /**
  23948. * Store current camera state (fov, position, etc..)
  23949. * @returns the camera
  23950. */
  23951. Camera.prototype.storeState = function () {
  23952. this._stateStored = true;
  23953. this._storedFov = this.fov;
  23954. return this;
  23955. };
  23956. /**
  23957. * Restores the camera state values if it has been stored. You must call storeState() first
  23958. */
  23959. Camera.prototype._restoreStateValues = function () {
  23960. if (!this._stateStored) {
  23961. return false;
  23962. }
  23963. this.fov = this._storedFov;
  23964. return true;
  23965. };
  23966. /**
  23967. * Restored camera state. You must call storeState() first.
  23968. * @returns true if restored and false otherwise
  23969. */
  23970. Camera.prototype.restoreState = function () {
  23971. if (this._restoreStateValues()) {
  23972. this.onRestoreStateObservable.notifyObservers(this);
  23973. return true;
  23974. }
  23975. return false;
  23976. };
  23977. /**
  23978. * Gets the class name of the camera.
  23979. * @returns the class name
  23980. */
  23981. Camera.prototype.getClassName = function () {
  23982. return "Camera";
  23983. };
  23984. /**
  23985. * Gets a string representation of the camera useful for debug purpose.
  23986. * @param fullDetails Defines that a more verboe level of logging is required
  23987. * @returns the string representation
  23988. */
  23989. Camera.prototype.toString = function (fullDetails) {
  23990. var ret = "Name: " + this.name;
  23991. ret += ", type: " + this.getClassName();
  23992. if (this.animations) {
  23993. for (var i = 0; i < this.animations.length; i++) {
  23994. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  23995. }
  23996. }
  23997. if (fullDetails) {
  23998. }
  23999. return ret;
  24000. };
  24001. Object.defineProperty(Camera.prototype, "globalPosition", {
  24002. /**
  24003. * Gets the current world space position of the camera.
  24004. */
  24005. get: function () {
  24006. return this._globalPosition;
  24007. },
  24008. enumerable: true,
  24009. configurable: true
  24010. });
  24011. /**
  24012. * Gets the list of active meshes this frame (meshes no culled or excluded by lod s in the frame)
  24013. * @returns the active meshe list
  24014. */
  24015. Camera.prototype.getActiveMeshes = function () {
  24016. return this._activeMeshes;
  24017. };
  24018. /**
  24019. * Check wether a mesh is part of the current active mesh list of the camera
  24020. * @param mesh Defines the mesh to check
  24021. * @returns true if active, false otherwise
  24022. */
  24023. Camera.prototype.isActiveMesh = function (mesh) {
  24024. return (this._activeMeshes.indexOf(mesh) !== -1);
  24025. };
  24026. /**
  24027. * Is this camera ready to be used/rendered
  24028. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  24029. * @return true if the camera is ready
  24030. */
  24031. Camera.prototype.isReady = function (completeCheck) {
  24032. if (completeCheck === void 0) { completeCheck = false; }
  24033. if (completeCheck) {
  24034. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  24035. var pp = _a[_i];
  24036. if (pp && !pp.isReady()) {
  24037. return false;
  24038. }
  24039. }
  24040. }
  24041. return _super.prototype.isReady.call(this, completeCheck);
  24042. };
  24043. /** @hidden */
  24044. Camera.prototype._initCache = function () {
  24045. _super.prototype._initCache.call(this);
  24046. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  24047. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  24048. this._cache.mode = undefined;
  24049. this._cache.minZ = undefined;
  24050. this._cache.maxZ = undefined;
  24051. this._cache.fov = undefined;
  24052. this._cache.fovMode = undefined;
  24053. this._cache.aspectRatio = undefined;
  24054. this._cache.orthoLeft = undefined;
  24055. this._cache.orthoRight = undefined;
  24056. this._cache.orthoBottom = undefined;
  24057. this._cache.orthoTop = undefined;
  24058. this._cache.renderWidth = undefined;
  24059. this._cache.renderHeight = undefined;
  24060. };
  24061. /** @hidden */
  24062. Camera.prototype._updateCache = function (ignoreParentClass) {
  24063. if (!ignoreParentClass) {
  24064. _super.prototype._updateCache.call(this);
  24065. }
  24066. this._cache.position.copyFrom(this.position);
  24067. this._cache.upVector.copyFrom(this.upVector);
  24068. };
  24069. /** @hidden */
  24070. Camera.prototype._isSynchronized = function () {
  24071. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  24072. };
  24073. /** @hidden */
  24074. Camera.prototype._isSynchronizedViewMatrix = function () {
  24075. if (!_super.prototype._isSynchronized.call(this)) {
  24076. return false;
  24077. }
  24078. return this._cache.position.equals(this.position)
  24079. && this._cache.upVector.equals(this.upVector)
  24080. && this.isSynchronizedWithParent();
  24081. };
  24082. /** @hidden */
  24083. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  24084. var check = this._cache.mode === this.mode
  24085. && this._cache.minZ === this.minZ
  24086. && this._cache.maxZ === this.maxZ;
  24087. if (!check) {
  24088. return false;
  24089. }
  24090. var engine = this.getEngine();
  24091. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  24092. check = this._cache.fov === this.fov
  24093. && this._cache.fovMode === this.fovMode
  24094. && this._cache.aspectRatio === engine.getAspectRatio(this);
  24095. }
  24096. else {
  24097. check = this._cache.orthoLeft === this.orthoLeft
  24098. && this._cache.orthoRight === this.orthoRight
  24099. && this._cache.orthoBottom === this.orthoBottom
  24100. && this._cache.orthoTop === this.orthoTop
  24101. && this._cache.renderWidth === engine.getRenderWidth()
  24102. && this._cache.renderHeight === engine.getRenderHeight();
  24103. }
  24104. return check;
  24105. };
  24106. /**
  24107. * Attach the input controls to a specific dom element to get the input from.
  24108. * @param element Defines the element the controls should be listened from
  24109. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  24110. */
  24111. Camera.prototype.attachControl = function (element, noPreventDefault) {
  24112. };
  24113. /**
  24114. * Detach the current controls from the specified dom element.
  24115. * @param element Defines the element to stop listening the inputs from
  24116. */
  24117. Camera.prototype.detachControl = function (element) {
  24118. };
  24119. /**
  24120. * Update the camera state according to the different inputs gathered during the frame.
  24121. */
  24122. Camera.prototype.update = function () {
  24123. this._checkInputs();
  24124. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  24125. this._updateRigCameras();
  24126. }
  24127. };
  24128. /** @hidden */
  24129. Camera.prototype._checkInputs = function () {
  24130. this.onAfterCheckInputsObservable.notifyObservers(this);
  24131. };
  24132. Object.defineProperty(Camera.prototype, "rigCameras", {
  24133. /** @hidden */
  24134. get: function () {
  24135. return this._rigCameras;
  24136. },
  24137. enumerable: true,
  24138. configurable: true
  24139. });
  24140. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  24141. /**
  24142. * Gets the post process used by the rig cameras
  24143. */
  24144. get: function () {
  24145. return this._rigPostProcess;
  24146. },
  24147. enumerable: true,
  24148. configurable: true
  24149. });
  24150. /**
  24151. * Internal, gets the first post proces.
  24152. * @returns the first post process to be run on this camera.
  24153. */
  24154. Camera.prototype._getFirstPostProcess = function () {
  24155. for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
  24156. if (this._postProcesses[ppIndex] !== null) {
  24157. return this._postProcesses[ppIndex];
  24158. }
  24159. }
  24160. return null;
  24161. };
  24162. Camera.prototype._cascadePostProcessesToRigCams = function () {
  24163. // invalidate framebuffer
  24164. var firstPostProcess = this._getFirstPostProcess();
  24165. if (firstPostProcess) {
  24166. firstPostProcess.markTextureDirty();
  24167. }
  24168. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  24169. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  24170. var cam = this._rigCameras[i];
  24171. var rigPostProcess = cam._rigPostProcess;
  24172. // for VR rig, there does not have to be a post process
  24173. if (rigPostProcess) {
  24174. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  24175. if (isPass) {
  24176. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  24177. cam.isIntermediate = this._postProcesses.length === 0;
  24178. }
  24179. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  24180. rigPostProcess.markTextureDirty();
  24181. }
  24182. else {
  24183. cam._postProcesses = this._postProcesses.slice(0);
  24184. }
  24185. }
  24186. };
  24187. /**
  24188. * Attach a post process to the camera.
  24189. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocesses#attach-postprocess
  24190. * @param postProcess The post process to attach to the camera
  24191. * @param insertAt The position of the post process in case several of them are in use in the scene
  24192. * @returns the position the post process has been inserted at
  24193. */
  24194. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  24195. if (insertAt === void 0) { insertAt = null; }
  24196. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  24197. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  24198. return 0;
  24199. }
  24200. if (insertAt == null || insertAt < 0) {
  24201. this._postProcesses.push(postProcess);
  24202. }
  24203. else if (this._postProcesses[insertAt] === null) {
  24204. this._postProcesses[insertAt] = postProcess;
  24205. }
  24206. else {
  24207. this._postProcesses.splice(insertAt, 0, postProcess);
  24208. }
  24209. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  24210. return this._postProcesses.indexOf(postProcess);
  24211. };
  24212. /**
  24213. * Detach a post process to the camera.
  24214. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocesses#attach-postprocess
  24215. * @param postProcess The post process to detach from the camera
  24216. */
  24217. Camera.prototype.detachPostProcess = function (postProcess) {
  24218. var idx = this._postProcesses.indexOf(postProcess);
  24219. if (idx !== -1) {
  24220. this._postProcesses[idx] = null;
  24221. }
  24222. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  24223. };
  24224. /**
  24225. * Gets the current world matrix of the camera
  24226. */
  24227. Camera.prototype.getWorldMatrix = function () {
  24228. if (this._isSynchronizedViewMatrix()) {
  24229. return this._worldMatrix;
  24230. }
  24231. // Getting the the view matrix will also compute the world matrix.
  24232. this.getViewMatrix();
  24233. return this._worldMatrix;
  24234. };
  24235. /** @hidden */
  24236. Camera.prototype._getViewMatrix = function () {
  24237. return BABYLON.Matrix.Identity();
  24238. };
  24239. /**
  24240. * Gets the current view matrix of the camera.
  24241. * @param force forces the camera to recompute the matrix without looking at the cached state
  24242. * @returns the view matrix
  24243. */
  24244. Camera.prototype.getViewMatrix = function (force) {
  24245. if (!force && this._isSynchronizedViewMatrix()) {
  24246. return this._computedViewMatrix;
  24247. }
  24248. this.updateCache();
  24249. this._computedViewMatrix = this._getViewMatrix();
  24250. this._currentRenderId = this.getScene().getRenderId();
  24251. this._childRenderId = this._currentRenderId;
  24252. this._refreshFrustumPlanes = true;
  24253. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  24254. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  24255. }
  24256. this.onViewMatrixChangedObservable.notifyObservers(this);
  24257. this._computedViewMatrix.invertToRef(this._worldMatrix);
  24258. return this._computedViewMatrix;
  24259. };
  24260. /**
  24261. * Freeze the projection matrix.
  24262. * It will prevent the cache check of the camera projection compute and can speed up perf
  24263. * if no parameter of the camera are meant to change
  24264. * @param projection Defines manually a projection if necessary
  24265. */
  24266. Camera.prototype.freezeProjectionMatrix = function (projection) {
  24267. this._doNotComputeProjectionMatrix = true;
  24268. if (projection !== undefined) {
  24269. this._projectionMatrix = projection;
  24270. }
  24271. };
  24272. /**
  24273. * Unfreeze the projection matrix if it has previously been freezed by freezeProjectionMatrix.
  24274. */
  24275. Camera.prototype.unfreezeProjectionMatrix = function () {
  24276. this._doNotComputeProjectionMatrix = false;
  24277. };
  24278. /**
  24279. * Gets the current projection matrix of the camera.
  24280. * @param force forces the camera to recompute the matrix without looking at the cached state
  24281. * @returns the projection matrix
  24282. */
  24283. Camera.prototype.getProjectionMatrix = function (force) {
  24284. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  24285. return this._projectionMatrix;
  24286. }
  24287. // Cache
  24288. this._cache.mode = this.mode;
  24289. this._cache.minZ = this.minZ;
  24290. this._cache.maxZ = this.maxZ;
  24291. // Matrix
  24292. this._refreshFrustumPlanes = true;
  24293. var engine = this.getEngine();
  24294. var scene = this.getScene();
  24295. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  24296. this._cache.fov = this.fov;
  24297. this._cache.fovMode = this.fovMode;
  24298. this._cache.aspectRatio = engine.getAspectRatio(this);
  24299. if (this.minZ <= 0) {
  24300. this.minZ = 0.1;
  24301. }
  24302. if (scene.useRightHandedSystem) {
  24303. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  24304. }
  24305. else {
  24306. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  24307. }
  24308. }
  24309. else {
  24310. var halfWidth = engine.getRenderWidth() / 2.0;
  24311. var halfHeight = engine.getRenderHeight() / 2.0;
  24312. if (scene.useRightHandedSystem) {
  24313. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  24314. }
  24315. else {
  24316. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  24317. }
  24318. this._cache.orthoLeft = this.orthoLeft;
  24319. this._cache.orthoRight = this.orthoRight;
  24320. this._cache.orthoBottom = this.orthoBottom;
  24321. this._cache.orthoTop = this.orthoTop;
  24322. this._cache.renderWidth = engine.getRenderWidth();
  24323. this._cache.renderHeight = engine.getRenderHeight();
  24324. }
  24325. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  24326. return this._projectionMatrix;
  24327. };
  24328. /**
  24329. * Gets the transformation matrix (ie. the multiplication of view by projection matrices)
  24330. * @returns a Matrix
  24331. */
  24332. Camera.prototype.getTransformationMatrix = function () {
  24333. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  24334. return this._transformMatrix;
  24335. };
  24336. Camera.prototype._updateFrustumPlanes = function () {
  24337. if (!this._refreshFrustumPlanes) {
  24338. return;
  24339. }
  24340. this.getTransformationMatrix();
  24341. if (!this._frustumPlanes) {
  24342. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  24343. }
  24344. else {
  24345. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  24346. }
  24347. this._refreshFrustumPlanes = false;
  24348. };
  24349. /**
  24350. * Checks if a cullable object (mesh...) is in the camera frustum
  24351. * This checks the bounding box center. See isCompletelyInFrustum for a full bounding check
  24352. * @param target The object to check
  24353. * @returns true if the object is in frustum otherwise false
  24354. */
  24355. Camera.prototype.isInFrustum = function (target) {
  24356. this._updateFrustumPlanes();
  24357. return target.isInFrustum(this._frustumPlanes);
  24358. };
  24359. /**
  24360. * Checks if a cullable object (mesh...) is in the camera frustum
  24361. * Unlike isInFrustum this cheks the full bounding box
  24362. * @param target The object to check
  24363. * @returns true if the object is in frustum otherwise false
  24364. */
  24365. Camera.prototype.isCompletelyInFrustum = function (target) {
  24366. this._updateFrustumPlanes();
  24367. return target.isCompletelyInFrustum(this._frustumPlanes);
  24368. };
  24369. /**
  24370. * Gets a ray in the forward direction from the camera.
  24371. * @param length Defines the length of the ray to create
  24372. * @param transform Defines the transform to apply to the ray, by default the world matrx is used to create a workd space ray
  24373. * @param origin Defines the start point of the ray which defaults to the camera position
  24374. * @returns the forward ray
  24375. */
  24376. Camera.prototype.getForwardRay = function (length, transform, origin) {
  24377. if (length === void 0) { length = 100; }
  24378. if (!transform) {
  24379. transform = this.getWorldMatrix();
  24380. }
  24381. if (!origin) {
  24382. origin = this.position;
  24383. }
  24384. var forward = this._scene.useRightHandedSystem ? new BABYLON.Vector3(0, 0, -1) : new BABYLON.Vector3(0, 0, 1);
  24385. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  24386. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  24387. return new BABYLON.Ray(origin, direction, length);
  24388. };
  24389. /**
  24390. * Releases resources associated with this node.
  24391. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  24392. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  24393. */
  24394. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  24395. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  24396. // Observables
  24397. this.onViewMatrixChangedObservable.clear();
  24398. this.onProjectionMatrixChangedObservable.clear();
  24399. this.onAfterCheckInputsObservable.clear();
  24400. this.onRestoreStateObservable.clear();
  24401. // Inputs
  24402. if (this.inputs) {
  24403. this.inputs.clear();
  24404. }
  24405. // Animations
  24406. this.getScene().stopAnimation(this);
  24407. // Remove from scene
  24408. this.getScene().removeCamera(this);
  24409. while (this._rigCameras.length > 0) {
  24410. var camera = this._rigCameras.pop();
  24411. if (camera) {
  24412. camera.dispose();
  24413. }
  24414. }
  24415. // Postprocesses
  24416. if (this._rigPostProcess) {
  24417. this._rigPostProcess.dispose(this);
  24418. this._rigPostProcess = null;
  24419. this._postProcesses = [];
  24420. }
  24421. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  24422. this._rigPostProcess = null;
  24423. this._postProcesses = [];
  24424. }
  24425. else {
  24426. var i = this._postProcesses.length;
  24427. while (--i >= 0) {
  24428. var postProcess = this._postProcesses[i];
  24429. if (postProcess) {
  24430. postProcess.dispose(this);
  24431. }
  24432. }
  24433. }
  24434. // Render targets
  24435. var i = this.customRenderTargets.length;
  24436. while (--i >= 0) {
  24437. this.customRenderTargets[i].dispose();
  24438. }
  24439. this.customRenderTargets = [];
  24440. // Active Meshes
  24441. this._activeMeshes.dispose();
  24442. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  24443. };
  24444. Object.defineProperty(Camera.prototype, "leftCamera", {
  24445. /**
  24446. * Gets the left camera of a rig setup in case of Rigged Camera
  24447. */
  24448. get: function () {
  24449. if (this._rigCameras.length < 1) {
  24450. return null;
  24451. }
  24452. return this._rigCameras[0];
  24453. },
  24454. enumerable: true,
  24455. configurable: true
  24456. });
  24457. Object.defineProperty(Camera.prototype, "rightCamera", {
  24458. /**
  24459. * Gets the right camera of a rig setup in case of Rigged Camera
  24460. */
  24461. get: function () {
  24462. if (this._rigCameras.length < 2) {
  24463. return null;
  24464. }
  24465. return this._rigCameras[1];
  24466. },
  24467. enumerable: true,
  24468. configurable: true
  24469. });
  24470. /**
  24471. * Gets the left camera target of a rig setup in case of Rigged Camera
  24472. * @returns the target position
  24473. */
  24474. Camera.prototype.getLeftTarget = function () {
  24475. if (this._rigCameras.length < 1) {
  24476. return null;
  24477. }
  24478. return this._rigCameras[0].getTarget();
  24479. };
  24480. /**
  24481. * Gets the right camera target of a rig setup in case of Rigged Camera
  24482. * @returns the target position
  24483. */
  24484. Camera.prototype.getRightTarget = function () {
  24485. if (this._rigCameras.length < 2) {
  24486. return null;
  24487. }
  24488. return this._rigCameras[1].getTarget();
  24489. };
  24490. /**
  24491. * @hidden
  24492. */
  24493. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  24494. if (this.cameraRigMode === mode) {
  24495. return;
  24496. }
  24497. while (this._rigCameras.length > 0) {
  24498. var camera = this._rigCameras.pop();
  24499. if (camera) {
  24500. camera.dispose();
  24501. }
  24502. }
  24503. this.cameraRigMode = mode;
  24504. this._cameraRigParams = {};
  24505. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  24506. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  24507. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  24508. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  24509. // create the rig cameras, unless none
  24510. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  24511. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  24512. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  24513. if (leftCamera && rightCamera) {
  24514. this._rigCameras.push(leftCamera);
  24515. this._rigCameras.push(rightCamera);
  24516. }
  24517. }
  24518. switch (this.cameraRigMode) {
  24519. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  24520. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  24521. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  24522. break;
  24523. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  24524. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  24525. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  24526. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  24527. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  24528. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  24529. break;
  24530. case Camera.RIG_MODE_VR:
  24531. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  24532. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  24533. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  24534. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  24535. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  24536. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  24537. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  24538. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  24539. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  24540. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  24541. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  24542. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  24543. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  24544. if (metrics.compensateDistortion) {
  24545. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  24546. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  24547. }
  24548. break;
  24549. case Camera.RIG_MODE_WEBVR:
  24550. if (rigParams.vrDisplay) {
  24551. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  24552. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  24553. //Left eye
  24554. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  24555. this._rigCameras[0].setCameraRigParameter("left", true);
  24556. //leaving this for future reference
  24557. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  24558. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  24559. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  24560. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  24561. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  24562. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  24563. this._rigCameras[0].parent = this;
  24564. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  24565. //Right eye
  24566. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  24567. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  24568. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  24569. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  24570. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  24571. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  24572. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  24573. this._rigCameras[1].parent = this;
  24574. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  24575. if (Camera.UseAlternateWebVRRendering) {
  24576. this._rigCameras[1]._skipRendering = true;
  24577. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  24578. }
  24579. }
  24580. break;
  24581. }
  24582. this._cascadePostProcessesToRigCams();
  24583. this.update();
  24584. };
  24585. Camera.prototype._getVRProjectionMatrix = function () {
  24586. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  24587. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  24588. return this._projectionMatrix;
  24589. };
  24590. Camera.prototype._updateCameraRotationMatrix = function () {
  24591. //Here for WebVR
  24592. };
  24593. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  24594. //Here for WebVR
  24595. };
  24596. /**
  24597. * This function MUST be overwritten by the different WebVR cameras available.
  24598. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  24599. */
  24600. Camera.prototype._getWebVRProjectionMatrix = function () {
  24601. return BABYLON.Matrix.Identity();
  24602. };
  24603. /**
  24604. * This function MUST be overwritten by the different WebVR cameras available.
  24605. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  24606. */
  24607. Camera.prototype._getWebVRViewMatrix = function () {
  24608. return BABYLON.Matrix.Identity();
  24609. };
  24610. /** @hidden */
  24611. Camera.prototype.setCameraRigParameter = function (name, value) {
  24612. if (!this._cameraRigParams) {
  24613. this._cameraRigParams = {};
  24614. }
  24615. this._cameraRigParams[name] = value;
  24616. //provisionnally:
  24617. if (name === "interaxialDistance") {
  24618. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  24619. }
  24620. };
  24621. /**
  24622. * needs to be overridden by children so sub has required properties to be copied
  24623. * @hidden
  24624. */
  24625. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  24626. return null;
  24627. };
  24628. /**
  24629. * May need to be overridden by children
  24630. * @hidden
  24631. */
  24632. Camera.prototype._updateRigCameras = function () {
  24633. for (var i = 0; i < this._rigCameras.length; i++) {
  24634. this._rigCameras[i].minZ = this.minZ;
  24635. this._rigCameras[i].maxZ = this.maxZ;
  24636. this._rigCameras[i].fov = this.fov;
  24637. this._rigCameras[i].upVector.copyFrom(this.upVector);
  24638. }
  24639. // only update viewport when ANAGLYPH
  24640. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  24641. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  24642. }
  24643. };
  24644. /** @hidden */
  24645. Camera.prototype._setupInputs = function () {
  24646. };
  24647. /**
  24648. * Serialiaze the camera setup to a json represention
  24649. * @returns the JSON representation
  24650. */
  24651. Camera.prototype.serialize = function () {
  24652. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  24653. // Type
  24654. serializationObject.type = this.getClassName();
  24655. // Parent
  24656. if (this.parent) {
  24657. serializationObject.parentId = this.parent.id;
  24658. }
  24659. if (this.inputs) {
  24660. this.inputs.serialize(serializationObject);
  24661. }
  24662. // Animations
  24663. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  24664. serializationObject.ranges = this.serializeAnimationRanges();
  24665. return serializationObject;
  24666. };
  24667. /**
  24668. * Clones the current camera.
  24669. * @param name The cloned camera name
  24670. * @returns the cloned camera
  24671. */
  24672. Camera.prototype.clone = function (name) {
  24673. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  24674. };
  24675. /**
  24676. * Gets the direction of the camera relative to a given local axis.
  24677. * @param localAxis Defines the reference axis to provide a relative direction.
  24678. * @return the direction
  24679. */
  24680. Camera.prototype.getDirection = function (localAxis) {
  24681. var result = BABYLON.Vector3.Zero();
  24682. this.getDirectionToRef(localAxis, result);
  24683. return result;
  24684. };
  24685. /**
  24686. * Gets the direction of the camera relative to a given local axis into a passed vector.
  24687. * @param localAxis Defines the reference axis to provide a relative direction.
  24688. * @param result Defines the vector to store the result in
  24689. */
  24690. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  24691. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  24692. };
  24693. /**
  24694. * Gets a camera constructor for a given camera type
  24695. * @param type The type of the camera to construct (should be equal to one of the camera class name)
  24696. * @param name The name of the camera the result will be able to instantiate
  24697. * @param scene The scene the result will construct the camera in
  24698. * @param interaxial_distance In case of stereoscopic setup, the distance between both eyes
  24699. * @param isStereoscopicSideBySide In case of stereoscopic setup, should the sereo be side b side
  24700. * @returns a factory method to construc the camera
  24701. */
  24702. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  24703. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  24704. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  24705. var constructorFunc = BABYLON.Node.Construct(type, name, scene, {
  24706. interaxial_distance: interaxial_distance,
  24707. isStereoscopicSideBySide: isStereoscopicSideBySide
  24708. });
  24709. if (constructorFunc) {
  24710. return constructorFunc;
  24711. }
  24712. // Default to universal camera
  24713. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  24714. };
  24715. /**
  24716. * Compute the world matrix of the camera.
  24717. * @returns the camera workd matrix
  24718. */
  24719. Camera.prototype.computeWorldMatrix = function () {
  24720. return this.getWorldMatrix();
  24721. };
  24722. /**
  24723. * Parse a JSON and creates the camera from the parsed information
  24724. * @param parsedCamera The JSON to parse
  24725. * @param scene The scene to instantiate the camera in
  24726. * @returns the newly constructed camera
  24727. */
  24728. Camera.Parse = function (parsedCamera, scene) {
  24729. var type = parsedCamera.type;
  24730. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  24731. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  24732. // Parent
  24733. if (parsedCamera.parentId) {
  24734. camera._waitingParentId = parsedCamera.parentId;
  24735. }
  24736. //If camera has an input manager, let it parse inputs settings
  24737. if (camera.inputs) {
  24738. camera.inputs.parse(parsedCamera);
  24739. camera._setupInputs();
  24740. }
  24741. if (camera.setPosition) { // need to force position
  24742. camera.position.copyFromFloats(0, 0, 0);
  24743. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  24744. }
  24745. // Target
  24746. if (parsedCamera.target) {
  24747. if (camera.setTarget) {
  24748. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  24749. }
  24750. }
  24751. // Apply 3d rig, when found
  24752. if (parsedCamera.cameraRigMode) {
  24753. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  24754. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  24755. }
  24756. // Animations
  24757. if (parsedCamera.animations) {
  24758. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  24759. var parsedAnimation = parsedCamera.animations[animationIndex];
  24760. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  24761. }
  24762. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  24763. }
  24764. if (parsedCamera.autoAnimate) {
  24765. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  24766. }
  24767. return camera;
  24768. };
  24769. /**
  24770. * This is the default projection mode used by the cameras.
  24771. * It helps recreating a feeling of perspective and better appreciate depth.
  24772. * This is the best way to simulate real life cameras.
  24773. */
  24774. Camera.PERSPECTIVE_CAMERA = 0;
  24775. /**
  24776. * This helps creating camera with an orthographic mode.
  24777. * 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.
  24778. */
  24779. Camera.ORTHOGRAPHIC_CAMERA = 1;
  24780. /**
  24781. * This is the default FOV mode for perspective cameras.
  24782. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  24783. */
  24784. Camera.FOVMODE_VERTICAL_FIXED = 0;
  24785. /**
  24786. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  24787. */
  24788. Camera.FOVMODE_HORIZONTAL_FIXED = 1;
  24789. /**
  24790. * This specifies ther is no need for a camera rig.
  24791. * Basically only one eye is rendered corresponding to the camera.
  24792. */
  24793. Camera.RIG_MODE_NONE = 0;
  24794. /**
  24795. * Simulates a camera Rig with one blue eye and one red eye.
  24796. * This can be use with 3d blue and red glasses.
  24797. */
  24798. Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  24799. /**
  24800. * Defines that both eyes of the camera will be rendered side by side with a parallel target.
  24801. */
  24802. Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  24803. /**
  24804. * Defines that both eyes of the camera will be rendered side by side with a none parallel target.
  24805. */
  24806. Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  24807. /**
  24808. * Defines that both eyes of the camera will be rendered over under each other.
  24809. */
  24810. Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  24811. /**
  24812. * Defines that both eyes of the camera should be renderered in a VR mode (carbox).
  24813. */
  24814. Camera.RIG_MODE_VR = 20;
  24815. /**
  24816. * Defines that both eyes of the camera should be renderered in a VR mode (webVR).
  24817. */
  24818. Camera.RIG_MODE_WEBVR = 21;
  24819. /**
  24820. * Custom rig mode allowing rig cameras to be populated manually with any number of cameras
  24821. */
  24822. Camera.RIG_MODE_CUSTOM = 22;
  24823. /**
  24824. * Defines if by default attaching controls should prevent the default javascript event to continue.
  24825. */
  24826. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  24827. /**
  24828. * @hidden
  24829. * Might be removed once multiview will be a thing
  24830. */
  24831. Camera.UseAlternateWebVRRendering = false;
  24832. __decorate([
  24833. BABYLON.serializeAsVector3()
  24834. ], Camera.prototype, "position", void 0);
  24835. __decorate([
  24836. BABYLON.serializeAsVector3()
  24837. ], Camera.prototype, "upVector", void 0);
  24838. __decorate([
  24839. BABYLON.serialize()
  24840. ], Camera.prototype, "orthoLeft", void 0);
  24841. __decorate([
  24842. BABYLON.serialize()
  24843. ], Camera.prototype, "orthoRight", void 0);
  24844. __decorate([
  24845. BABYLON.serialize()
  24846. ], Camera.prototype, "orthoBottom", void 0);
  24847. __decorate([
  24848. BABYLON.serialize()
  24849. ], Camera.prototype, "orthoTop", void 0);
  24850. __decorate([
  24851. BABYLON.serialize()
  24852. ], Camera.prototype, "fov", void 0);
  24853. __decorate([
  24854. BABYLON.serialize()
  24855. ], Camera.prototype, "minZ", void 0);
  24856. __decorate([
  24857. BABYLON.serialize()
  24858. ], Camera.prototype, "maxZ", void 0);
  24859. __decorate([
  24860. BABYLON.serialize()
  24861. ], Camera.prototype, "inertia", void 0);
  24862. __decorate([
  24863. BABYLON.serialize()
  24864. ], Camera.prototype, "mode", void 0);
  24865. __decorate([
  24866. BABYLON.serialize()
  24867. ], Camera.prototype, "layerMask", void 0);
  24868. __decorate([
  24869. BABYLON.serialize()
  24870. ], Camera.prototype, "fovMode", void 0);
  24871. __decorate([
  24872. BABYLON.serialize()
  24873. ], Camera.prototype, "cameraRigMode", void 0);
  24874. __decorate([
  24875. BABYLON.serialize()
  24876. ], Camera.prototype, "interaxialDistance", void 0);
  24877. __decorate([
  24878. BABYLON.serialize()
  24879. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  24880. return Camera;
  24881. }(BABYLON.Node));
  24882. BABYLON.Camera = Camera;
  24883. })(BABYLON || (BABYLON = {}));
  24884. //# sourceMappingURL=babylon.camera.js.map
  24885. var BABYLON;
  24886. (function (BABYLON) {
  24887. /**
  24888. * This is the manager responsible of all the rendering for meshes sprites and particles.
  24889. * It is enable to manage the different groups as well as the different necessary sort functions.
  24890. * This should not be used directly aside of the few static configurations
  24891. */
  24892. var RenderingManager = /** @class */ (function () {
  24893. /**
  24894. * Instantiates a new rendering group for a particular scene
  24895. * @param scene Defines the scene the groups belongs to
  24896. */
  24897. function RenderingManager(scene) {
  24898. /**
  24899. * @hidden
  24900. */
  24901. this._useSceneAutoClearSetup = false;
  24902. this._renderingGroups = new Array();
  24903. this._autoClearDepthStencil = {};
  24904. this._customOpaqueSortCompareFn = {};
  24905. this._customAlphaTestSortCompareFn = {};
  24906. this._customTransparentSortCompareFn = {};
  24907. this._renderingGroupInfo = new BABYLON.RenderingGroupInfo();
  24908. this._scene = scene;
  24909. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  24910. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  24911. }
  24912. }
  24913. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  24914. if (depth === void 0) { depth = true; }
  24915. if (stencil === void 0) { stencil = true; }
  24916. if (this._depthStencilBufferAlreadyCleaned) {
  24917. return;
  24918. }
  24919. this._scene.getEngine().clear(null, false, depth, stencil);
  24920. this._depthStencilBufferAlreadyCleaned = true;
  24921. };
  24922. /**
  24923. * Renders the entire managed groups. This is used by the scene or the different rennder targets.
  24924. * @hidden
  24925. */
  24926. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  24927. // Update the observable context (not null as it only goes away on dispose)
  24928. var info = this._renderingGroupInfo;
  24929. info.scene = this._scene;
  24930. info.camera = this._scene.activeCamera;
  24931. // Dispatch sprites
  24932. if (this._scene.spriteManagers && renderSprites) {
  24933. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  24934. var manager = this._scene.spriteManagers[index];
  24935. this.dispatchSprites(manager);
  24936. }
  24937. }
  24938. // Render
  24939. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  24940. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  24941. var renderingGroup = this._renderingGroups[index];
  24942. if (!renderingGroup) {
  24943. continue;
  24944. }
  24945. var renderingGroupMask = Math.pow(2, index);
  24946. info.renderingGroupId = index;
  24947. // Before Observable
  24948. this._scene.onBeforeRenderingGroupObservable.notifyObservers(info, renderingGroupMask);
  24949. // Clear depth/stencil if needed
  24950. if (RenderingManager.AUTOCLEAR) {
  24951. var autoClear = this._useSceneAutoClearSetup ?
  24952. this._scene.getAutoClearDepthStencilSetup(index) :
  24953. this._autoClearDepthStencil[index];
  24954. if (autoClear && autoClear.autoClear) {
  24955. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  24956. }
  24957. }
  24958. // Render
  24959. for (var _i = 0, _a = this._scene._beforeRenderingGroupDrawStage; _i < _a.length; _i++) {
  24960. var step = _a[_i];
  24961. step.action(index);
  24962. }
  24963. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  24964. for (var _b = 0, _c = this._scene._afterRenderingGroupDrawStage; _b < _c.length; _b++) {
  24965. var step = _c[_b];
  24966. step.action(index);
  24967. }
  24968. // After Observable
  24969. this._scene.onAfterRenderingGroupObservable.notifyObservers(info, renderingGroupMask);
  24970. }
  24971. };
  24972. /**
  24973. * Resets the different information of the group to prepare a new frame
  24974. * @hidden
  24975. */
  24976. RenderingManager.prototype.reset = function () {
  24977. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  24978. var renderingGroup = this._renderingGroups[index];
  24979. if (renderingGroup) {
  24980. renderingGroup.prepare();
  24981. }
  24982. }
  24983. };
  24984. /**
  24985. * Dispose and release the group and its associated resources.
  24986. * @hidden
  24987. */
  24988. RenderingManager.prototype.dispose = function () {
  24989. this.freeRenderingGroups();
  24990. this._renderingGroups.length = 0;
  24991. this._renderingGroupInfo = null;
  24992. };
  24993. /**
  24994. * Clear the info related to rendering groups preventing retention points during dispose.
  24995. */
  24996. RenderingManager.prototype.freeRenderingGroups = function () {
  24997. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  24998. var renderingGroup = this._renderingGroups[index];
  24999. if (renderingGroup) {
  25000. renderingGroup.dispose();
  25001. }
  25002. }
  25003. };
  25004. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  25005. if (this._renderingGroups[renderingGroupId] === undefined) {
  25006. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  25007. }
  25008. };
  25009. /**
  25010. * Add a sprite manager to the rendering manager in order to render it this frame.
  25011. * @param spriteManager Define the sprite manager to render
  25012. */
  25013. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  25014. var renderingGroupId = spriteManager.renderingGroupId || 0;
  25015. this._prepareRenderingGroup(renderingGroupId);
  25016. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  25017. };
  25018. /**
  25019. * Add a particle system to the rendering manager in order to render it this frame.
  25020. * @param particleSystem Define the particle system to render
  25021. */
  25022. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  25023. var renderingGroupId = particleSystem.renderingGroupId || 0;
  25024. this._prepareRenderingGroup(renderingGroupId);
  25025. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  25026. };
  25027. /**
  25028. * Add a submesh to the manager in order to render it this frame
  25029. * @param subMesh The submesh to dispatch
  25030. * @param mesh Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  25031. * @param material Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  25032. */
  25033. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  25034. if (mesh === undefined) {
  25035. mesh = subMesh.getMesh();
  25036. }
  25037. var renderingGroupId = mesh.renderingGroupId || 0;
  25038. this._prepareRenderingGroup(renderingGroupId);
  25039. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  25040. };
  25041. /**
  25042. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  25043. * This allowed control for front to back rendering or reversly depending of the special needs.
  25044. *
  25045. * @param renderingGroupId The rendering group id corresponding to its index
  25046. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  25047. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  25048. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  25049. */
  25050. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  25051. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  25052. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  25053. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  25054. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  25055. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  25056. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  25057. if (this._renderingGroups[renderingGroupId]) {
  25058. var group = this._renderingGroups[renderingGroupId];
  25059. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  25060. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  25061. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  25062. }
  25063. };
  25064. /**
  25065. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  25066. *
  25067. * @param renderingGroupId The rendering group id corresponding to its index
  25068. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  25069. * @param depth Automatically clears depth between groups if true and autoClear is true.
  25070. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  25071. */
  25072. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  25073. if (depth === void 0) { depth = true; }
  25074. if (stencil === void 0) { stencil = true; }
  25075. this._autoClearDepthStencil[renderingGroupId] = {
  25076. autoClear: autoClearDepthStencil,
  25077. depth: depth,
  25078. stencil: stencil
  25079. };
  25080. };
  25081. /**
  25082. * Gets the current auto clear configuration for one rendering group of the rendering
  25083. * manager.
  25084. * @param index the rendering group index to get the information for
  25085. * @returns The auto clear setup for the requested rendering group
  25086. */
  25087. RenderingManager.prototype.getAutoClearDepthStencilSetup = function (index) {
  25088. return this._autoClearDepthStencil[index];
  25089. };
  25090. /**
  25091. * The max id used for rendering groups (not included)
  25092. */
  25093. RenderingManager.MAX_RENDERINGGROUPS = 4;
  25094. /**
  25095. * The min id used for rendering groups (included)
  25096. */
  25097. RenderingManager.MIN_RENDERINGGROUPS = 0;
  25098. /**
  25099. * Used to globally prevent autoclearing scenes.
  25100. */
  25101. RenderingManager.AUTOCLEAR = true;
  25102. return RenderingManager;
  25103. }());
  25104. BABYLON.RenderingManager = RenderingManager;
  25105. })(BABYLON || (BABYLON = {}));
  25106. //# sourceMappingURL=babylon.renderingManager.js.map
  25107. var BABYLON;
  25108. (function (BABYLON) {
  25109. /**
  25110. * This represents the object necessary to create a rendering group.
  25111. * This is exclusively used and created by the rendering manager.
  25112. * To modify the behavior, you use the available helpers in your scene or meshes.
  25113. * @hidden
  25114. */
  25115. var RenderingGroup = /** @class */ (function () {
  25116. /**
  25117. * Creates a new rendering group.
  25118. * @param index The rendering group index
  25119. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  25120. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  25121. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  25122. */
  25123. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  25124. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  25125. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  25126. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  25127. this.index = index;
  25128. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  25129. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  25130. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  25131. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  25132. this._particleSystems = new BABYLON.SmartArray(256);
  25133. this._spriteManagers = new BABYLON.SmartArray(256);
  25134. this._edgesRenderers = new BABYLON.SmartArray(16);
  25135. this._scene = scene;
  25136. this.opaqueSortCompareFn = opaqueSortCompareFn;
  25137. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  25138. this.transparentSortCompareFn = transparentSortCompareFn;
  25139. }
  25140. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  25141. /**
  25142. * Set the opaque sort comparison function.
  25143. * If null the sub meshes will be render in the order they were created
  25144. */
  25145. set: function (value) {
  25146. this._opaqueSortCompareFn = value;
  25147. if (value) {
  25148. this._renderOpaque = this.renderOpaqueSorted;
  25149. }
  25150. else {
  25151. this._renderOpaque = RenderingGroup.renderUnsorted;
  25152. }
  25153. },
  25154. enumerable: true,
  25155. configurable: true
  25156. });
  25157. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  25158. /**
  25159. * Set the alpha test sort comparison function.
  25160. * If null the sub meshes will be render in the order they were created
  25161. */
  25162. set: function (value) {
  25163. this._alphaTestSortCompareFn = value;
  25164. if (value) {
  25165. this._renderAlphaTest = this.renderAlphaTestSorted;
  25166. }
  25167. else {
  25168. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  25169. }
  25170. },
  25171. enumerable: true,
  25172. configurable: true
  25173. });
  25174. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  25175. /**
  25176. * Set the transparent sort comparison function.
  25177. * If null the sub meshes will be render in the order they were created
  25178. */
  25179. set: function (value) {
  25180. if (value) {
  25181. this._transparentSortCompareFn = value;
  25182. }
  25183. else {
  25184. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  25185. }
  25186. this._renderTransparent = this.renderTransparentSorted;
  25187. },
  25188. enumerable: true,
  25189. configurable: true
  25190. });
  25191. /**
  25192. * Render all the sub meshes contained in the group.
  25193. * @param customRenderFunction Used to override the default render behaviour of the group.
  25194. * @returns true if rendered some submeshes.
  25195. */
  25196. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  25197. if (customRenderFunction) {
  25198. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  25199. return;
  25200. }
  25201. var engine = this._scene.getEngine();
  25202. // Depth only
  25203. if (this._depthOnlySubMeshes.length !== 0) {
  25204. engine.setColorWrite(false);
  25205. this._renderAlphaTest(this._depthOnlySubMeshes);
  25206. engine.setColorWrite(true);
  25207. }
  25208. // Opaque
  25209. if (this._opaqueSubMeshes.length !== 0) {
  25210. this._renderOpaque(this._opaqueSubMeshes);
  25211. }
  25212. // Alpha test
  25213. if (this._alphaTestSubMeshes.length !== 0) {
  25214. this._renderAlphaTest(this._alphaTestSubMeshes);
  25215. }
  25216. var stencilState = engine.getStencilBuffer();
  25217. engine.setStencilBuffer(false);
  25218. // Sprites
  25219. if (renderSprites) {
  25220. this._renderSprites();
  25221. }
  25222. // Particles
  25223. if (renderParticles) {
  25224. this._renderParticles(activeMeshes);
  25225. }
  25226. if (this.onBeforeTransparentRendering) {
  25227. this.onBeforeTransparentRendering();
  25228. }
  25229. // Transparent
  25230. if (this._transparentSubMeshes.length !== 0) {
  25231. this._renderTransparent(this._transparentSubMeshes);
  25232. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  25233. }
  25234. // Set back stencil to false in case it changes before the edge renderer.
  25235. engine.setStencilBuffer(false);
  25236. // Edges
  25237. if (this._edgesRenderers.length) {
  25238. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  25239. this._edgesRenderers.data[edgesRendererIndex].render();
  25240. }
  25241. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  25242. }
  25243. // Restore Stencil state.
  25244. engine.setStencilBuffer(stencilState);
  25245. };
  25246. /**
  25247. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  25248. * @param subMeshes The submeshes to render
  25249. */
  25250. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  25251. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  25252. };
  25253. /**
  25254. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  25255. * @param subMeshes The submeshes to render
  25256. */
  25257. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  25258. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  25259. };
  25260. /**
  25261. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  25262. * @param subMeshes The submeshes to render
  25263. */
  25264. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  25265. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  25266. };
  25267. /**
  25268. * Renders the submeshes in a specified order.
  25269. * @param subMeshes The submeshes to sort before render
  25270. * @param sortCompareFn The comparison function use to sort
  25271. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  25272. * @param transparent Specifies to activate blending if true
  25273. */
  25274. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  25275. var subIndex = 0;
  25276. var subMesh;
  25277. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  25278. for (; subIndex < subMeshes.length; subIndex++) {
  25279. subMesh = subMeshes.data[subIndex];
  25280. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  25281. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  25282. }
  25283. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  25284. if (sortCompareFn) {
  25285. sortedArray.sort(sortCompareFn);
  25286. }
  25287. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  25288. subMesh = sortedArray[subIndex];
  25289. if (transparent) {
  25290. var material = subMesh.getMaterial();
  25291. if (material && material.needDepthPrePass) {
  25292. var engine = material.getScene().getEngine();
  25293. engine.setColorWrite(false);
  25294. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  25295. subMesh.render(false);
  25296. engine.setColorWrite(true);
  25297. }
  25298. }
  25299. subMesh.render(transparent);
  25300. }
  25301. };
  25302. /**
  25303. * Renders the submeshes in the order they were dispatched (no sort applied).
  25304. * @param subMeshes The submeshes to render
  25305. */
  25306. RenderingGroup.renderUnsorted = function (subMeshes) {
  25307. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  25308. var submesh = subMeshes.data[subIndex];
  25309. submesh.render(false);
  25310. }
  25311. };
  25312. /**
  25313. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  25314. * are rendered back to front if in the same alpha index.
  25315. *
  25316. * @param a The first submesh
  25317. * @param b The second submesh
  25318. * @returns The result of the comparison
  25319. */
  25320. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  25321. // Alpha index first
  25322. if (a._alphaIndex > b._alphaIndex) {
  25323. return 1;
  25324. }
  25325. if (a._alphaIndex < b._alphaIndex) {
  25326. return -1;
  25327. }
  25328. // Then distance to camera
  25329. return RenderingGroup.backToFrontSortCompare(a, b);
  25330. };
  25331. /**
  25332. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  25333. * are rendered back to front.
  25334. *
  25335. * @param a The first submesh
  25336. * @param b The second submesh
  25337. * @returns The result of the comparison
  25338. */
  25339. RenderingGroup.backToFrontSortCompare = function (a, b) {
  25340. // Then distance to camera
  25341. if (a._distanceToCamera < b._distanceToCamera) {
  25342. return 1;
  25343. }
  25344. if (a._distanceToCamera > b._distanceToCamera) {
  25345. return -1;
  25346. }
  25347. return 0;
  25348. };
  25349. /**
  25350. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  25351. * are rendered front to back (prevent overdraw).
  25352. *
  25353. * @param a The first submesh
  25354. * @param b The second submesh
  25355. * @returns The result of the comparison
  25356. */
  25357. RenderingGroup.frontToBackSortCompare = function (a, b) {
  25358. // Then distance to camera
  25359. if (a._distanceToCamera < b._distanceToCamera) {
  25360. return -1;
  25361. }
  25362. if (a._distanceToCamera > b._distanceToCamera) {
  25363. return 1;
  25364. }
  25365. return 0;
  25366. };
  25367. /**
  25368. * Resets the different lists of submeshes to prepare a new frame.
  25369. */
  25370. RenderingGroup.prototype.prepare = function () {
  25371. this._opaqueSubMeshes.reset();
  25372. this._transparentSubMeshes.reset();
  25373. this._alphaTestSubMeshes.reset();
  25374. this._depthOnlySubMeshes.reset();
  25375. this._particleSystems.reset();
  25376. this._spriteManagers.reset();
  25377. this._edgesRenderers.reset();
  25378. };
  25379. RenderingGroup.prototype.dispose = function () {
  25380. this._opaqueSubMeshes.dispose();
  25381. this._transparentSubMeshes.dispose();
  25382. this._alphaTestSubMeshes.dispose();
  25383. this._depthOnlySubMeshes.dispose();
  25384. this._particleSystems.dispose();
  25385. this._spriteManagers.dispose();
  25386. this._edgesRenderers.dispose();
  25387. };
  25388. /**
  25389. * Inserts the submesh in its correct queue depending on its material.
  25390. * @param subMesh The submesh to dispatch
  25391. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  25392. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  25393. */
  25394. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  25395. // Get mesh and materials if not provided
  25396. if (mesh === undefined) {
  25397. mesh = subMesh.getMesh();
  25398. }
  25399. if (material === undefined) {
  25400. material = subMesh.getMaterial();
  25401. }
  25402. if (material === null || material === undefined) {
  25403. return;
  25404. }
  25405. if (material.needAlphaBlendingForMesh(mesh)) { // Transparent
  25406. this._transparentSubMeshes.push(subMesh);
  25407. }
  25408. else if (material.needAlphaTesting()) { // Alpha test
  25409. if (material.needDepthPrePass) {
  25410. this._depthOnlySubMeshes.push(subMesh);
  25411. }
  25412. this._alphaTestSubMeshes.push(subMesh);
  25413. }
  25414. else {
  25415. if (material.needDepthPrePass) {
  25416. this._depthOnlySubMeshes.push(subMesh);
  25417. }
  25418. this._opaqueSubMeshes.push(subMesh); // Opaque
  25419. }
  25420. if (mesh._edgesRenderer && mesh._edgesRenderer.isEnabled) {
  25421. this._edgesRenderers.push(mesh._edgesRenderer);
  25422. }
  25423. };
  25424. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  25425. this._spriteManagers.push(spriteManager);
  25426. };
  25427. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  25428. this._particleSystems.push(particleSystem);
  25429. };
  25430. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  25431. if (this._particleSystems.length === 0) {
  25432. return;
  25433. }
  25434. // Particles
  25435. var activeCamera = this._scene.activeCamera;
  25436. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  25437. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  25438. var particleSystem = this._particleSystems.data[particleIndex];
  25439. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  25440. continue;
  25441. }
  25442. var emitter = particleSystem.emitter;
  25443. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  25444. this._scene._activeParticles.addCount(particleSystem.render(), false);
  25445. }
  25446. }
  25447. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  25448. };
  25449. RenderingGroup.prototype._renderSprites = function () {
  25450. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  25451. return;
  25452. }
  25453. // Sprites
  25454. var activeCamera = this._scene.activeCamera;
  25455. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  25456. for (var id = 0; id < this._spriteManagers.length; id++) {
  25457. var spriteManager = this._spriteManagers.data[id];
  25458. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  25459. spriteManager.render();
  25460. }
  25461. }
  25462. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  25463. };
  25464. return RenderingGroup;
  25465. }());
  25466. BABYLON.RenderingGroup = RenderingGroup;
  25467. })(BABYLON || (BABYLON = {}));
  25468. //# sourceMappingURL=babylon.renderingGroup.js.map
  25469. var BABYLON;
  25470. (function (BABYLON) {
  25471. /**
  25472. * Groups all the scene component constants in one place to ease maintenance.
  25473. * @hidden
  25474. */
  25475. var SceneComponentConstants = /** @class */ (function () {
  25476. function SceneComponentConstants() {
  25477. }
  25478. SceneComponentConstants.NAME_EFFECTLAYER = "EffectLayer";
  25479. SceneComponentConstants.NAME_LAYER = "Layer";
  25480. SceneComponentConstants.NAME_LENSFLARESYSTEM = "LensFlareSystem";
  25481. SceneComponentConstants.NAME_BOUNDINGBOXRENDERER = "BoundingBoxRenderer";
  25482. SceneComponentConstants.NAME_PARTICLESYSTEM = "ParticleSystem";
  25483. SceneComponentConstants.NAME_GAMEPAD = "Gamepad";
  25484. SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE = "SimplificationQueue";
  25485. SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER = "GeometryBufferRenderer";
  25486. SceneComponentConstants.NAME_DEPTHRENDERER = "DepthRenderer";
  25487. SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER = "PostProcessRenderPipelineManager";
  25488. SceneComponentConstants.NAME_SPRITE = "Sprite";
  25489. SceneComponentConstants.NAME_OUTLINERENDERER = "Outline";
  25490. SceneComponentConstants.NAME_PROCEDURALTEXTURE = "ProceduralTexture";
  25491. SceneComponentConstants.NAME_SHADOWGENERATOR = "ShadowGenerator";
  25492. SceneComponentConstants.NAME_OCTREE = "Octree";
  25493. SceneComponentConstants.NAME_PHYSICSENGINE = "PhysicsEngine";
  25494. SceneComponentConstants.NAME_AUDIO = "Audio";
  25495. SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER = 0;
  25496. SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER = 0;
  25497. SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER = 0;
  25498. SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER = 0;
  25499. SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER = 1;
  25500. SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER = 0;
  25501. SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER = 1;
  25502. SceneComponentConstants.STEP_BEFORERENDERTARGETDRAW_LAYER = 0;
  25503. SceneComponentConstants.STEP_BEFORERENDERINGMESH_OUTLINE = 0;
  25504. SceneComponentConstants.STEP_AFTERRENDERINGMESH_OUTLINE = 0;
  25505. SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW = 0;
  25506. SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER = 1;
  25507. SceneComponentConstants.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE = 0;
  25508. SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD = 1;
  25509. SceneComponentConstants.STEP_BEFORECLEAR_PROCEDURALTEXTURE = 0;
  25510. SceneComponentConstants.STEP_AFTERRENDERTARGETDRAW_LAYER = 0;
  25511. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER = 0;
  25512. SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM = 1;
  25513. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW = 2;
  25514. SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER = 3;
  25515. SceneComponentConstants.STEP_AFTERRENDER_AUDIO = 0;
  25516. SceneComponentConstants.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR = 0;
  25517. SceneComponentConstants.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER = 1;
  25518. SceneComponentConstants.STEP_GATHERRENDERTARGETS_DEPTHRENDERER = 2;
  25519. SceneComponentConstants.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER = 3;
  25520. SceneComponentConstants.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER = 0;
  25521. SceneComponentConstants.STEP_POINTERMOVE_SPRITE = 0;
  25522. SceneComponentConstants.STEP_POINTERDOWN_SPRITE = 0;
  25523. SceneComponentConstants.STEP_POINTERUP_SPRITE = 0;
  25524. return SceneComponentConstants;
  25525. }());
  25526. BABYLON.SceneComponentConstants = SceneComponentConstants;
  25527. /**
  25528. * Repressentation of a stage in the scene (Basically a list of ordered steps)
  25529. * @hidden
  25530. */
  25531. var Stage = /** @class */ (function (_super) {
  25532. __extends(Stage, _super);
  25533. /**
  25534. * Hide ctor from the rest of the world.
  25535. * @param items The items to add.
  25536. */
  25537. function Stage(items) {
  25538. return _super.apply(this, items) || this;
  25539. }
  25540. /**
  25541. * Creates a new Stage.
  25542. * @returns A new instance of a Stage
  25543. */
  25544. Stage.Create = function () {
  25545. return Object.create(Stage.prototype);
  25546. };
  25547. /**
  25548. * Registers a step in an ordered way in the targeted stage.
  25549. * @param index Defines the position to register the step in
  25550. * @param component Defines the component attached to the step
  25551. * @param action Defines the action to launch during the step
  25552. */
  25553. Stage.prototype.registerStep = function (index, component, action) {
  25554. var i = 0;
  25555. var maxIndex = Number.MAX_VALUE;
  25556. for (; i < this.length; i++) {
  25557. var step = this[i];
  25558. maxIndex = step.index;
  25559. if (index < maxIndex) {
  25560. break;
  25561. }
  25562. }
  25563. this.splice(i, 0, { index: index, component: component, action: action.bind(component) });
  25564. };
  25565. /**
  25566. * Clears all the steps from the stage.
  25567. */
  25568. Stage.prototype.clear = function () {
  25569. this.length = 0;
  25570. };
  25571. return Stage;
  25572. }(Array));
  25573. BABYLON.Stage = Stage;
  25574. })(BABYLON || (BABYLON = {}));
  25575. //# sourceMappingURL=babylon.sceneComponent.js.map
  25576. var BABYLON;
  25577. (function (BABYLON) {
  25578. /**
  25579. * Base class of the scene acting as a container for the different elements composing a scene.
  25580. * This class is dynamically extended by the different components of the scene increasing
  25581. * flexibility and reducing coupling
  25582. */
  25583. var AbstractScene = /** @class */ (function () {
  25584. function AbstractScene() {
  25585. /**
  25586. * Gets the list of root nodes (ie. nodes with no parent)
  25587. */
  25588. this.rootNodes = new Array();
  25589. /** All of the cameras added to this scene
  25590. * @see http://doc.babylonjs.com/babylon101/cameras
  25591. */
  25592. this.cameras = new Array();
  25593. /**
  25594. * All of the lights added to this scene
  25595. * @see http://doc.babylonjs.com/babylon101/lights
  25596. */
  25597. this.lights = new Array();
  25598. /**
  25599. * All of the (abstract) meshes added to this scene
  25600. */
  25601. this.meshes = new Array();
  25602. /**
  25603. * The list of skeletons added to the scene
  25604. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  25605. */
  25606. this.skeletons = new Array();
  25607. /**
  25608. * All of the particle systems added to this scene
  25609. * @see http://doc.babylonjs.com/babylon101/particles
  25610. */
  25611. this.particleSystems = new Array();
  25612. /**
  25613. * Gets a list of Animations associated with the scene
  25614. */
  25615. this.animations = [];
  25616. /**
  25617. * All of the animation groups added to this scene
  25618. * @see http://doc.babylonjs.com/how_to/group
  25619. */
  25620. this.animationGroups = new Array();
  25621. /**
  25622. * All of the multi-materials added to this scene
  25623. * @see http://doc.babylonjs.com/how_to/multi_materials
  25624. */
  25625. this.multiMaterials = new Array();
  25626. /**
  25627. * All of the materials added to this scene
  25628. * In the context of a Scene, it is not supposed to be modified manually.
  25629. * Any addition or removal should be done using the addMaterial and removeMAterial Scene methods.
  25630. * Note also that the order of the Material wihin the array is not significant and might change.
  25631. * @see http://doc.babylonjs.com/babylon101/materials
  25632. */
  25633. this.materials = new Array();
  25634. /**
  25635. * The list of morph target managers added to the scene
  25636. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  25637. */
  25638. this.morphTargetManagers = new Array();
  25639. /**
  25640. * The list of geometries used in the scene.
  25641. */
  25642. this.geometries = new Array();
  25643. /**
  25644. * All of the tranform nodes added to this scene
  25645. * In the context of a Scene, it is not supposed to be modified manually.
  25646. * Any addition or removal should be done using the addTransformNode and removeTransformNode Scene methods.
  25647. * Note also that the order of the TransformNode wihin the array is not significant and might change.
  25648. * @see http://doc.babylonjs.com/how_to/transformnode
  25649. */
  25650. this.transformNodes = new Array();
  25651. /**
  25652. * ActionManagers available on the scene.
  25653. */
  25654. this.actionManagers = new Array();
  25655. /**
  25656. * Textures to keep.
  25657. */
  25658. this.textures = new Array();
  25659. }
  25660. /**
  25661. * Adds a parser in the list of available ones
  25662. * @param name Defines the name of the parser
  25663. * @param parser Defines the parser to add
  25664. */
  25665. AbstractScene.AddParser = function (name, parser) {
  25666. this._BabylonFileParsers[name] = parser;
  25667. };
  25668. /**
  25669. * Gets a general parser from the list of avaialble ones
  25670. * @param name Defines the name of the parser
  25671. * @returns the requested parser or null
  25672. */
  25673. AbstractScene.GetParser = function (name) {
  25674. if (this._BabylonFileParsers[name]) {
  25675. return this._BabylonFileParsers[name];
  25676. }
  25677. return null;
  25678. };
  25679. /**
  25680. * Adds n individual parser in the list of available ones
  25681. * @param name Defines the name of the parser
  25682. * @param parser Defines the parser to add
  25683. */
  25684. AbstractScene.AddIndividualParser = function (name, parser) {
  25685. this._IndividualBabylonFileParsers[name] = parser;
  25686. };
  25687. /**
  25688. * Gets an individual parser from the list of avaialble ones
  25689. * @param name Defines the name of the parser
  25690. * @returns the requested parser or null
  25691. */
  25692. AbstractScene.GetIndividualParser = function (name) {
  25693. if (this._IndividualBabylonFileParsers[name]) {
  25694. return this._IndividualBabylonFileParsers[name];
  25695. }
  25696. return null;
  25697. };
  25698. /**
  25699. * Parser json data and populate both a scene and its associated container object
  25700. * @param jsonData Defines the data to parse
  25701. * @param scene Defines the scene to parse the data for
  25702. * @param container Defines the container attached to the parsing sequence
  25703. * @param rootUrl Defines the root url of the data
  25704. */
  25705. AbstractScene.Parse = function (jsonData, scene, container, rootUrl) {
  25706. for (var parserName in this._BabylonFileParsers) {
  25707. if (this._BabylonFileParsers.hasOwnProperty(parserName)) {
  25708. this._BabylonFileParsers[parserName](jsonData, scene, container, rootUrl);
  25709. }
  25710. }
  25711. };
  25712. /**
  25713. * Stores the list of available parsers in the application.
  25714. */
  25715. AbstractScene._BabylonFileParsers = {};
  25716. /**
  25717. * Stores the list of available individual parsers in the application.
  25718. */
  25719. AbstractScene._IndividualBabylonFileParsers = {};
  25720. return AbstractScene;
  25721. }());
  25722. BABYLON.AbstractScene = AbstractScene;
  25723. })(BABYLON || (BABYLON = {}));
  25724. //# sourceMappingURL=babylon.abstractScene.js.map
  25725. var BABYLON;
  25726. (function (BABYLON) {
  25727. /** @hidden */
  25728. var ClickInfo = /** @class */ (function () {
  25729. function ClickInfo() {
  25730. this._singleClick = false;
  25731. this._doubleClick = false;
  25732. this._hasSwiped = false;
  25733. this._ignore = false;
  25734. }
  25735. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  25736. get: function () {
  25737. return this._singleClick;
  25738. },
  25739. set: function (b) {
  25740. this._singleClick = b;
  25741. },
  25742. enumerable: true,
  25743. configurable: true
  25744. });
  25745. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  25746. get: function () {
  25747. return this._doubleClick;
  25748. },
  25749. set: function (b) {
  25750. this._doubleClick = b;
  25751. },
  25752. enumerable: true,
  25753. configurable: true
  25754. });
  25755. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  25756. get: function () {
  25757. return this._hasSwiped;
  25758. },
  25759. set: function (b) {
  25760. this._hasSwiped = b;
  25761. },
  25762. enumerable: true,
  25763. configurable: true
  25764. });
  25765. Object.defineProperty(ClickInfo.prototype, "ignore", {
  25766. get: function () {
  25767. return this._ignore;
  25768. },
  25769. set: function (b) {
  25770. this._ignore = b;
  25771. },
  25772. enumerable: true,
  25773. configurable: true
  25774. });
  25775. return ClickInfo;
  25776. }());
  25777. /**
  25778. * This class is used by the onRenderingGroupObservable
  25779. */
  25780. var RenderingGroupInfo = /** @class */ (function () {
  25781. function RenderingGroupInfo() {
  25782. }
  25783. return RenderingGroupInfo;
  25784. }());
  25785. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  25786. /**
  25787. * Represents a scene to be rendered by the engine.
  25788. * @see http://doc.babylonjs.com/features/scene
  25789. */
  25790. var Scene = /** @class */ (function (_super) {
  25791. __extends(Scene, _super);
  25792. /**
  25793. * Creates a new Scene
  25794. * @param engine defines the engine to use to render this scene
  25795. */
  25796. function Scene(engine, options) {
  25797. var _this = _super.call(this) || this;
  25798. // Members
  25799. /**
  25800. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  25801. */
  25802. _this.autoClear = true;
  25803. /**
  25804. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  25805. */
  25806. _this.autoClearDepthAndStencil = true;
  25807. /**
  25808. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  25809. */
  25810. _this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  25811. /**
  25812. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  25813. */
  25814. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  25815. _this._forceWireframe = false;
  25816. _this._forcePointsCloud = false;
  25817. /**
  25818. * Gets or sets a boolean indicating if animations are enabled
  25819. */
  25820. _this.animationsEnabled = true;
  25821. _this._animationPropertiesOverride = null;
  25822. /**
  25823. * Gets or sets a boolean indicating if a constant deltatime has to be used
  25824. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  25825. */
  25826. _this.useConstantAnimationDeltaTime = false;
  25827. /**
  25828. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  25829. * Please note that it requires to run a ray cast through the scene on every frame
  25830. */
  25831. _this.constantlyUpdateMeshUnderPointer = false;
  25832. /**
  25833. * Defines the HTML cursor to use when hovering over interactive elements
  25834. */
  25835. _this.hoverCursor = "pointer";
  25836. /**
  25837. * Defines the HTML default cursor to use (empty by default)
  25838. */
  25839. _this.defaultCursor = "";
  25840. /**
  25841. * This is used to call preventDefault() on pointer down
  25842. * in order to block unwanted artifacts like system double clicks
  25843. */
  25844. _this.preventDefaultOnPointerDown = true;
  25845. /**
  25846. * This is used to call preventDefault() on pointer up
  25847. * in order to block unwanted artifacts like system double clicks
  25848. */
  25849. _this.preventDefaultOnPointerUp = true;
  25850. // Metadata
  25851. /**
  25852. * Gets or sets user defined metadata
  25853. */
  25854. _this.metadata = null;
  25855. /**
  25856. * For internal use only. Please do not use.
  25857. */
  25858. _this.reservedDataStore = null;
  25859. /**
  25860. * Use this array to add regular expressions used to disable offline support for specific urls
  25861. */
  25862. _this.disableOfflineSupportExceptionRules = new Array();
  25863. /**
  25864. * An event triggered when the scene is disposed.
  25865. */
  25866. _this.onDisposeObservable = new BABYLON.Observable();
  25867. _this._onDisposeObserver = null;
  25868. /**
  25869. * An event triggered before rendering the scene (right after animations and physics)
  25870. */
  25871. _this.onBeforeRenderObservable = new BABYLON.Observable();
  25872. _this._onBeforeRenderObserver = null;
  25873. /**
  25874. * An event triggered after rendering the scene
  25875. */
  25876. _this.onAfterRenderObservable = new BABYLON.Observable();
  25877. _this._onAfterRenderObserver = null;
  25878. /**
  25879. * An event triggered before animating the scene
  25880. */
  25881. _this.onBeforeAnimationsObservable = new BABYLON.Observable();
  25882. /**
  25883. * An event triggered after animations processing
  25884. */
  25885. _this.onAfterAnimationsObservable = new BABYLON.Observable();
  25886. /**
  25887. * An event triggered before draw calls are ready to be sent
  25888. */
  25889. _this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  25890. /**
  25891. * An event triggered after draw calls have been sent
  25892. */
  25893. _this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  25894. /**
  25895. * An event triggered when the scene is ready
  25896. */
  25897. _this.onReadyObservable = new BABYLON.Observable();
  25898. /**
  25899. * An event triggered before rendering a camera
  25900. */
  25901. _this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  25902. _this._onBeforeCameraRenderObserver = null;
  25903. /**
  25904. * An event triggered after rendering a camera
  25905. */
  25906. _this.onAfterCameraRenderObservable = new BABYLON.Observable();
  25907. _this._onAfterCameraRenderObserver = null;
  25908. /**
  25909. * An event triggered when active meshes evaluation is about to start
  25910. */
  25911. _this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  25912. /**
  25913. * An event triggered when active meshes evaluation is done
  25914. */
  25915. _this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  25916. /**
  25917. * An event triggered when particles rendering is about to start
  25918. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  25919. */
  25920. _this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  25921. /**
  25922. * An event triggered when particles rendering is done
  25923. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  25924. */
  25925. _this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  25926. /**
  25927. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  25928. */
  25929. _this.onDataLoadedObservable = new BABYLON.Observable();
  25930. /**
  25931. * An event triggered when a camera is created
  25932. */
  25933. _this.onNewCameraAddedObservable = new BABYLON.Observable();
  25934. /**
  25935. * An event triggered when a camera is removed
  25936. */
  25937. _this.onCameraRemovedObservable = new BABYLON.Observable();
  25938. /**
  25939. * An event triggered when a light is created
  25940. */
  25941. _this.onNewLightAddedObservable = new BABYLON.Observable();
  25942. /**
  25943. * An event triggered when a light is removed
  25944. */
  25945. _this.onLightRemovedObservable = new BABYLON.Observable();
  25946. /**
  25947. * An event triggered when a geometry is created
  25948. */
  25949. _this.onNewGeometryAddedObservable = new BABYLON.Observable();
  25950. /**
  25951. * An event triggered when a geometry is removed
  25952. */
  25953. _this.onGeometryRemovedObservable = new BABYLON.Observable();
  25954. /**
  25955. * An event triggered when a transform node is created
  25956. */
  25957. _this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  25958. /**
  25959. * An event triggered when a transform node is removed
  25960. */
  25961. _this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  25962. /**
  25963. * An event triggered when a mesh is created
  25964. */
  25965. _this.onNewMeshAddedObservable = new BABYLON.Observable();
  25966. /**
  25967. * An event triggered when a mesh is removed
  25968. */
  25969. _this.onMeshRemovedObservable = new BABYLON.Observable();
  25970. /**
  25971. * An event triggered when a material is created
  25972. */
  25973. _this.onNewMaterialAddedObservable = new BABYLON.Observable();
  25974. /**
  25975. * An event triggered when a material is removed
  25976. */
  25977. _this.onMaterialRemovedObservable = new BABYLON.Observable();
  25978. /**
  25979. * An event triggered when a texture is created
  25980. */
  25981. _this.onNewTextureAddedObservable = new BABYLON.Observable();
  25982. /**
  25983. * An event triggered when a texture is removed
  25984. */
  25985. _this.onTextureRemovedObservable = new BABYLON.Observable();
  25986. /**
  25987. * An event triggered when render targets are about to be rendered
  25988. * Can happen multiple times per frame.
  25989. */
  25990. _this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  25991. /**
  25992. * An event triggered when render targets were rendered.
  25993. * Can happen multiple times per frame.
  25994. */
  25995. _this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  25996. /**
  25997. * An event triggered before calculating deterministic simulation step
  25998. */
  25999. _this.onBeforeStepObservable = new BABYLON.Observable();
  26000. /**
  26001. * An event triggered after calculating deterministic simulation step
  26002. */
  26003. _this.onAfterStepObservable = new BABYLON.Observable();
  26004. /**
  26005. * An event triggered when the activeCamera property is updated
  26006. */
  26007. _this.onActiveCameraChanged = new BABYLON.Observable();
  26008. /**
  26009. * This Observable will be triggered before rendering each renderingGroup of each rendered camera.
  26010. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  26011. * 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)
  26012. */
  26013. _this.onBeforeRenderingGroupObservable = new BABYLON.Observable();
  26014. /**
  26015. * This Observable will be triggered after rendering each renderingGroup of each rendered camera.
  26016. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  26017. * 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)
  26018. */
  26019. _this.onAfterRenderingGroupObservable = new BABYLON.Observable();
  26020. /**
  26021. * This Observable will when a mesh has been imported into the scene.
  26022. */
  26023. _this.onMeshImportedObservable = new BABYLON.Observable();
  26024. // Animations
  26025. _this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  26026. /**
  26027. * 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).
  26028. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  26029. */
  26030. _this.onPrePointerObservable = new BABYLON.Observable();
  26031. /**
  26032. * Observable event triggered each time an input event is received from the rendering canvas
  26033. */
  26034. _this.onPointerObservable = new BABYLON.Observable();
  26035. _this._meshPickProceed = false;
  26036. _this._currentPickResult = null;
  26037. _this._previousPickResult = null;
  26038. _this._totalPointersPressed = 0;
  26039. _this._doubleClickOccured = false;
  26040. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  26041. _this.cameraToUseForPointers = null;
  26042. _this._pointerX = 0;
  26043. _this._pointerY = 0;
  26044. _this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  26045. _this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  26046. _this._startingPointerTime = 0;
  26047. _this._previousStartingPointerTime = 0;
  26048. _this._pointerCaptures = {};
  26049. // Deterministic lockstep
  26050. _this._timeAccumulator = 0;
  26051. _this._currentStepId = 0;
  26052. _this._currentInternalStep = 0;
  26053. // Keyboard
  26054. /**
  26055. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  26056. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  26057. */
  26058. _this.onPreKeyboardObservable = new BABYLON.Observable();
  26059. /**
  26060. * Observable event triggered each time an keyboard event is received from the hosting window
  26061. */
  26062. _this.onKeyboardObservable = new BABYLON.Observable();
  26063. // Coordinates system
  26064. _this._useRightHandedSystem = false;
  26065. // Fog
  26066. _this._fogEnabled = true;
  26067. _this._fogMode = Scene.FOGMODE_NONE;
  26068. /**
  26069. * Gets or sets the fog color to use
  26070. * @see http://doc.babylonjs.com/babylon101/environment#fog
  26071. * (Default is Color3(0.2, 0.2, 0.3))
  26072. */
  26073. _this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  26074. /**
  26075. * Gets or sets the fog density to use
  26076. * @see http://doc.babylonjs.com/babylon101/environment#fog
  26077. * (Default is 0.1)
  26078. */
  26079. _this.fogDensity = 0.1;
  26080. /**
  26081. * Gets or sets the fog start distance to use
  26082. * @see http://doc.babylonjs.com/babylon101/environment#fog
  26083. * (Default is 0)
  26084. */
  26085. _this.fogStart = 0;
  26086. /**
  26087. * Gets or sets the fog end distance to use
  26088. * @see http://doc.babylonjs.com/babylon101/environment#fog
  26089. * (Default is 1000)
  26090. */
  26091. _this.fogEnd = 1000.0;
  26092. // Lights
  26093. _this._shadowsEnabled = true;
  26094. _this._lightsEnabled = true;
  26095. /** All of the active cameras added to this scene. */
  26096. _this.activeCameras = new Array();
  26097. // Textures
  26098. _this._texturesEnabled = true;
  26099. // Particles
  26100. /**
  26101. * Gets or sets a boolean indicating if particles are enabled on this scene
  26102. */
  26103. _this.particlesEnabled = true;
  26104. // Sprites
  26105. /**
  26106. * Gets or sets a boolean indicating if sprites are enabled on this scene
  26107. */
  26108. _this.spritesEnabled = true;
  26109. // Skeletons
  26110. _this._skeletonsEnabled = true;
  26111. // Lens flares
  26112. /**
  26113. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  26114. */
  26115. _this.lensFlaresEnabled = true;
  26116. // Collisions
  26117. /**
  26118. * Gets or sets a boolean indicating if collisions are enabled on this scene
  26119. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  26120. */
  26121. _this.collisionsEnabled = true;
  26122. /**
  26123. * Defines the gravity applied to this scene (used only for collisions)
  26124. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  26125. */
  26126. _this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  26127. // Postprocesses
  26128. /**
  26129. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  26130. */
  26131. _this.postProcessesEnabled = true;
  26132. /**
  26133. * The list of postprocesses added to the scene
  26134. */
  26135. _this.postProcesses = new Array();
  26136. // Customs render targets
  26137. /**
  26138. * Gets or sets a boolean indicating if render targets are enabled on this scene
  26139. */
  26140. _this.renderTargetsEnabled = true;
  26141. /**
  26142. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  26143. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  26144. */
  26145. _this.dumpNextRenderTargets = false;
  26146. /**
  26147. * The list of user defined render targets added to the scene
  26148. */
  26149. _this.customRenderTargets = new Array();
  26150. /**
  26151. * Gets the list of meshes imported to the scene through SceneLoader
  26152. */
  26153. _this.importedMeshesFiles = new Array();
  26154. // Probes
  26155. /**
  26156. * Gets or sets a boolean indicating if probes are enabled on this scene
  26157. */
  26158. _this.probesEnabled = true;
  26159. _this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  26160. // Procedural textures
  26161. /**
  26162. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  26163. */
  26164. _this.proceduralTexturesEnabled = true;
  26165. // Performance counters
  26166. _this._totalVertices = new BABYLON.PerfCounter();
  26167. /** @hidden */
  26168. _this._activeIndices = new BABYLON.PerfCounter();
  26169. /** @hidden */
  26170. _this._activeParticles = new BABYLON.PerfCounter();
  26171. /** @hidden */
  26172. _this._activeBones = new BABYLON.PerfCounter();
  26173. _this._animationTime = 0;
  26174. /**
  26175. * Gets or sets a general scale for animation speed
  26176. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  26177. */
  26178. _this.animationTimeScale = 1;
  26179. _this._renderId = 0;
  26180. _this._frameId = 0;
  26181. _this._executeWhenReadyTimeoutId = -1;
  26182. _this._intermediateRendering = false;
  26183. _this._viewUpdateFlag = -1;
  26184. _this._projectionUpdateFlag = -1;
  26185. _this._alternateViewUpdateFlag = -1;
  26186. _this._alternateProjectionUpdateFlag = -1;
  26187. /** @hidden */
  26188. _this._toBeDisposed = new Array(256);
  26189. _this._activeRequests = new Array();
  26190. _this._pendingData = new Array();
  26191. _this._isDisposed = false;
  26192. /**
  26193. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  26194. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  26195. */
  26196. _this.dispatchAllSubMeshesOfActiveMeshes = false;
  26197. _this._activeMeshes = new BABYLON.SmartArray(256);
  26198. _this._processedMaterials = new BABYLON.SmartArray(256);
  26199. _this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  26200. /** @hidden */
  26201. _this._activeParticleSystems = new BABYLON.SmartArray(256);
  26202. _this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  26203. _this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  26204. /** @hidden */
  26205. _this._activeAnimatables = new Array();
  26206. _this._transformMatrix = BABYLON.Matrix.Zero();
  26207. _this._useAlternateCameraConfiguration = false;
  26208. _this._alternateRendering = false;
  26209. _this._wheelEventName = "";
  26210. /**
  26211. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  26212. * This is useful if there are more lights that the maximum simulteanous authorized
  26213. */
  26214. _this.requireLightSorting = false;
  26215. /**
  26216. * @hidden
  26217. * Backing store of defined scene components.
  26218. */
  26219. _this._components = [];
  26220. /**
  26221. * @hidden
  26222. * Backing store of defined scene components.
  26223. */
  26224. _this._serializableComponents = [];
  26225. /**
  26226. * List of components to register on the next registration step.
  26227. */
  26228. _this._transientComponents = [];
  26229. /**
  26230. * @hidden
  26231. * Defines the actions happening before camera updates.
  26232. */
  26233. _this._beforeCameraUpdateStage = BABYLON.Stage.Create();
  26234. /**
  26235. * @hidden
  26236. * Defines the actions happening before clear the canvas.
  26237. */
  26238. _this._beforeClearStage = BABYLON.Stage.Create();
  26239. /**
  26240. * @hidden
  26241. * Defines the actions when collecting render targets for the frame.
  26242. */
  26243. _this._gatherRenderTargetsStage = BABYLON.Stage.Create();
  26244. /**
  26245. * @hidden
  26246. * Defines the actions happening for one camera in the frame.
  26247. */
  26248. _this._gatherActiveCameraRenderTargetsStage = BABYLON.Stage.Create();
  26249. /**
  26250. * @hidden
  26251. * Defines the actions happening during the per mesh ready checks.
  26252. */
  26253. _this._isReadyForMeshStage = BABYLON.Stage.Create();
  26254. /**
  26255. * @hidden
  26256. * Defines the actions happening before evaluate active mesh checks.
  26257. */
  26258. _this._beforeEvaluateActiveMeshStage = BABYLON.Stage.Create();
  26259. /**
  26260. * @hidden
  26261. * Defines the actions happening during the evaluate sub mesh checks.
  26262. */
  26263. _this._evaluateSubMeshStage = BABYLON.Stage.Create();
  26264. /**
  26265. * @hidden
  26266. * Defines the actions happening during the active mesh stage.
  26267. */
  26268. _this._activeMeshStage = BABYLON.Stage.Create();
  26269. /**
  26270. * @hidden
  26271. * Defines the actions happening during the per camera render target step.
  26272. */
  26273. _this._cameraDrawRenderTargetStage = BABYLON.Stage.Create();
  26274. /**
  26275. * @hidden
  26276. * Defines the actions happening just before the active camera is drawing.
  26277. */
  26278. _this._beforeCameraDrawStage = BABYLON.Stage.Create();
  26279. /**
  26280. * @hidden
  26281. * Defines the actions happening just before a render target is drawing.
  26282. */
  26283. _this._beforeRenderTargetDrawStage = BABYLON.Stage.Create();
  26284. /**
  26285. * @hidden
  26286. * Defines the actions happening just before a rendering group is drawing.
  26287. */
  26288. _this._beforeRenderingGroupDrawStage = BABYLON.Stage.Create();
  26289. /**
  26290. * @hidden
  26291. * Defines the actions happening just before a mesh is drawing.
  26292. */
  26293. _this._beforeRenderingMeshStage = BABYLON.Stage.Create();
  26294. /**
  26295. * @hidden
  26296. * Defines the actions happening just after a mesh has been drawn.
  26297. */
  26298. _this._afterRenderingMeshStage = BABYLON.Stage.Create();
  26299. /**
  26300. * @hidden
  26301. * Defines the actions happening just after a rendering group has been drawn.
  26302. */
  26303. _this._afterRenderingGroupDrawStage = BABYLON.Stage.Create();
  26304. /**
  26305. * @hidden
  26306. * Defines the actions happening just after the active camera has been drawn.
  26307. */
  26308. _this._afterCameraDrawStage = BABYLON.Stage.Create();
  26309. /**
  26310. * @hidden
  26311. * Defines the actions happening just after a render target has been drawn.
  26312. */
  26313. _this._afterRenderTargetDrawStage = BABYLON.Stage.Create();
  26314. /**
  26315. * @hidden
  26316. * Defines the actions happening just after rendering all cameras and computing intersections.
  26317. */
  26318. _this._afterRenderStage = BABYLON.Stage.Create();
  26319. /**
  26320. * @hidden
  26321. * Defines the actions happening when a pointer move event happens.
  26322. */
  26323. _this._pointerMoveStage = BABYLON.Stage.Create();
  26324. /**
  26325. * @hidden
  26326. * Defines the actions happening when a pointer down event happens.
  26327. */
  26328. _this._pointerDownStage = BABYLON.Stage.Create();
  26329. /**
  26330. * @hidden
  26331. * Defines the actions happening when a pointer up event happens.
  26332. */
  26333. _this._pointerUpStage = BABYLON.Stage.Create();
  26334. /**
  26335. * an optional map from Geometry Id to Geometry index in the 'geometries' array
  26336. */
  26337. _this.geometriesByUniqueId = null;
  26338. _this._defaultMeshCandidates = {
  26339. data: [],
  26340. length: 0
  26341. };
  26342. _this._defaultSubMeshCandidates = {
  26343. data: [],
  26344. length: 0
  26345. };
  26346. _this._preventFreeActiveMeshesAndRenderingGroups = false;
  26347. _this._activeMeshesFrozen = false;
  26348. /** @hidden */
  26349. _this._allowPostProcessClearColor = true;
  26350. /**
  26351. * User updatable function that will return a deterministic frame time when engine is in deterministic lock step mode
  26352. */
  26353. _this.getDeterministicFrameTime = function () {
  26354. return 1000.0 / 60.0; // frame time in ms
  26355. };
  26356. _this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  26357. _this._blockMaterialDirtyMechanism = false;
  26358. _this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  26359. _this._engine.scenes.push(_this);
  26360. _this._uid = null;
  26361. _this._renderingManager = new BABYLON.RenderingManager(_this);
  26362. if (BABYLON.PostProcessManager) {
  26363. _this.postProcessManager = new BABYLON.PostProcessManager(_this);
  26364. }
  26365. if (BABYLON.Tools.IsWindowObjectExist()) {
  26366. _this.attachControl();
  26367. }
  26368. //collision coordinator initialization. For now legacy per default.
  26369. _this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  26370. // Uniform Buffer
  26371. _this._createUbo();
  26372. // Default Image processing definition
  26373. if (BABYLON.ImageProcessingConfiguration) {
  26374. _this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  26375. }
  26376. _this.setDefaultCandidateProviders();
  26377. if (options && options.useGeometryUniqueIdsMap === true) {
  26378. _this.geometriesByUniqueId = {};
  26379. }
  26380. _this.useMaterialMeshMap = options && options.useGeometryUniqueIdsMap || false;
  26381. _this.useClonedMeshhMap = options && options.useClonedMeshhMap || false;
  26382. _this._engine.onNewSceneAddedObservable.notifyObservers(_this);
  26383. return _this;
  26384. }
  26385. Object.defineProperty(Scene.prototype, "environmentTexture", {
  26386. /**
  26387. * Texture used in all pbr material as the reflection texture.
  26388. * As in the majority of the scene they are the same (exception for multi room and so on),
  26389. * this is easier to reference from here than from all the materials.
  26390. */
  26391. get: function () {
  26392. return this._environmentTexture;
  26393. },
  26394. /**
  26395. * Texture used in all pbr material as the reflection texture.
  26396. * As in the majority of the scene they are the same (exception for multi room and so on),
  26397. * this is easier to set here than in all the materials.
  26398. */
  26399. set: function (value) {
  26400. if (this._environmentTexture === value) {
  26401. return;
  26402. }
  26403. this._environmentTexture = value;
  26404. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  26405. },
  26406. enumerable: true,
  26407. configurable: true
  26408. });
  26409. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  26410. /**
  26411. * Default image processing configuration used either in the rendering
  26412. * Forward main pass or through the imageProcessingPostProcess if present.
  26413. * As in the majority of the scene they are the same (exception for multi camera),
  26414. * this is easier to reference from here than from all the materials and post process.
  26415. *
  26416. * No setter as we it is a shared configuration, you can set the values instead.
  26417. */
  26418. get: function () {
  26419. return this._imageProcessingConfiguration;
  26420. },
  26421. enumerable: true,
  26422. configurable: true
  26423. });
  26424. Object.defineProperty(Scene.prototype, "forceWireframe", {
  26425. get: function () {
  26426. return this._forceWireframe;
  26427. },
  26428. /**
  26429. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  26430. */
  26431. set: function (value) {
  26432. if (this._forceWireframe === value) {
  26433. return;
  26434. }
  26435. this._forceWireframe = value;
  26436. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  26437. },
  26438. enumerable: true,
  26439. configurable: true
  26440. });
  26441. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  26442. get: function () {
  26443. return this._forcePointsCloud;
  26444. },
  26445. /**
  26446. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  26447. */
  26448. set: function (value) {
  26449. if (this._forcePointsCloud === value) {
  26450. return;
  26451. }
  26452. this._forcePointsCloud = value;
  26453. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  26454. },
  26455. enumerable: true,
  26456. configurable: true
  26457. });
  26458. Object.defineProperty(Scene.prototype, "animationPropertiesOverride", {
  26459. /**
  26460. * Gets or sets the animation properties override
  26461. */
  26462. get: function () {
  26463. return this._animationPropertiesOverride;
  26464. },
  26465. set: function (value) {
  26466. this._animationPropertiesOverride = value;
  26467. },
  26468. enumerable: true,
  26469. configurable: true
  26470. });
  26471. Object.defineProperty(Scene.prototype, "onDispose", {
  26472. /** Sets a function to be executed when this scene is disposed. */
  26473. set: function (callback) {
  26474. if (this._onDisposeObserver) {
  26475. this.onDisposeObservable.remove(this._onDisposeObserver);
  26476. }
  26477. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  26478. },
  26479. enumerable: true,
  26480. configurable: true
  26481. });
  26482. Object.defineProperty(Scene.prototype, "beforeRender", {
  26483. /** Sets a function to be executed before rendering this scene */
  26484. set: function (callback) {
  26485. if (this._onBeforeRenderObserver) {
  26486. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  26487. }
  26488. if (callback) {
  26489. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  26490. }
  26491. },
  26492. enumerable: true,
  26493. configurable: true
  26494. });
  26495. Object.defineProperty(Scene.prototype, "afterRender", {
  26496. /** Sets a function to be executed after rendering this scene */
  26497. set: function (callback) {
  26498. if (this._onAfterRenderObserver) {
  26499. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  26500. }
  26501. if (callback) {
  26502. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  26503. }
  26504. },
  26505. enumerable: true,
  26506. configurable: true
  26507. });
  26508. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  26509. /** Sets a function to be executed before rendering a camera*/
  26510. set: function (callback) {
  26511. if (this._onBeforeCameraRenderObserver) {
  26512. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  26513. }
  26514. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  26515. },
  26516. enumerable: true,
  26517. configurable: true
  26518. });
  26519. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  26520. /** Sets a function to be executed after rendering a camera*/
  26521. set: function (callback) {
  26522. if (this._onAfterCameraRenderObserver) {
  26523. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  26524. }
  26525. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  26526. },
  26527. enumerable: true,
  26528. configurable: true
  26529. });
  26530. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  26531. /**
  26532. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  26533. */
  26534. get: function () {
  26535. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  26536. },
  26537. enumerable: true,
  26538. configurable: true
  26539. });
  26540. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  26541. get: function () {
  26542. return this._useRightHandedSystem;
  26543. },
  26544. /**
  26545. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  26546. */
  26547. set: function (value) {
  26548. if (this._useRightHandedSystem === value) {
  26549. return;
  26550. }
  26551. this._useRightHandedSystem = value;
  26552. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  26553. },
  26554. enumerable: true,
  26555. configurable: true
  26556. });
  26557. /**
  26558. * Sets the step Id used by deterministic lock step
  26559. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  26560. * @param newStepId defines the step Id
  26561. */
  26562. Scene.prototype.setStepId = function (newStepId) {
  26563. this._currentStepId = newStepId;
  26564. };
  26565. /**
  26566. * Gets the step Id used by deterministic lock step
  26567. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  26568. * @returns the step Id
  26569. */
  26570. Scene.prototype.getStepId = function () {
  26571. return this._currentStepId;
  26572. };
  26573. /**
  26574. * Gets the internal step used by deterministic lock step
  26575. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  26576. * @returns the internal step
  26577. */
  26578. Scene.prototype.getInternalStep = function () {
  26579. return this._currentInternalStep;
  26580. };
  26581. Object.defineProperty(Scene.prototype, "fogEnabled", {
  26582. get: function () {
  26583. return this._fogEnabled;
  26584. },
  26585. /**
  26586. * Gets or sets a boolean indicating if fog is enabled on this scene
  26587. * @see http://doc.babylonjs.com/babylon101/environment#fog
  26588. * (Default is true)
  26589. */
  26590. set: function (value) {
  26591. if (this._fogEnabled === value) {
  26592. return;
  26593. }
  26594. this._fogEnabled = value;
  26595. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  26596. },
  26597. enumerable: true,
  26598. configurable: true
  26599. });
  26600. Object.defineProperty(Scene.prototype, "fogMode", {
  26601. get: function () {
  26602. return this._fogMode;
  26603. },
  26604. /**
  26605. * Gets or sets the fog mode to use
  26606. * @see http://doc.babylonjs.com/babylon101/environment#fog
  26607. * | mode | value |
  26608. * | --- | --- |
  26609. * | FOGMODE_NONE | 0 |
  26610. * | FOGMODE_EXP | 1 |
  26611. * | FOGMODE_EXP2 | 2 |
  26612. * | FOGMODE_LINEAR | 3 |
  26613. */
  26614. set: function (value) {
  26615. if (this._fogMode === value) {
  26616. return;
  26617. }
  26618. this._fogMode = value;
  26619. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  26620. },
  26621. enumerable: true,
  26622. configurable: true
  26623. });
  26624. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  26625. get: function () {
  26626. return this._shadowsEnabled;
  26627. },
  26628. /**
  26629. * Gets or sets a boolean indicating if shadows are enabled on this scene
  26630. */
  26631. set: function (value) {
  26632. if (this._shadowsEnabled === value) {
  26633. return;
  26634. }
  26635. this._shadowsEnabled = value;
  26636. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  26637. },
  26638. enumerable: true,
  26639. configurable: true
  26640. });
  26641. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  26642. get: function () {
  26643. return this._lightsEnabled;
  26644. },
  26645. /**
  26646. * Gets or sets a boolean indicating if lights are enabled on this scene
  26647. */
  26648. set: function (value) {
  26649. if (this._lightsEnabled === value) {
  26650. return;
  26651. }
  26652. this._lightsEnabled = value;
  26653. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  26654. },
  26655. enumerable: true,
  26656. configurable: true
  26657. });
  26658. Object.defineProperty(Scene.prototype, "activeCamera", {
  26659. /** Gets or sets the current active camera */
  26660. get: function () {
  26661. return this._activeCamera;
  26662. },
  26663. set: function (value) {
  26664. if (value === this._activeCamera) {
  26665. return;
  26666. }
  26667. this._activeCamera = value;
  26668. this.onActiveCameraChanged.notifyObservers(this);
  26669. },
  26670. enumerable: true,
  26671. configurable: true
  26672. });
  26673. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  26674. /** The default material used on meshes when no material is affected */
  26675. get: function () {
  26676. if (!this._defaultMaterial) {
  26677. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  26678. }
  26679. return this._defaultMaterial;
  26680. },
  26681. /** The default material used on meshes when no material is affected */
  26682. set: function (value) {
  26683. this._defaultMaterial = value;
  26684. },
  26685. enumerable: true,
  26686. configurable: true
  26687. });
  26688. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  26689. get: function () {
  26690. return this._texturesEnabled;
  26691. },
  26692. /**
  26693. * Gets or sets a boolean indicating if textures are enabled on this scene
  26694. */
  26695. set: function (value) {
  26696. if (this._texturesEnabled === value) {
  26697. return;
  26698. }
  26699. this._texturesEnabled = value;
  26700. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  26701. },
  26702. enumerable: true,
  26703. configurable: true
  26704. });
  26705. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  26706. get: function () {
  26707. return this._skeletonsEnabled;
  26708. },
  26709. /**
  26710. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  26711. */
  26712. set: function (value) {
  26713. if (this._skeletonsEnabled === value) {
  26714. return;
  26715. }
  26716. this._skeletonsEnabled = value;
  26717. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  26718. },
  26719. enumerable: true,
  26720. configurable: true
  26721. });
  26722. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  26723. /** @hidden */
  26724. get: function () {
  26725. return this._alternateRendering;
  26726. },
  26727. enumerable: true,
  26728. configurable: true
  26729. });
  26730. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  26731. /**
  26732. * Gets the list of frustum planes (built from the active camera)
  26733. */
  26734. get: function () {
  26735. return this._frustumPlanes;
  26736. },
  26737. enumerable: true,
  26738. configurable: true
  26739. });
  26740. /**
  26741. * Registers the transient components if needed.
  26742. */
  26743. Scene.prototype._registerTransientComponents = function () {
  26744. // Register components that have been associated lately to the scene.
  26745. if (this._transientComponents.length > 0) {
  26746. for (var _i = 0, _a = this._transientComponents; _i < _a.length; _i++) {
  26747. var component = _a[_i];
  26748. component.register();
  26749. }
  26750. this._transientComponents = [];
  26751. }
  26752. };
  26753. /**
  26754. * @hidden
  26755. * Add a component to the scene.
  26756. * Note that the ccomponent could be registered on th next frame if this is called after
  26757. * the register component stage.
  26758. * @param component Defines the component to add to the scene
  26759. */
  26760. Scene.prototype._addComponent = function (component) {
  26761. this._components.push(component);
  26762. this._transientComponents.push(component);
  26763. var serializableComponent = component;
  26764. if (serializableComponent.addFromContainer) {
  26765. this._serializableComponents.push(serializableComponent);
  26766. }
  26767. };
  26768. /**
  26769. * @hidden
  26770. * Gets a component from the scene.
  26771. * @param name defines the name of the component to retrieve
  26772. * @returns the component or null if not present
  26773. */
  26774. Scene.prototype._getComponent = function (name) {
  26775. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  26776. var component = _a[_i];
  26777. if (component.name === name) {
  26778. return component;
  26779. }
  26780. }
  26781. return null;
  26782. };
  26783. /**
  26784. * @hidden
  26785. */
  26786. Scene.prototype._getDefaultMeshCandidates = function () {
  26787. this._defaultMeshCandidates.data = this.meshes;
  26788. this._defaultMeshCandidates.length = this.meshes.length;
  26789. return this._defaultMeshCandidates;
  26790. };
  26791. /**
  26792. * @hidden
  26793. */
  26794. Scene.prototype._getDefaultSubMeshCandidates = function (mesh) {
  26795. this._defaultSubMeshCandidates.data = mesh.subMeshes;
  26796. this._defaultSubMeshCandidates.length = mesh.subMeshes.length;
  26797. return this._defaultSubMeshCandidates;
  26798. };
  26799. /**
  26800. * Sets the default candidate providers for the scene.
  26801. * This sets the getActiveMeshCandidates, getActiveSubMeshCandidates, getIntersectingSubMeshCandidates
  26802. * and getCollidingSubMeshCandidates to their default function
  26803. */
  26804. Scene.prototype.setDefaultCandidateProviders = function () {
  26805. this.getActiveMeshCandidates = this._getDefaultMeshCandidates.bind(this);
  26806. this.getActiveSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  26807. this.getIntersectingSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  26808. this.getCollidingSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  26809. };
  26810. Object.defineProperty(Scene.prototype, "workerCollisions", {
  26811. /**
  26812. * Gets a boolean indicating if collisions are processed on a web worker
  26813. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  26814. */
  26815. get: function () {
  26816. return this._workerCollisions;
  26817. },
  26818. set: function (enabled) {
  26819. if (!BABYLON.CollisionCoordinatorLegacy) {
  26820. return;
  26821. }
  26822. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  26823. this._workerCollisions = enabled;
  26824. if (this.collisionCoordinator) {
  26825. this.collisionCoordinator.destroy();
  26826. }
  26827. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  26828. this.collisionCoordinator.init(this);
  26829. },
  26830. enumerable: true,
  26831. configurable: true
  26832. });
  26833. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  26834. /**
  26835. * Gets the mesh that is currently under the pointer
  26836. */
  26837. get: function () {
  26838. return this._pointerOverMesh;
  26839. },
  26840. enumerable: true,
  26841. configurable: true
  26842. });
  26843. Object.defineProperty(Scene.prototype, "pointerX", {
  26844. /**
  26845. * Gets the current on-screen X position of the pointer
  26846. */
  26847. get: function () {
  26848. return this._pointerX;
  26849. },
  26850. enumerable: true,
  26851. configurable: true
  26852. });
  26853. Object.defineProperty(Scene.prototype, "pointerY", {
  26854. /**
  26855. * Gets the current on-screen Y position of the pointer
  26856. */
  26857. get: function () {
  26858. return this._pointerY;
  26859. },
  26860. enumerable: true,
  26861. configurable: true
  26862. });
  26863. /**
  26864. * Gets the cached material (ie. the latest rendered one)
  26865. * @returns the cached material
  26866. */
  26867. Scene.prototype.getCachedMaterial = function () {
  26868. return this._cachedMaterial;
  26869. };
  26870. /**
  26871. * Gets the cached effect (ie. the latest rendered one)
  26872. * @returns the cached effect
  26873. */
  26874. Scene.prototype.getCachedEffect = function () {
  26875. return this._cachedEffect;
  26876. };
  26877. /**
  26878. * Gets the cached visibility state (ie. the latest rendered one)
  26879. * @returns the cached visibility state
  26880. */
  26881. Scene.prototype.getCachedVisibility = function () {
  26882. return this._cachedVisibility;
  26883. };
  26884. /**
  26885. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  26886. * @param material defines the current material
  26887. * @param effect defines the current effect
  26888. * @param visibility defines the current visibility state
  26889. * @returns true if one parameter is not cached
  26890. */
  26891. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  26892. if (visibility === void 0) { visibility = 1; }
  26893. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  26894. };
  26895. /**
  26896. * Gets the engine associated with the scene
  26897. * @returns an Engine
  26898. */
  26899. Scene.prototype.getEngine = function () {
  26900. return this._engine;
  26901. };
  26902. /**
  26903. * Gets the total number of vertices rendered per frame
  26904. * @returns the total number of vertices rendered per frame
  26905. */
  26906. Scene.prototype.getTotalVertices = function () {
  26907. return this._totalVertices.current;
  26908. };
  26909. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  26910. /**
  26911. * Gets the performance counter for total vertices
  26912. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  26913. */
  26914. get: function () {
  26915. return this._totalVertices;
  26916. },
  26917. enumerable: true,
  26918. configurable: true
  26919. });
  26920. /**
  26921. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  26922. * @returns the total number of active indices rendered per frame
  26923. */
  26924. Scene.prototype.getActiveIndices = function () {
  26925. return this._activeIndices.current;
  26926. };
  26927. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  26928. /**
  26929. * Gets the performance counter for active indices
  26930. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  26931. */
  26932. get: function () {
  26933. return this._activeIndices;
  26934. },
  26935. enumerable: true,
  26936. configurable: true
  26937. });
  26938. /**
  26939. * Gets the total number of active particles rendered per frame
  26940. * @returns the total number of active particles rendered per frame
  26941. */
  26942. Scene.prototype.getActiveParticles = function () {
  26943. return this._activeParticles.current;
  26944. };
  26945. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  26946. /**
  26947. * Gets the performance counter for active particles
  26948. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  26949. */
  26950. get: function () {
  26951. return this._activeParticles;
  26952. },
  26953. enumerable: true,
  26954. configurable: true
  26955. });
  26956. /**
  26957. * Gets the total number of active bones rendered per frame
  26958. * @returns the total number of active bones rendered per frame
  26959. */
  26960. Scene.prototype.getActiveBones = function () {
  26961. return this._activeBones.current;
  26962. };
  26963. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  26964. /**
  26965. * Gets the performance counter for active bones
  26966. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  26967. */
  26968. get: function () {
  26969. return this._activeBones;
  26970. },
  26971. enumerable: true,
  26972. configurable: true
  26973. });
  26974. /**
  26975. * Gets the array of active meshes
  26976. * @returns an array of AbstractMesh
  26977. */
  26978. Scene.prototype.getActiveMeshes = function () {
  26979. return this._activeMeshes;
  26980. };
  26981. /**
  26982. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  26983. * @returns a number
  26984. */
  26985. Scene.prototype.getAnimationRatio = function () {
  26986. return this._animationRatio !== undefined ? this._animationRatio : 1;
  26987. };
  26988. /**
  26989. * Gets an unique Id for the current render phase
  26990. * @returns a number
  26991. */
  26992. Scene.prototype.getRenderId = function () {
  26993. return this._renderId;
  26994. };
  26995. /**
  26996. * Gets an unique Id for the current frame
  26997. * @returns a number
  26998. */
  26999. Scene.prototype.getFrameId = function () {
  27000. return this._frameId;
  27001. };
  27002. /** Call this function if you want to manually increment the render Id*/
  27003. Scene.prototype.incrementRenderId = function () {
  27004. this._renderId++;
  27005. };
  27006. Scene.prototype._updatePointerPosition = function (evt) {
  27007. var canvasRect = this._engine.getRenderingCanvasClientRect();
  27008. if (!canvasRect) {
  27009. return;
  27010. }
  27011. this._pointerX = evt.clientX - canvasRect.left;
  27012. this._pointerY = evt.clientY - canvasRect.top;
  27013. this._unTranslatedPointerX = this._pointerX;
  27014. this._unTranslatedPointerY = this._pointerY;
  27015. };
  27016. Scene.prototype._createUbo = function () {
  27017. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  27018. this._sceneUbo.addUniform("viewProjection", 16);
  27019. this._sceneUbo.addUniform("view", 16);
  27020. };
  27021. Scene.prototype._createAlternateUbo = function () {
  27022. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  27023. this._alternateSceneUbo.addUniform("viewProjection", 16);
  27024. this._alternateSceneUbo.addUniform("view", 16);
  27025. };
  27026. // Pointers handling
  27027. Scene.prototype._setRayOnPointerInfo = function (pointerInfo) {
  27028. if (pointerInfo.pickInfo) {
  27029. if (!pointerInfo.pickInfo.ray) {
  27030. pointerInfo.pickInfo.ray = this.createPickingRay(pointerInfo.event.offsetX, pointerInfo.event.offsetY, BABYLON.Matrix.Identity(), this.activeCamera);
  27031. }
  27032. }
  27033. };
  27034. /**
  27035. * Use this method to simulate a pointer move on a mesh
  27036. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  27037. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  27038. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  27039. * @returns the current scene
  27040. */
  27041. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  27042. var evt = new PointerEvent("pointermove", pointerEventInit);
  27043. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERMOVE)) {
  27044. return this;
  27045. }
  27046. return this._processPointerMove(pickResult, evt);
  27047. };
  27048. Scene.prototype._processPointerMove = function (pickResult, evt) {
  27049. var canvas = this._engine.getRenderingCanvas();
  27050. if (!canvas) {
  27051. return this;
  27052. }
  27053. // Restore pointer
  27054. canvas.style.cursor = this.defaultCursor;
  27055. var isMeshPicked = (pickResult && pickResult.hit && pickResult.pickedMesh) ? true : false;
  27056. if (isMeshPicked) {
  27057. this.setPointerOverMesh(pickResult.pickedMesh);
  27058. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  27059. if (this._pointerOverMesh.actionManager.hoverCursor) {
  27060. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  27061. }
  27062. else {
  27063. canvas.style.cursor = this.hoverCursor;
  27064. }
  27065. }
  27066. }
  27067. else {
  27068. this.setPointerOverMesh(null);
  27069. }
  27070. for (var _i = 0, _a = this._pointerMoveStage; _i < _a.length; _i++) {
  27071. var step = _a[_i];
  27072. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, isMeshPicked, canvas);
  27073. }
  27074. if (pickResult) {
  27075. var type = evt.type === this._wheelEventName ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  27076. if (this.onPointerMove) {
  27077. this.onPointerMove(evt, pickResult, type);
  27078. }
  27079. if (this.onPointerObservable.hasObservers()) {
  27080. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  27081. this._setRayOnPointerInfo(pi);
  27082. this.onPointerObservable.notifyObservers(pi, type);
  27083. }
  27084. }
  27085. return this;
  27086. };
  27087. Scene.prototype._checkPrePointerObservable = function (pickResult, evt, type) {
  27088. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  27089. if (pickResult) {
  27090. pi.ray = pickResult.ray;
  27091. }
  27092. this.onPrePointerObservable.notifyObservers(pi, type);
  27093. if (pi.skipOnPointerObservable) {
  27094. return true;
  27095. }
  27096. else {
  27097. return false;
  27098. }
  27099. };
  27100. /**
  27101. * Use this method to simulate a pointer down on a mesh
  27102. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  27103. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  27104. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  27105. * @returns the current scene
  27106. */
  27107. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  27108. var evt = new PointerEvent("pointerdown", pointerEventInit);
  27109. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  27110. return this;
  27111. }
  27112. return this._processPointerDown(pickResult, evt);
  27113. };
  27114. Scene.prototype._processPointerDown = function (pickResult, evt) {
  27115. var _this = this;
  27116. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  27117. this._pickedDownMesh = pickResult.pickedMesh;
  27118. var actionManager = pickResult.pickedMesh.actionManager;
  27119. if (actionManager) {
  27120. if (actionManager.hasPickTriggers) {
  27121. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  27122. switch (evt.button) {
  27123. case 0:
  27124. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  27125. break;
  27126. case 1:
  27127. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  27128. break;
  27129. case 2:
  27130. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  27131. break;
  27132. }
  27133. }
  27134. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  27135. window.setTimeout(function () {
  27136. 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);
  27137. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  27138. if (_this._totalPointersPressed !== 0 &&
  27139. ((Date.now() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  27140. !_this._isPointerSwiping()) {
  27141. _this._startingPointerTime = 0;
  27142. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  27143. }
  27144. }
  27145. }, Scene.LongPressDelay);
  27146. }
  27147. }
  27148. }
  27149. else {
  27150. for (var _i = 0, _a = this._pointerDownStage; _i < _a.length; _i++) {
  27151. var step = _a[_i];
  27152. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, evt);
  27153. }
  27154. }
  27155. if (pickResult) {
  27156. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  27157. if (this.onPointerDown) {
  27158. this.onPointerDown(evt, pickResult, type);
  27159. }
  27160. if (this.onPointerObservable.hasObservers()) {
  27161. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  27162. this._setRayOnPointerInfo(pi);
  27163. this.onPointerObservable.notifyObservers(pi, type);
  27164. }
  27165. }
  27166. return this;
  27167. };
  27168. /**
  27169. * Use this method to simulate a pointer up on a mesh
  27170. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  27171. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  27172. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  27173. * @param doubleTap indicates that the pointer up event should be considered as part of a double click (false by default)
  27174. * @returns the current scene
  27175. */
  27176. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit, doubleTap) {
  27177. var evt = new PointerEvent("pointerup", pointerEventInit);
  27178. var clickInfo = new ClickInfo();
  27179. if (doubleTap) {
  27180. clickInfo.doubleClick = true;
  27181. }
  27182. else {
  27183. clickInfo.singleClick = true;
  27184. }
  27185. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  27186. return this;
  27187. }
  27188. return this._processPointerUp(pickResult, evt, clickInfo);
  27189. };
  27190. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  27191. if (pickResult && pickResult && pickResult.pickedMesh) {
  27192. this._pickedUpMesh = pickResult.pickedMesh;
  27193. if (this._pickedDownMesh === this._pickedUpMesh) {
  27194. if (this.onPointerPick) {
  27195. this.onPointerPick(evt, pickResult);
  27196. }
  27197. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  27198. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  27199. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  27200. this._setRayOnPointerInfo(pi);
  27201. this.onPointerObservable.notifyObservers(pi, type_1);
  27202. }
  27203. }
  27204. if (pickResult.pickedMesh.actionManager && !clickInfo.ignore) {
  27205. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  27206. if (!clickInfo.hasSwiped && clickInfo.singleClick) {
  27207. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  27208. }
  27209. if (clickInfo.doubleClick && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  27210. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  27211. }
  27212. }
  27213. }
  27214. else {
  27215. if (!clickInfo.ignore) {
  27216. for (var _i = 0, _a = this._pointerUpStage; _i < _a.length; _i++) {
  27217. var step = _a[_i];
  27218. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, evt);
  27219. }
  27220. }
  27221. }
  27222. if (this._pickedDownMesh &&
  27223. this._pickedDownMesh.actionManager &&
  27224. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  27225. this._pickedDownMesh !== this._pickedUpMesh) {
  27226. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  27227. }
  27228. var type = 0;
  27229. if (this.onPointerObservable.hasObservers()) {
  27230. if (!clickInfo.ignore && !clickInfo.hasSwiped) {
  27231. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  27232. type = BABYLON.PointerEventTypes.POINTERTAP;
  27233. }
  27234. else if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  27235. type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  27236. }
  27237. if (type) {
  27238. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  27239. this._setRayOnPointerInfo(pi);
  27240. this.onPointerObservable.notifyObservers(pi, type);
  27241. }
  27242. }
  27243. if (!clickInfo.ignore) {
  27244. type = BABYLON.PointerEventTypes.POINTERUP;
  27245. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  27246. this._setRayOnPointerInfo(pi);
  27247. this.onPointerObservable.notifyObservers(pi, type);
  27248. }
  27249. }
  27250. if (this.onPointerUp && !clickInfo.ignore) {
  27251. this.onPointerUp(evt, pickResult, type);
  27252. }
  27253. return this;
  27254. };
  27255. /**
  27256. * Gets a boolean indicating if the current pointer event is captured (meaning that the scene has already handled the pointer down)
  27257. * @param pointerId defines the pointer id to use in a multi-touch scenario (0 by default)
  27258. * @returns true if the pointer was captured
  27259. */
  27260. Scene.prototype.isPointerCaptured = function (pointerId) {
  27261. if (pointerId === void 0) { pointerId = 0; }
  27262. return this._pointerCaptures[pointerId];
  27263. };
  27264. /** @hidden */
  27265. Scene.prototype._isPointerSwiping = function () {
  27266. return Math.abs(this._startingPointerPosition.x - this._pointerX) > Scene.DragMovementThreshold ||
  27267. Math.abs(this._startingPointerPosition.y - this._pointerY) > Scene.DragMovementThreshold;
  27268. };
  27269. /**
  27270. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  27271. * @param attachUp defines if you want to attach events to pointerup
  27272. * @param attachDown defines if you want to attach events to pointerdown
  27273. * @param attachMove defines if you want to attach events to pointermove
  27274. */
  27275. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  27276. var _this = this;
  27277. if (attachUp === void 0) { attachUp = true; }
  27278. if (attachDown === void 0) { attachDown = true; }
  27279. if (attachMove === void 0) { attachMove = true; }
  27280. this._initActionManager = function (act, clickInfo) {
  27281. if (!_this._meshPickProceed) {
  27282. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  27283. _this._currentPickResult = pickResult;
  27284. if (pickResult) {
  27285. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  27286. }
  27287. _this._meshPickProceed = true;
  27288. }
  27289. return act;
  27290. };
  27291. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  27292. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  27293. if ((Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  27294. btn !== _this._previousButtonPressed) {
  27295. _this._doubleClickOccured = false;
  27296. clickInfo.singleClick = true;
  27297. clickInfo.ignore = false;
  27298. cb(clickInfo, _this._currentPickResult);
  27299. }
  27300. };
  27301. this._initClickEvent = function (obs1, obs2, evt, cb) {
  27302. var clickInfo = new ClickInfo();
  27303. _this._currentPickResult = null;
  27304. var act = null;
  27305. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  27306. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  27307. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  27308. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  27309. act = _this._initActionManager(act, clickInfo);
  27310. if (act) {
  27311. checkPicking = act.hasPickTriggers;
  27312. }
  27313. }
  27314. var needToIgnoreNext = false;
  27315. if (checkPicking) {
  27316. var btn = evt.button;
  27317. clickInfo.hasSwiped = _this._isPointerSwiping();
  27318. if (!clickInfo.hasSwiped) {
  27319. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  27320. if (!checkSingleClickImmediately) {
  27321. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  27322. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  27323. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  27324. act = _this._initActionManager(act, clickInfo);
  27325. if (act) {
  27326. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  27327. }
  27328. }
  27329. }
  27330. if (checkSingleClickImmediately) {
  27331. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  27332. if (Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  27333. btn !== _this._previousButtonPressed) {
  27334. clickInfo.singleClick = true;
  27335. cb(clickInfo, _this._currentPickResult);
  27336. needToIgnoreNext = true;
  27337. }
  27338. }
  27339. // at least one double click is required to be check and exclusive double click is enabled
  27340. else {
  27341. // wait that no double click has been raised during the double click delay
  27342. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  27343. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  27344. }
  27345. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  27346. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  27347. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  27348. act = _this._initActionManager(act, clickInfo);
  27349. if (act) {
  27350. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  27351. }
  27352. }
  27353. if (checkDoubleClick) {
  27354. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  27355. if (btn === _this._previousButtonPressed &&
  27356. Date.now() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  27357. !_this._doubleClickOccured) {
  27358. // pointer has not moved for 2 clicks, it's a double click
  27359. if (!clickInfo.hasSwiped &&
  27360. !_this._isPointerSwiping()) {
  27361. _this._previousStartingPointerTime = 0;
  27362. _this._doubleClickOccured = true;
  27363. clickInfo.doubleClick = true;
  27364. clickInfo.ignore = false;
  27365. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  27366. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  27367. }
  27368. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  27369. cb(clickInfo, _this._currentPickResult);
  27370. }
  27371. // if the two successive clicks are too far, it's just two simple clicks
  27372. else {
  27373. _this._doubleClickOccured = false;
  27374. _this._previousStartingPointerTime = _this._startingPointerTime;
  27375. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  27376. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  27377. _this._previousButtonPressed = btn;
  27378. if (Scene.ExclusiveDoubleClickMode) {
  27379. if (_this._previousDelayedSimpleClickTimeout) {
  27380. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  27381. }
  27382. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  27383. cb(clickInfo, _this._previousPickResult);
  27384. }
  27385. else {
  27386. cb(clickInfo, _this._currentPickResult);
  27387. }
  27388. }
  27389. needToIgnoreNext = true;
  27390. }
  27391. // just the first click of the double has been raised
  27392. else {
  27393. _this._doubleClickOccured = false;
  27394. _this._previousStartingPointerTime = _this._startingPointerTime;
  27395. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  27396. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  27397. _this._previousButtonPressed = btn;
  27398. }
  27399. }
  27400. }
  27401. }
  27402. if (!needToIgnoreNext) {
  27403. cb(clickInfo, _this._currentPickResult);
  27404. }
  27405. };
  27406. this._onPointerMove = function (evt) {
  27407. _this._updatePointerPosition(evt);
  27408. // PreObservable support
  27409. if (_this._checkPrePointerObservable(null, evt, evt.type === _this._wheelEventName ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE)) {
  27410. return;
  27411. }
  27412. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  27413. return;
  27414. }
  27415. if (!_this.pointerMovePredicate) {
  27416. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  27417. }
  27418. // Meshes
  27419. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  27420. _this._processPointerMove(pickResult, evt);
  27421. };
  27422. this._onPointerDown = function (evt) {
  27423. _this._totalPointersPressed++;
  27424. _this._pickedDownMesh = null;
  27425. _this._meshPickProceed = false;
  27426. _this._updatePointerPosition(evt);
  27427. if (_this.preventDefaultOnPointerDown && canvas) {
  27428. evt.preventDefault();
  27429. canvas.focus();
  27430. }
  27431. _this._startingPointerPosition.x = _this._pointerX;
  27432. _this._startingPointerPosition.y = _this._pointerY;
  27433. _this._startingPointerTime = Date.now();
  27434. // PreObservable support
  27435. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  27436. return;
  27437. }
  27438. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  27439. return;
  27440. }
  27441. _this._pointerCaptures[evt.pointerId] = true;
  27442. if (!_this.pointerDownPredicate) {
  27443. _this.pointerDownPredicate = function (mesh) {
  27444. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  27445. };
  27446. }
  27447. // Meshes
  27448. _this._pickedDownMesh = null;
  27449. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  27450. _this._processPointerDown(pickResult, evt);
  27451. };
  27452. this._onPointerUp = function (evt) {
  27453. if (_this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  27454. return; // So we need to test it the pointer down was pressed before.
  27455. }
  27456. _this._totalPointersPressed--;
  27457. _this._pickedUpMesh = null;
  27458. _this._meshPickProceed = false;
  27459. _this._updatePointerPosition(evt);
  27460. if (_this.preventDefaultOnPointerUp && canvas) {
  27461. evt.preventDefault();
  27462. canvas.focus();
  27463. }
  27464. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  27465. _this._pointerCaptures[evt.pointerId] = false;
  27466. // PreObservable support
  27467. if (_this.onPrePointerObservable.hasObservers()) {
  27468. if (!clickInfo.ignore) {
  27469. if (!clickInfo.hasSwiped) {
  27470. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  27471. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERTAP)) {
  27472. return;
  27473. }
  27474. }
  27475. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  27476. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  27477. return;
  27478. }
  27479. }
  27480. }
  27481. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  27482. return;
  27483. }
  27484. }
  27485. }
  27486. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  27487. return;
  27488. }
  27489. if (!_this.pointerUpPredicate) {
  27490. _this.pointerUpPredicate = function (mesh) {
  27491. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  27492. };
  27493. }
  27494. // Meshes
  27495. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  27496. _this._initActionManager(null, clickInfo);
  27497. }
  27498. if (!pickResult) {
  27499. pickResult = _this._currentPickResult;
  27500. }
  27501. _this._processPointerUp(pickResult, evt, clickInfo);
  27502. _this._previousPickResult = _this._currentPickResult;
  27503. });
  27504. };
  27505. this._onKeyDown = function (evt) {
  27506. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  27507. if (_this.onPreKeyboardObservable.hasObservers()) {
  27508. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  27509. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  27510. if (pi.skipOnPointerObservable) {
  27511. return;
  27512. }
  27513. }
  27514. if (_this.onKeyboardObservable.hasObservers()) {
  27515. var pi = new BABYLON.KeyboardInfo(type, evt);
  27516. _this.onKeyboardObservable.notifyObservers(pi, type);
  27517. }
  27518. if (_this.actionManager) {
  27519. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  27520. }
  27521. };
  27522. this._onKeyUp = function (evt) {
  27523. var type = BABYLON.KeyboardEventTypes.KEYUP;
  27524. if (_this.onPreKeyboardObservable.hasObservers()) {
  27525. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  27526. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  27527. if (pi.skipOnPointerObservable) {
  27528. return;
  27529. }
  27530. }
  27531. if (_this.onKeyboardObservable.hasObservers()) {
  27532. var pi = new BABYLON.KeyboardInfo(type, evt);
  27533. _this.onKeyboardObservable.notifyObservers(pi, type);
  27534. }
  27535. if (_this.actionManager) {
  27536. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  27537. }
  27538. };
  27539. var engine = this.getEngine();
  27540. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  27541. if (!canvas) {
  27542. return;
  27543. }
  27544. canvas.addEventListener("keydown", _this._onKeyDown, false);
  27545. canvas.addEventListener("keyup", _this._onKeyUp, false);
  27546. });
  27547. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  27548. if (!canvas) {
  27549. return;
  27550. }
  27551. canvas.removeEventListener("keydown", _this._onKeyDown);
  27552. canvas.removeEventListener("keyup", _this._onKeyUp);
  27553. });
  27554. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  27555. var canvas = this._engine.getRenderingCanvas();
  27556. if (!canvas) {
  27557. return;
  27558. }
  27559. if (attachMove) {
  27560. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  27561. // Wheel
  27562. this._wheelEventName = "onwheel" in document.createElement("div") ? "wheel" : // Modern browsers support "wheel"
  27563. document.onmousewheel !== undefined ? "mousewheel" : // Webkit and IE support at least "mousewheel"
  27564. "DOMMouseScroll"; // let's assume that remaining browsers are older Firefox
  27565. canvas.addEventListener(this._wheelEventName, this._onPointerMove, false);
  27566. }
  27567. if (attachDown) {
  27568. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  27569. }
  27570. if (attachUp) {
  27571. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  27572. }
  27573. canvas.tabIndex = 1;
  27574. };
  27575. /** Detaches all event handlers*/
  27576. Scene.prototype.detachControl = function () {
  27577. var engine = this.getEngine();
  27578. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  27579. var canvas = engine.getRenderingCanvas();
  27580. if (!canvas) {
  27581. return;
  27582. }
  27583. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  27584. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  27585. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  27586. if (this._onCanvasBlurObserver) {
  27587. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  27588. }
  27589. if (this._onCanvasFocusObserver) {
  27590. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  27591. }
  27592. // Wheel
  27593. canvas.removeEventListener(this._wheelEventName, this._onPointerMove);
  27594. // Keyboard
  27595. canvas.removeEventListener("keydown", this._onKeyDown);
  27596. canvas.removeEventListener("keyup", this._onKeyUp);
  27597. // Observables
  27598. this.onKeyboardObservable.clear();
  27599. this.onPreKeyboardObservable.clear();
  27600. this.onPointerObservable.clear();
  27601. this.onPrePointerObservable.clear();
  27602. };
  27603. /**
  27604. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  27605. * Delay loaded resources are not taking in account
  27606. * @return true if all required resources are ready
  27607. */
  27608. Scene.prototype.isReady = function () {
  27609. if (this._isDisposed) {
  27610. return false;
  27611. }
  27612. var index;
  27613. var engine = this.getEngine();
  27614. // Effects
  27615. if (!engine.areAllEffectsReady()) {
  27616. return false;
  27617. }
  27618. // Pending data
  27619. if (this._pendingData.length > 0) {
  27620. return false;
  27621. }
  27622. // Meshes
  27623. for (index = 0; index < this.meshes.length; index++) {
  27624. var mesh = this.meshes[index];
  27625. if (!mesh.isEnabled()) {
  27626. continue;
  27627. }
  27628. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  27629. continue;
  27630. }
  27631. if (!mesh.isReady(true)) {
  27632. return false;
  27633. }
  27634. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || mesh.getClassName() === "InstancedLinesMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  27635. // Is Ready For Mesh
  27636. for (var _i = 0, _a = this._isReadyForMeshStage; _i < _a.length; _i++) {
  27637. var step = _a[_i];
  27638. if (!step.action(mesh, hardwareInstancedRendering)) {
  27639. return false;
  27640. }
  27641. }
  27642. }
  27643. // Geometries
  27644. for (index = 0; index < this.geometries.length; index++) {
  27645. var geometry = this.geometries[index];
  27646. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  27647. return false;
  27648. }
  27649. }
  27650. // Post-processes
  27651. if (this.activeCameras && this.activeCameras.length > 0) {
  27652. for (var _b = 0, _c = this.activeCameras; _b < _c.length; _b++) {
  27653. var camera = _c[_b];
  27654. if (!camera.isReady(true)) {
  27655. return false;
  27656. }
  27657. }
  27658. }
  27659. else if (this.activeCamera) {
  27660. if (!this.activeCamera.isReady(true)) {
  27661. return false;
  27662. }
  27663. }
  27664. // Particles
  27665. for (var _d = 0, _e = this.particleSystems; _d < _e.length; _d++) {
  27666. var particleSystem = _e[_d];
  27667. if (!particleSystem.isReady()) {
  27668. return false;
  27669. }
  27670. }
  27671. return true;
  27672. };
  27673. /** Resets all cached information relative to material (including effect and visibility) */
  27674. Scene.prototype.resetCachedMaterial = function () {
  27675. this._cachedMaterial = null;
  27676. this._cachedEffect = null;
  27677. this._cachedVisibility = null;
  27678. };
  27679. /**
  27680. * Registers a function to be called before every frame render
  27681. * @param func defines the function to register
  27682. */
  27683. Scene.prototype.registerBeforeRender = function (func) {
  27684. this.onBeforeRenderObservable.add(func);
  27685. };
  27686. /**
  27687. * Unregisters a function called before every frame render
  27688. * @param func defines the function to unregister
  27689. */
  27690. Scene.prototype.unregisterBeforeRender = function (func) {
  27691. this.onBeforeRenderObservable.removeCallback(func);
  27692. };
  27693. /**
  27694. * Registers a function to be called after every frame render
  27695. * @param func defines the function to register
  27696. */
  27697. Scene.prototype.registerAfterRender = function (func) {
  27698. this.onAfterRenderObservable.add(func);
  27699. };
  27700. /**
  27701. * Unregisters a function called after every frame render
  27702. * @param func defines the function to unregister
  27703. */
  27704. Scene.prototype.unregisterAfterRender = function (func) {
  27705. this.onAfterRenderObservable.removeCallback(func);
  27706. };
  27707. Scene.prototype._executeOnceBeforeRender = function (func) {
  27708. var _this = this;
  27709. var execFunc = function () {
  27710. func();
  27711. setTimeout(function () {
  27712. _this.unregisterBeforeRender(execFunc);
  27713. });
  27714. };
  27715. this.registerBeforeRender(execFunc);
  27716. };
  27717. /**
  27718. * The provided function will run before render once and will be disposed afterwards.
  27719. * A timeout delay can be provided so that the function will be executed in N ms.
  27720. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  27721. * @param func The function to be executed.
  27722. * @param timeout optional delay in ms
  27723. */
  27724. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  27725. var _this = this;
  27726. if (timeout !== undefined) {
  27727. setTimeout(function () {
  27728. _this._executeOnceBeforeRender(func);
  27729. }, timeout);
  27730. }
  27731. else {
  27732. this._executeOnceBeforeRender(func);
  27733. }
  27734. };
  27735. /** @hidden */
  27736. Scene.prototype._addPendingData = function (data) {
  27737. this._pendingData.push(data);
  27738. };
  27739. /** @hidden */
  27740. Scene.prototype._removePendingData = function (data) {
  27741. var wasLoading = this.isLoading;
  27742. var index = this._pendingData.indexOf(data);
  27743. if (index !== -1) {
  27744. this._pendingData.splice(index, 1);
  27745. }
  27746. if (wasLoading && !this.isLoading) {
  27747. this.onDataLoadedObservable.notifyObservers(this);
  27748. }
  27749. };
  27750. /**
  27751. * Returns the number of items waiting to be loaded
  27752. * @returns the number of items waiting to be loaded
  27753. */
  27754. Scene.prototype.getWaitingItemsCount = function () {
  27755. return this._pendingData.length;
  27756. };
  27757. Object.defineProperty(Scene.prototype, "isLoading", {
  27758. /**
  27759. * Returns a boolean indicating if the scene is still loading data
  27760. */
  27761. get: function () {
  27762. return this._pendingData.length > 0;
  27763. },
  27764. enumerable: true,
  27765. configurable: true
  27766. });
  27767. /**
  27768. * Registers a function to be executed when the scene is ready
  27769. * @param {Function} func - the function to be executed
  27770. */
  27771. Scene.prototype.executeWhenReady = function (func) {
  27772. var _this = this;
  27773. this.onReadyObservable.add(func);
  27774. if (this._executeWhenReadyTimeoutId !== -1) {
  27775. return;
  27776. }
  27777. this._executeWhenReadyTimeoutId = setTimeout(function () {
  27778. _this._checkIsReady();
  27779. }, 150);
  27780. };
  27781. /**
  27782. * Returns a promise that resolves when the scene is ready
  27783. * @returns A promise that resolves when the scene is ready
  27784. */
  27785. Scene.prototype.whenReadyAsync = function () {
  27786. var _this = this;
  27787. return new Promise(function (resolve) {
  27788. _this.executeWhenReady(function () {
  27789. resolve();
  27790. });
  27791. });
  27792. };
  27793. /** @hidden */
  27794. Scene.prototype._checkIsReady = function () {
  27795. var _this = this;
  27796. this._registerTransientComponents();
  27797. if (this.isReady()) {
  27798. this.onReadyObservable.notifyObservers(this);
  27799. this.onReadyObservable.clear();
  27800. this._executeWhenReadyTimeoutId = -1;
  27801. return;
  27802. }
  27803. this._executeWhenReadyTimeoutId = setTimeout(function () {
  27804. _this._checkIsReady();
  27805. }, 150);
  27806. };
  27807. // Animations
  27808. /**
  27809. * Will start the animation sequence of a given target
  27810. * @param target defines the target
  27811. * @param from defines from which frame should animation start
  27812. * @param to defines until which frame should animation run.
  27813. * @param weight defines the weight to apply to the animation (1.0 by default)
  27814. * @param loop defines if the animation loops
  27815. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  27816. * @param onAnimationEnd defines the function to be executed when the animation ends
  27817. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  27818. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  27819. * @param onAnimationLoop defines the callback to call when an animation loops
  27820. * @returns the animatable object created for this animation
  27821. */
  27822. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable, targetMask, onAnimationLoop) {
  27823. if (weight === void 0) { weight = 1.0; }
  27824. if (speedRatio === void 0) { speedRatio = 1.0; }
  27825. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false, targetMask, onAnimationLoop);
  27826. returnedAnimatable.weight = weight;
  27827. return returnedAnimatable;
  27828. };
  27829. /**
  27830. * Will start the animation sequence of a given target
  27831. * @param target defines the target
  27832. * @param from defines from which frame should animation start
  27833. * @param to defines until which frame should animation run.
  27834. * @param loop defines if the animation loops
  27835. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  27836. * @param onAnimationEnd defines the function to be executed when the animation ends
  27837. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  27838. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  27839. * @param targetMask defines if the target should be animate if animations are present (this is called recursively on descendant animatables regardless of return value)
  27840. * @param onAnimationLoop defines the callback to call when an animation loops
  27841. * @returns the animatable object created for this animation
  27842. */
  27843. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask, onAnimationLoop) {
  27844. if (speedRatio === void 0) { speedRatio = 1.0; }
  27845. if (stopCurrent === void 0) { stopCurrent = true; }
  27846. if (from > to && speedRatio > 0) {
  27847. speedRatio *= -1;
  27848. }
  27849. if (stopCurrent) {
  27850. this.stopAnimation(target, undefined, targetMask);
  27851. }
  27852. if (!animatable) {
  27853. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, undefined, onAnimationLoop);
  27854. }
  27855. var shouldRunTargetAnimations = targetMask ? targetMask(target) : true;
  27856. // Local animations
  27857. if (target.animations && shouldRunTargetAnimations) {
  27858. animatable.appendAnimations(target, target.animations);
  27859. }
  27860. // Children animations
  27861. if (target.getAnimatables) {
  27862. var animatables = target.getAnimatables();
  27863. for (var index = 0; index < animatables.length; index++) {
  27864. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask, onAnimationLoop);
  27865. }
  27866. }
  27867. animatable.reset();
  27868. return animatable;
  27869. };
  27870. /**
  27871. * Will start the animation sequence of a given target and its hierarchy
  27872. * @param target defines the target
  27873. * @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.
  27874. * @param from defines from which frame should animation start
  27875. * @param to defines until which frame should animation run.
  27876. * @param loop defines if the animation loops
  27877. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  27878. * @param onAnimationEnd defines the function to be executed when the animation ends
  27879. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  27880. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  27881. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  27882. * @param onAnimationLoop defines the callback to call when an animation loops
  27883. * @returns the list of created animatables
  27884. */
  27885. Scene.prototype.beginHierarchyAnimation = function (target, directDescendantsOnly, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask, onAnimationLoop) {
  27886. if (speedRatio === void 0) { speedRatio = 1.0; }
  27887. if (stopCurrent === void 0) { stopCurrent = true; }
  27888. var children = target.getDescendants(directDescendantsOnly);
  27889. var result = [];
  27890. result.push(this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask));
  27891. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  27892. var child = children_1[_i];
  27893. result.push(this.beginAnimation(child, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask));
  27894. }
  27895. return result;
  27896. };
  27897. /**
  27898. * Begin a new animation on a given node
  27899. * @param target defines the target where the animation will take place
  27900. * @param animations defines the list of animations to start
  27901. * @param from defines the initial value
  27902. * @param to defines the final value
  27903. * @param loop defines if you want animation to loop (off by default)
  27904. * @param speedRatio defines the speed ratio to apply to all animations
  27905. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  27906. * @param onAnimationLoop defines the callback to call when an animation loops
  27907. * @returns the list of created animatables
  27908. */
  27909. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd, onAnimationLoop) {
  27910. if (speedRatio === undefined) {
  27911. speedRatio = 1.0;
  27912. }
  27913. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations, onAnimationLoop);
  27914. return animatable;
  27915. };
  27916. /**
  27917. * Begin a new animation on a given node and its hierarchy
  27918. * @param target defines the root node where the animation will take place
  27919. * @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.
  27920. * @param animations defines the list of animations to start
  27921. * @param from defines the initial value
  27922. * @param to defines the final value
  27923. * @param loop defines if you want animation to loop (off by default)
  27924. * @param speedRatio defines the speed ratio to apply to all animations
  27925. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  27926. * @param onAnimationLoop defines the callback to call when an animation loops
  27927. * @returns the list of animatables created for all nodes
  27928. */
  27929. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd, onAnimationLoop) {
  27930. var children = target.getDescendants(directDescendantsOnly);
  27931. var result = [];
  27932. result.push(this.beginDirectAnimation(target, animations, from, to, loop, speedRatio, onAnimationEnd, onAnimationLoop));
  27933. for (var _i = 0, children_2 = children; _i < children_2.length; _i++) {
  27934. var child = children_2[_i];
  27935. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd, onAnimationLoop));
  27936. }
  27937. return result;
  27938. };
  27939. /**
  27940. * Gets the animatable associated with a specific target
  27941. * @param target defines the target of the animatable
  27942. * @returns the required animatable if found
  27943. */
  27944. Scene.prototype.getAnimatableByTarget = function (target) {
  27945. for (var index = 0; index < this._activeAnimatables.length; index++) {
  27946. if (this._activeAnimatables[index].target === target) {
  27947. return this._activeAnimatables[index];
  27948. }
  27949. }
  27950. return null;
  27951. };
  27952. /**
  27953. * Gets all animatables associated with a given target
  27954. * @param target defines the target to look animatables for
  27955. * @returns an array of Animatables
  27956. */
  27957. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  27958. var result = [];
  27959. for (var index = 0; index < this._activeAnimatables.length; index++) {
  27960. if (this._activeAnimatables[index].target === target) {
  27961. result.push(this._activeAnimatables[index]);
  27962. }
  27963. }
  27964. return result;
  27965. };
  27966. Object.defineProperty(Scene.prototype, "animatables", {
  27967. /**
  27968. * Gets all animatable attached to the scene
  27969. */
  27970. get: function () {
  27971. return this._activeAnimatables;
  27972. },
  27973. enumerable: true,
  27974. configurable: true
  27975. });
  27976. /**
  27977. * Will stop the animation of the given target
  27978. * @param target - the target
  27979. * @param animationName - the name of the animation to stop (all animations will be stopped if both this and targetMask are empty)
  27980. * @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)
  27981. */
  27982. Scene.prototype.stopAnimation = function (target, animationName, targetMask) {
  27983. var animatables = this.getAllAnimatablesByTarget(target);
  27984. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  27985. var animatable = animatables_1[_i];
  27986. animatable.stop(animationName, targetMask);
  27987. }
  27988. };
  27989. /**
  27990. * Stops and removes all animations that have been applied to the scene
  27991. */
  27992. Scene.prototype.stopAllAnimations = function () {
  27993. if (this._activeAnimatables) {
  27994. for (var i = 0; i < this._activeAnimatables.length; i++) {
  27995. this._activeAnimatables[i].stop();
  27996. }
  27997. this._activeAnimatables = [];
  27998. }
  27999. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  28000. var group = _a[_i];
  28001. group.stop();
  28002. }
  28003. };
  28004. Scene.prototype._animate = function () {
  28005. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  28006. return;
  28007. }
  28008. // Getting time
  28009. var now = BABYLON.Tools.Now;
  28010. if (!this._animationTimeLast) {
  28011. if (this._pendingData.length > 0) {
  28012. return;
  28013. }
  28014. this._animationTimeLast = now;
  28015. }
  28016. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  28017. this._animationTime += deltaTime;
  28018. this._animationTimeLast = now;
  28019. for (var index = 0; index < this._activeAnimatables.length; index++) {
  28020. this._activeAnimatables[index]._animate(this._animationTime);
  28021. }
  28022. // Late animation bindings
  28023. this._processLateAnimationBindings();
  28024. };
  28025. /** @hidden */
  28026. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation, originalValue) {
  28027. var target = runtimeAnimation.target;
  28028. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  28029. if (!target._lateAnimationHolders) {
  28030. target._lateAnimationHolders = {};
  28031. }
  28032. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  28033. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  28034. totalWeight: 0,
  28035. animations: [],
  28036. originalValue: originalValue
  28037. };
  28038. }
  28039. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  28040. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  28041. };
  28042. Scene.prototype._processLateAnimationBindingsForMatrices = function (holder) {
  28043. var normalizer = 1.0;
  28044. var finalPosition = BABYLON.Tmp.Vector3[0];
  28045. var finalScaling = BABYLON.Tmp.Vector3[1];
  28046. var finalQuaternion = BABYLON.Tmp.Quaternion[0];
  28047. var startIndex = 0;
  28048. var originalAnimation = holder.animations[0];
  28049. var originalValue = holder.originalValue;
  28050. var scale = 1;
  28051. if (holder.totalWeight < 1.0) {
  28052. // We need to mix the original value in
  28053. originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
  28054. scale = 1.0 - holder.totalWeight;
  28055. }
  28056. else {
  28057. startIndex = 1;
  28058. // We need to normalize the weights
  28059. normalizer = holder.totalWeight;
  28060. originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
  28061. scale = originalAnimation.weight / normalizer;
  28062. if (scale == 1) {
  28063. return originalAnimation.currentValue;
  28064. }
  28065. }
  28066. finalScaling.scaleInPlace(scale);
  28067. finalPosition.scaleInPlace(scale);
  28068. finalQuaternion.scaleInPlace(scale);
  28069. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  28070. var runtimeAnimation = holder.animations[animIndex];
  28071. var scale = runtimeAnimation.weight / normalizer;
  28072. var currentPosition = BABYLON.Tmp.Vector3[2];
  28073. var currentScaling = BABYLON.Tmp.Vector3[3];
  28074. var currentQuaternion = BABYLON.Tmp.Quaternion[1];
  28075. runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
  28076. currentScaling.scaleAndAddToRef(scale, finalScaling);
  28077. currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
  28078. currentPosition.scaleAndAddToRef(scale, finalPosition);
  28079. }
  28080. BABYLON.Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
  28081. return originalAnimation._workValue;
  28082. };
  28083. Scene.prototype._processLateAnimationBindingsForQuaternions = function (holder, refQuaternion) {
  28084. var originalAnimation = holder.animations[0];
  28085. var originalValue = holder.originalValue;
  28086. if (holder.animations.length === 1) {
  28087. BABYLON.Quaternion.SlerpToRef(originalValue, originalAnimation.currentValue, Math.min(1.0, holder.totalWeight), refQuaternion);
  28088. return refQuaternion;
  28089. }
  28090. var normalizer = 1.0;
  28091. var quaternions;
  28092. var weights;
  28093. if (holder.totalWeight < 1.0) {
  28094. var scale = 1.0 - holder.totalWeight;
  28095. quaternions = [];
  28096. weights = [];
  28097. quaternions.push(originalValue);
  28098. weights.push(scale);
  28099. }
  28100. else {
  28101. if (holder.animations.length === 2) { // Slerp as soon as we can
  28102. BABYLON.Quaternion.SlerpToRef(holder.animations[0].currentValue, holder.animations[1].currentValue, holder.animations[1].weight / holder.totalWeight, refQuaternion);
  28103. return refQuaternion;
  28104. }
  28105. quaternions = [];
  28106. weights = [];
  28107. normalizer = holder.totalWeight;
  28108. }
  28109. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  28110. var runtimeAnimation = holder.animations[animIndex];
  28111. quaternions.push(runtimeAnimation.currentValue);
  28112. weights.push(runtimeAnimation.weight / normalizer);
  28113. }
  28114. // https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions
  28115. var cumulativeAmount = 0;
  28116. var cumulativeQuaternion = null;
  28117. for (var index = 0; index < quaternions.length;) {
  28118. if (!cumulativeQuaternion) {
  28119. BABYLON.Quaternion.SlerpToRef(quaternions[index], quaternions[index + 1], weights[index + 1] / (weights[index] + weights[index + 1]), refQuaternion);
  28120. cumulativeQuaternion = refQuaternion;
  28121. cumulativeAmount = weights[index] + weights[index + 1];
  28122. index += 2;
  28123. continue;
  28124. }
  28125. cumulativeAmount += weights[index];
  28126. BABYLON.Quaternion.SlerpToRef(cumulativeQuaternion, quaternions[index], weights[index] / cumulativeAmount, cumulativeQuaternion);
  28127. index++;
  28128. }
  28129. return cumulativeQuaternion;
  28130. };
  28131. Scene.prototype._processLateAnimationBindings = function () {
  28132. if (!this._registeredForLateAnimationBindings.length) {
  28133. return;
  28134. }
  28135. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  28136. var target = this._registeredForLateAnimationBindings.data[index];
  28137. for (var path in target._lateAnimationHolders) {
  28138. var holder = target._lateAnimationHolders[path];
  28139. var originalAnimation = holder.animations[0];
  28140. var originalValue = holder.originalValue;
  28141. var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  28142. var finalValue = target[path];
  28143. if (matrixDecomposeMode) {
  28144. finalValue = this._processLateAnimationBindingsForMatrices(holder);
  28145. }
  28146. else {
  28147. var quaternionMode = originalValue.w !== undefined;
  28148. if (quaternionMode) {
  28149. finalValue = this._processLateAnimationBindingsForQuaternions(holder, finalValue || BABYLON.Quaternion.Identity());
  28150. }
  28151. else {
  28152. var startIndex = 0;
  28153. var normalizer = 1.0;
  28154. if (holder.totalWeight < 1.0) {
  28155. // We need to mix the original value in
  28156. if (originalValue.scale) {
  28157. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  28158. }
  28159. else {
  28160. finalValue = originalValue * (1.0 - holder.totalWeight);
  28161. }
  28162. }
  28163. else {
  28164. // We need to normalize the weights
  28165. normalizer = holder.totalWeight;
  28166. var scale_1 = originalAnimation.weight / normalizer;
  28167. if (scale_1 !== 1) {
  28168. if (originalAnimation.currentValue.scale) {
  28169. finalValue = originalAnimation.currentValue.scale(scale_1);
  28170. }
  28171. else {
  28172. finalValue = originalAnimation.currentValue * scale_1;
  28173. }
  28174. }
  28175. else {
  28176. finalValue = originalAnimation.currentValue;
  28177. }
  28178. startIndex = 1;
  28179. }
  28180. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  28181. var runtimeAnimation = holder.animations[animIndex];
  28182. var scale = runtimeAnimation.weight / normalizer;
  28183. if (runtimeAnimation.currentValue.scaleAndAddToRef) {
  28184. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  28185. }
  28186. else {
  28187. finalValue += runtimeAnimation.currentValue * scale;
  28188. }
  28189. }
  28190. }
  28191. }
  28192. target[path] = finalValue;
  28193. }
  28194. target._lateAnimationHolders = {};
  28195. }
  28196. this._registeredForLateAnimationBindings.reset();
  28197. };
  28198. // Matrix
  28199. /** @hidden */
  28200. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  28201. this._useAlternateCameraConfiguration = active;
  28202. };
  28203. /**
  28204. * Gets the current view matrix
  28205. * @returns a Matrix
  28206. */
  28207. Scene.prototype.getViewMatrix = function () {
  28208. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  28209. };
  28210. /**
  28211. * Gets the current projection matrix
  28212. * @returns a Matrix
  28213. */
  28214. Scene.prototype.getProjectionMatrix = function () {
  28215. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  28216. };
  28217. /**
  28218. * Gets the current transform matrix
  28219. * @returns a Matrix made of View * Projection
  28220. */
  28221. Scene.prototype.getTransformMatrix = function () {
  28222. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  28223. };
  28224. /**
  28225. * Sets the current transform matrix
  28226. * @param view defines the View matrix to use
  28227. * @param projection defines the Projection matrix to use
  28228. */
  28229. Scene.prototype.setTransformMatrix = function (view, projection) {
  28230. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  28231. return;
  28232. }
  28233. this._viewUpdateFlag = view.updateFlag;
  28234. this._projectionUpdateFlag = projection.updateFlag;
  28235. this._viewMatrix = view;
  28236. this._projectionMatrix = projection;
  28237. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  28238. // Update frustum
  28239. if (!this._frustumPlanes) {
  28240. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  28241. }
  28242. else {
  28243. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  28244. }
  28245. if (this.activeCamera && this.activeCamera._alternateCamera) {
  28246. var otherCamera = this.activeCamera._alternateCamera;
  28247. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  28248. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  28249. }
  28250. if (this._sceneUbo.useUbo) {
  28251. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  28252. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  28253. this._sceneUbo.update();
  28254. }
  28255. };
  28256. /** @hidden */
  28257. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  28258. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  28259. return;
  28260. }
  28261. this._alternateViewUpdateFlag = view.updateFlag;
  28262. this._alternateProjectionUpdateFlag = projection.updateFlag;
  28263. this._alternateViewMatrix = view;
  28264. this._alternateProjectionMatrix = projection;
  28265. if (!this._alternateTransformMatrix) {
  28266. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  28267. }
  28268. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  28269. if (!this._alternateSceneUbo) {
  28270. this._createAlternateUbo();
  28271. }
  28272. if (this._alternateSceneUbo.useUbo) {
  28273. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  28274. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  28275. this._alternateSceneUbo.update();
  28276. }
  28277. };
  28278. /**
  28279. * Gets the uniform buffer used to store scene data
  28280. * @returns a UniformBuffer
  28281. */
  28282. Scene.prototype.getSceneUniformBuffer = function () {
  28283. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  28284. };
  28285. /**
  28286. * Gets an unique (relatively to the current scene) Id
  28287. * @returns an unique number for the scene
  28288. */
  28289. Scene.prototype.getUniqueId = function () {
  28290. var result = Scene._uniqueIdCounter;
  28291. Scene._uniqueIdCounter++;
  28292. return result;
  28293. };
  28294. /**
  28295. * Add a mesh to the list of scene's meshes
  28296. * @param newMesh defines the mesh to add
  28297. * @param recursive if all child meshes should also be added to the scene
  28298. */
  28299. Scene.prototype.addMesh = function (newMesh, recursive) {
  28300. var _this = this;
  28301. if (recursive === void 0) { recursive = false; }
  28302. this.meshes.push(newMesh);
  28303. //notify the collision coordinator
  28304. if (this.collisionCoordinator) {
  28305. this.collisionCoordinator.onMeshAdded(newMesh);
  28306. }
  28307. newMesh._resyncLightSources();
  28308. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  28309. if (recursive) {
  28310. newMesh.getChildMeshes().forEach(function (m) {
  28311. _this.addMesh(m);
  28312. });
  28313. }
  28314. };
  28315. /**
  28316. * Remove a mesh for the list of scene's meshes
  28317. * @param toRemove defines the mesh to remove
  28318. * @param recursive if all child meshes should also be removed from the scene
  28319. * @returns the index where the mesh was in the mesh list
  28320. */
  28321. Scene.prototype.removeMesh = function (toRemove, recursive) {
  28322. var _this = this;
  28323. if (recursive === void 0) { recursive = false; }
  28324. var index = this.meshes.indexOf(toRemove);
  28325. if (index !== -1) {
  28326. // Remove from the scene if mesh found
  28327. this.meshes[index] = this.meshes[this.meshes.length - 1];
  28328. this.meshes.pop();
  28329. }
  28330. this.onMeshRemovedObservable.notifyObservers(toRemove);
  28331. if (recursive) {
  28332. toRemove.getChildMeshes().forEach(function (m) {
  28333. _this.removeMesh(m);
  28334. });
  28335. }
  28336. return index;
  28337. };
  28338. /**
  28339. * Add a transform node to the list of scene's transform nodes
  28340. * @param newTransformNode defines the transform node to add
  28341. */
  28342. Scene.prototype.addTransformNode = function (newTransformNode) {
  28343. newTransformNode._indexInSceneTransformNodesArray = this.transformNodes.length;
  28344. this.transformNodes.push(newTransformNode);
  28345. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  28346. };
  28347. /**
  28348. * Remove a transform node for the list of scene's transform nodes
  28349. * @param toRemove defines the transform node to remove
  28350. * @returns the index where the transform node was in the transform node list
  28351. */
  28352. Scene.prototype.removeTransformNode = function (toRemove) {
  28353. var index = toRemove._indexInSceneTransformNodesArray;
  28354. if (index !== -1) {
  28355. if (index !== this.transformNodes.length - 1) {
  28356. var lastNode = this.transformNodes[this.transformNodes.length - 1];
  28357. this.transformNodes[index] = lastNode;
  28358. lastNode._indexInSceneTransformNodesArray = index;
  28359. }
  28360. toRemove._indexInSceneTransformNodesArray = -1;
  28361. this.transformNodes.pop();
  28362. }
  28363. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  28364. return index;
  28365. };
  28366. /**
  28367. * Remove a skeleton for the list of scene's skeletons
  28368. * @param toRemove defines the skeleton to remove
  28369. * @returns the index where the skeleton was in the skeleton list
  28370. */
  28371. Scene.prototype.removeSkeleton = function (toRemove) {
  28372. var index = this.skeletons.indexOf(toRemove);
  28373. if (index !== -1) {
  28374. // Remove from the scene if found
  28375. this.skeletons.splice(index, 1);
  28376. }
  28377. return index;
  28378. };
  28379. /**
  28380. * Remove a morph target for the list of scene's morph targets
  28381. * @param toRemove defines the morph target to remove
  28382. * @returns the index where the morph target was in the morph target list
  28383. */
  28384. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  28385. var index = this.morphTargetManagers.indexOf(toRemove);
  28386. if (index !== -1) {
  28387. // Remove from the scene if found
  28388. this.morphTargetManagers.splice(index, 1);
  28389. }
  28390. return index;
  28391. };
  28392. /**
  28393. * Remove a light for the list of scene's lights
  28394. * @param toRemove defines the light to remove
  28395. * @returns the index where the light was in the light list
  28396. */
  28397. Scene.prototype.removeLight = function (toRemove) {
  28398. var index = this.lights.indexOf(toRemove);
  28399. if (index !== -1) {
  28400. // Remove from meshes
  28401. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  28402. var mesh = _a[_i];
  28403. mesh._removeLightSource(toRemove);
  28404. }
  28405. // Remove from the scene if mesh found
  28406. this.lights.splice(index, 1);
  28407. this.sortLightsByPriority();
  28408. }
  28409. this.onLightRemovedObservable.notifyObservers(toRemove);
  28410. return index;
  28411. };
  28412. /**
  28413. * Remove a camera for the list of scene's cameras
  28414. * @param toRemove defines the camera to remove
  28415. * @returns the index where the camera was in the camera list
  28416. */
  28417. Scene.prototype.removeCamera = function (toRemove) {
  28418. var index = this.cameras.indexOf(toRemove);
  28419. if (index !== -1) {
  28420. // Remove from the scene if mesh found
  28421. this.cameras.splice(index, 1);
  28422. }
  28423. // Remove from activeCameras
  28424. var index2 = this.activeCameras.indexOf(toRemove);
  28425. if (index2 !== -1) {
  28426. // Remove from the scene if mesh found
  28427. this.activeCameras.splice(index2, 1);
  28428. }
  28429. // Reset the activeCamera
  28430. if (this.activeCamera === toRemove) {
  28431. if (this.cameras.length > 0) {
  28432. this.activeCamera = this.cameras[0];
  28433. }
  28434. else {
  28435. this.activeCamera = null;
  28436. }
  28437. }
  28438. this.onCameraRemovedObservable.notifyObservers(toRemove);
  28439. return index;
  28440. };
  28441. /**
  28442. * Remove a particle system for the list of scene's particle systems
  28443. * @param toRemove defines the particle system to remove
  28444. * @returns the index where the particle system was in the particle system list
  28445. */
  28446. Scene.prototype.removeParticleSystem = function (toRemove) {
  28447. var index = this.particleSystems.indexOf(toRemove);
  28448. if (index !== -1) {
  28449. this.particleSystems.splice(index, 1);
  28450. }
  28451. return index;
  28452. };
  28453. /**
  28454. * Remove a animation for the list of scene's animations
  28455. * @param toRemove defines the animation to remove
  28456. * @returns the index where the animation was in the animation list
  28457. */
  28458. Scene.prototype.removeAnimation = function (toRemove) {
  28459. var index = this.animations.indexOf(toRemove);
  28460. if (index !== -1) {
  28461. this.animations.splice(index, 1);
  28462. }
  28463. return index;
  28464. };
  28465. /**
  28466. * Removes the given animation group from this scene.
  28467. * @param toRemove The animation group to remove
  28468. * @returns The index of the removed animation group
  28469. */
  28470. Scene.prototype.removeAnimationGroup = function (toRemove) {
  28471. var index = this.animationGroups.indexOf(toRemove);
  28472. if (index !== -1) {
  28473. this.animationGroups.splice(index, 1);
  28474. }
  28475. return index;
  28476. };
  28477. /**
  28478. * Removes the given multi-material from this scene.
  28479. * @param toRemove The multi-material to remove
  28480. * @returns The index of the removed multi-material
  28481. */
  28482. Scene.prototype.removeMultiMaterial = function (toRemove) {
  28483. var index = this.multiMaterials.indexOf(toRemove);
  28484. if (index !== -1) {
  28485. this.multiMaterials.splice(index, 1);
  28486. }
  28487. return index;
  28488. };
  28489. /**
  28490. * Removes the given material from this scene.
  28491. * @param toRemove The material to remove
  28492. * @returns The index of the removed material
  28493. */
  28494. Scene.prototype.removeMaterial = function (toRemove) {
  28495. var index = toRemove._indexInSceneMaterialArray;
  28496. if (index !== -1) {
  28497. if (index !== this.materials.length - 1) {
  28498. var lastMaterial = this.materials[this.materials.length - 1];
  28499. this.materials[index] = lastMaterial;
  28500. lastMaterial._indexInSceneMaterialArray = index;
  28501. }
  28502. toRemove._indexInSceneMaterialArray = -1;
  28503. this.materials.pop();
  28504. }
  28505. this.onMaterialRemovedObservable.notifyObservers(toRemove);
  28506. return index;
  28507. };
  28508. /**
  28509. * Removes the given action manager from this scene.
  28510. * @param toRemove The action manager to remove
  28511. * @returns The index of the removed action manager
  28512. */
  28513. Scene.prototype.removeActionManager = function (toRemove) {
  28514. var index = this.actionManagers.indexOf(toRemove);
  28515. if (index !== -1) {
  28516. this.actionManagers.splice(index, 1);
  28517. }
  28518. return index;
  28519. };
  28520. /**
  28521. * Removes the given texture from this scene.
  28522. * @param toRemove The texture to remove
  28523. * @returns The index of the removed texture
  28524. */
  28525. Scene.prototype.removeTexture = function (toRemove) {
  28526. var index = this.textures.indexOf(toRemove);
  28527. if (index !== -1) {
  28528. this.textures.splice(index, 1);
  28529. }
  28530. this.onTextureRemovedObservable.notifyObservers(toRemove);
  28531. return index;
  28532. };
  28533. /**
  28534. * Adds the given light to this scene
  28535. * @param newLight The light to add
  28536. */
  28537. Scene.prototype.addLight = function (newLight) {
  28538. this.lights.push(newLight);
  28539. this.sortLightsByPriority();
  28540. // Add light to all meshes (To support if the light is removed and then readded)
  28541. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  28542. var mesh = _a[_i];
  28543. if (mesh._lightSources.indexOf(newLight) === -1) {
  28544. mesh._lightSources.push(newLight);
  28545. mesh._resyncLightSources();
  28546. }
  28547. }
  28548. this.onNewLightAddedObservable.notifyObservers(newLight);
  28549. };
  28550. /**
  28551. * Sorts the list list based on light priorities
  28552. */
  28553. Scene.prototype.sortLightsByPriority = function () {
  28554. if (this.requireLightSorting) {
  28555. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  28556. }
  28557. };
  28558. /**
  28559. * Adds the given camera to this scene
  28560. * @param newCamera The camera to add
  28561. */
  28562. Scene.prototype.addCamera = function (newCamera) {
  28563. this.cameras.push(newCamera);
  28564. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  28565. };
  28566. /**
  28567. * Adds the given skeleton to this scene
  28568. * @param newSkeleton The skeleton to add
  28569. */
  28570. Scene.prototype.addSkeleton = function (newSkeleton) {
  28571. this.skeletons.push(newSkeleton);
  28572. };
  28573. /**
  28574. * Adds the given particle system to this scene
  28575. * @param newParticleSystem The particle system to add
  28576. */
  28577. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  28578. this.particleSystems.push(newParticleSystem);
  28579. };
  28580. /**
  28581. * Adds the given animation to this scene
  28582. * @param newAnimation The animation to add
  28583. */
  28584. Scene.prototype.addAnimation = function (newAnimation) {
  28585. this.animations.push(newAnimation);
  28586. };
  28587. /**
  28588. * Adds the given animation group to this scene.
  28589. * @param newAnimationGroup The animation group to add
  28590. */
  28591. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  28592. this.animationGroups.push(newAnimationGroup);
  28593. };
  28594. /**
  28595. * Adds the given multi-material to this scene
  28596. * @param newMultiMaterial The multi-material to add
  28597. */
  28598. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  28599. this.multiMaterials.push(newMultiMaterial);
  28600. };
  28601. /**
  28602. * Adds the given material to this scene
  28603. * @param newMaterial The material to add
  28604. */
  28605. Scene.prototype.addMaterial = function (newMaterial) {
  28606. newMaterial._indexInSceneMaterialArray = this.materials.length;
  28607. this.materials.push(newMaterial);
  28608. this.onNewMaterialAddedObservable.notifyObservers(newMaterial);
  28609. };
  28610. /**
  28611. * Adds the given morph target to this scene
  28612. * @param newMorphTargetManager The morph target to add
  28613. */
  28614. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  28615. this.morphTargetManagers.push(newMorphTargetManager);
  28616. };
  28617. /**
  28618. * Adds the given geometry to this scene
  28619. * @param newGeometry The geometry to add
  28620. */
  28621. Scene.prototype.addGeometry = function (newGeometry) {
  28622. if (this.geometriesByUniqueId) {
  28623. this.geometriesByUniqueId[newGeometry.uniqueId] = this.geometries.length;
  28624. }
  28625. this.geometries.push(newGeometry);
  28626. };
  28627. /**
  28628. * Adds the given action manager to this scene
  28629. * @param newActionManager The action manager to add
  28630. */
  28631. Scene.prototype.addActionManager = function (newActionManager) {
  28632. this.actionManagers.push(newActionManager);
  28633. };
  28634. /**
  28635. * Adds the given texture to this scene.
  28636. * @param newTexture The texture to add
  28637. */
  28638. Scene.prototype.addTexture = function (newTexture) {
  28639. this.textures.push(newTexture);
  28640. this.onNewTextureAddedObservable.notifyObservers(newTexture);
  28641. };
  28642. /**
  28643. * Switch active camera
  28644. * @param newCamera defines the new active camera
  28645. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  28646. */
  28647. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  28648. if (attachControl === void 0) { attachControl = true; }
  28649. var canvas = this._engine.getRenderingCanvas();
  28650. if (!canvas) {
  28651. return;
  28652. }
  28653. if (this.activeCamera) {
  28654. this.activeCamera.detachControl(canvas);
  28655. }
  28656. this.activeCamera = newCamera;
  28657. if (attachControl) {
  28658. newCamera.attachControl(canvas);
  28659. }
  28660. };
  28661. /**
  28662. * sets the active camera of the scene using its ID
  28663. * @param id defines the camera's ID
  28664. * @return the new active camera or null if none found.
  28665. */
  28666. Scene.prototype.setActiveCameraByID = function (id) {
  28667. var camera = this.getCameraByID(id);
  28668. if (camera) {
  28669. this.activeCamera = camera;
  28670. return camera;
  28671. }
  28672. return null;
  28673. };
  28674. /**
  28675. * sets the active camera of the scene using its name
  28676. * @param name defines the camera's name
  28677. * @returns the new active camera or null if none found.
  28678. */
  28679. Scene.prototype.setActiveCameraByName = function (name) {
  28680. var camera = this.getCameraByName(name);
  28681. if (camera) {
  28682. this.activeCamera = camera;
  28683. return camera;
  28684. }
  28685. return null;
  28686. };
  28687. /**
  28688. * get an animation group using its name
  28689. * @param name defines the material's name
  28690. * @return the animation group or null if none found.
  28691. */
  28692. Scene.prototype.getAnimationGroupByName = function (name) {
  28693. for (var index = 0; index < this.animationGroups.length; index++) {
  28694. if (this.animationGroups[index].name === name) {
  28695. return this.animationGroups[index];
  28696. }
  28697. }
  28698. return null;
  28699. };
  28700. /**
  28701. * get a material using its id
  28702. * @param id defines the material's ID
  28703. * @return the material or null if none found.
  28704. */
  28705. Scene.prototype.getMaterialByID = function (id) {
  28706. for (var index = 0; index < this.materials.length; index++) {
  28707. if (this.materials[index].id === id) {
  28708. return this.materials[index];
  28709. }
  28710. }
  28711. return null;
  28712. };
  28713. /**
  28714. * Gets a material using its name
  28715. * @param name defines the material's name
  28716. * @return the material or null if none found.
  28717. */
  28718. Scene.prototype.getMaterialByName = function (name) {
  28719. for (var index = 0; index < this.materials.length; index++) {
  28720. if (this.materials[index].name === name) {
  28721. return this.materials[index];
  28722. }
  28723. }
  28724. return null;
  28725. };
  28726. /**
  28727. * Gets a camera using its id
  28728. * @param id defines the id to look for
  28729. * @returns the camera or null if not found
  28730. */
  28731. Scene.prototype.getCameraByID = function (id) {
  28732. for (var index = 0; index < this.cameras.length; index++) {
  28733. if (this.cameras[index].id === id) {
  28734. return this.cameras[index];
  28735. }
  28736. }
  28737. return null;
  28738. };
  28739. /**
  28740. * Gets a camera using its unique id
  28741. * @param uniqueId defines the unique id to look for
  28742. * @returns the camera or null if not found
  28743. */
  28744. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  28745. for (var index = 0; index < this.cameras.length; index++) {
  28746. if (this.cameras[index].uniqueId === uniqueId) {
  28747. return this.cameras[index];
  28748. }
  28749. }
  28750. return null;
  28751. };
  28752. /**
  28753. * Gets a camera using its name
  28754. * @param name defines the camera's name
  28755. * @return the camera or null if none found.
  28756. */
  28757. Scene.prototype.getCameraByName = function (name) {
  28758. for (var index = 0; index < this.cameras.length; index++) {
  28759. if (this.cameras[index].name === name) {
  28760. return this.cameras[index];
  28761. }
  28762. }
  28763. return null;
  28764. };
  28765. /**
  28766. * Gets a bone using its id
  28767. * @param id defines the bone's id
  28768. * @return the bone or null if not found
  28769. */
  28770. Scene.prototype.getBoneByID = function (id) {
  28771. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  28772. var skeleton = this.skeletons[skeletonIndex];
  28773. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  28774. if (skeleton.bones[boneIndex].id === id) {
  28775. return skeleton.bones[boneIndex];
  28776. }
  28777. }
  28778. }
  28779. return null;
  28780. };
  28781. /**
  28782. * Gets a bone using its id
  28783. * @param name defines the bone's name
  28784. * @return the bone or null if not found
  28785. */
  28786. Scene.prototype.getBoneByName = function (name) {
  28787. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  28788. var skeleton = this.skeletons[skeletonIndex];
  28789. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  28790. if (skeleton.bones[boneIndex].name === name) {
  28791. return skeleton.bones[boneIndex];
  28792. }
  28793. }
  28794. }
  28795. return null;
  28796. };
  28797. /**
  28798. * Gets a light node using its name
  28799. * @param name defines the the light's name
  28800. * @return the light or null if none found.
  28801. */
  28802. Scene.prototype.getLightByName = function (name) {
  28803. for (var index = 0; index < this.lights.length; index++) {
  28804. if (this.lights[index].name === name) {
  28805. return this.lights[index];
  28806. }
  28807. }
  28808. return null;
  28809. };
  28810. /**
  28811. * Gets a light node using its id
  28812. * @param id defines the light's id
  28813. * @return the light or null if none found.
  28814. */
  28815. Scene.prototype.getLightByID = function (id) {
  28816. for (var index = 0; index < this.lights.length; index++) {
  28817. if (this.lights[index].id === id) {
  28818. return this.lights[index];
  28819. }
  28820. }
  28821. return null;
  28822. };
  28823. /**
  28824. * Gets a light node using its scene-generated unique ID
  28825. * @param uniqueId defines the light's unique id
  28826. * @return the light or null if none found.
  28827. */
  28828. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  28829. for (var index = 0; index < this.lights.length; index++) {
  28830. if (this.lights[index].uniqueId === uniqueId) {
  28831. return this.lights[index];
  28832. }
  28833. }
  28834. return null;
  28835. };
  28836. /**
  28837. * Gets a particle system by id
  28838. * @param id defines the particle system id
  28839. * @return the corresponding system or null if none found
  28840. */
  28841. Scene.prototype.getParticleSystemByID = function (id) {
  28842. for (var index = 0; index < this.particleSystems.length; index++) {
  28843. if (this.particleSystems[index].id === id) {
  28844. return this.particleSystems[index];
  28845. }
  28846. }
  28847. return null;
  28848. };
  28849. /**
  28850. * Gets a geometry using its ID
  28851. * @param id defines the geometry's id
  28852. * @return the geometry or null if none found.
  28853. */
  28854. Scene.prototype.getGeometryByID = function (id) {
  28855. for (var index = 0; index < this.geometries.length; index++) {
  28856. if (this.geometries[index].id === id) {
  28857. return this.geometries[index];
  28858. }
  28859. }
  28860. return null;
  28861. };
  28862. Scene.prototype._getGeometryByUniqueID = function (uniqueId) {
  28863. if (this.geometriesByUniqueId) {
  28864. var index_1 = this.geometriesByUniqueId[uniqueId];
  28865. if (index_1 !== undefined) {
  28866. return this.geometries[index_1];
  28867. }
  28868. }
  28869. else {
  28870. for (var index = 0; index < this.geometries.length; index++) {
  28871. if (this.geometries[index].uniqueId === uniqueId) {
  28872. return this.geometries[index];
  28873. }
  28874. }
  28875. }
  28876. return null;
  28877. };
  28878. /**
  28879. * Add a new geometry to this scene
  28880. * @param geometry defines the geometry to be added to the scene.
  28881. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  28882. * @return a boolean defining if the geometry was added or not
  28883. */
  28884. Scene.prototype.pushGeometry = function (geometry, force) {
  28885. if (!force && this._getGeometryByUniqueID(geometry.uniqueId)) {
  28886. return false;
  28887. }
  28888. this.addGeometry(geometry);
  28889. //notify the collision coordinator
  28890. if (this.collisionCoordinator) {
  28891. this.collisionCoordinator.onGeometryAdded(geometry);
  28892. }
  28893. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  28894. return true;
  28895. };
  28896. /**
  28897. * Removes an existing geometry
  28898. * @param geometry defines the geometry to be removed from the scene
  28899. * @return a boolean defining if the geometry was removed or not
  28900. */
  28901. Scene.prototype.removeGeometry = function (geometry) {
  28902. var index;
  28903. if (this.geometriesByUniqueId) {
  28904. index = this.geometriesByUniqueId[geometry.uniqueId];
  28905. if (index === undefined) {
  28906. return false;
  28907. }
  28908. }
  28909. else {
  28910. index = this.geometries.indexOf(geometry);
  28911. if (index < 0) {
  28912. return false;
  28913. }
  28914. }
  28915. if (index !== this.geometries.length - 1) {
  28916. var lastGeometry = this.geometries[this.geometries.length - 1];
  28917. this.geometries[index] = lastGeometry;
  28918. if (this.geometriesByUniqueId) {
  28919. this.geometriesByUniqueId[lastGeometry.uniqueId] = index;
  28920. this.geometriesByUniqueId[geometry.uniqueId] = undefined;
  28921. }
  28922. }
  28923. this.geometries.pop();
  28924. //notify the collision coordinator
  28925. if (this.collisionCoordinator) {
  28926. this.collisionCoordinator.onGeometryDeleted(geometry);
  28927. }
  28928. this.onGeometryRemovedObservable.notifyObservers(geometry);
  28929. return true;
  28930. };
  28931. /**
  28932. * Gets the list of geometries attached to the scene
  28933. * @returns an array of Geometry
  28934. */
  28935. Scene.prototype.getGeometries = function () {
  28936. return this.geometries;
  28937. };
  28938. /**
  28939. * Gets the first added mesh found of a given ID
  28940. * @param id defines the id to search for
  28941. * @return the mesh found or null if not found at all
  28942. */
  28943. Scene.prototype.getMeshByID = function (id) {
  28944. for (var index = 0; index < this.meshes.length; index++) {
  28945. if (this.meshes[index].id === id) {
  28946. return this.meshes[index];
  28947. }
  28948. }
  28949. return null;
  28950. };
  28951. /**
  28952. * Gets a list of meshes using their id
  28953. * @param id defines the id to search for
  28954. * @returns a list of meshes
  28955. */
  28956. Scene.prototype.getMeshesByID = function (id) {
  28957. return this.meshes.filter(function (m) {
  28958. return m.id === id;
  28959. });
  28960. };
  28961. /**
  28962. * Gets the first added transform node found of a given ID
  28963. * @param id defines the id to search for
  28964. * @return the found transform node or null if not found at all.
  28965. */
  28966. Scene.prototype.getTransformNodeByID = function (id) {
  28967. for (var index = 0; index < this.transformNodes.length; index++) {
  28968. if (this.transformNodes[index].id === id) {
  28969. return this.transformNodes[index];
  28970. }
  28971. }
  28972. return null;
  28973. };
  28974. /**
  28975. * Gets a list of transform nodes using their id
  28976. * @param id defines the id to search for
  28977. * @returns a list of transform nodes
  28978. */
  28979. Scene.prototype.getTransformNodesByID = function (id) {
  28980. return this.transformNodes.filter(function (m) {
  28981. return m.id === id;
  28982. });
  28983. };
  28984. /**
  28985. * Gets a mesh with its auto-generated unique id
  28986. * @param uniqueId defines the unique id to search for
  28987. * @return the found mesh or null if not found at all.
  28988. */
  28989. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  28990. for (var index = 0; index < this.meshes.length; index++) {
  28991. if (this.meshes[index].uniqueId === uniqueId) {
  28992. return this.meshes[index];
  28993. }
  28994. }
  28995. return null;
  28996. };
  28997. /**
  28998. * Gets a the last added mesh using a given id
  28999. * @param id defines the id to search for
  29000. * @return the found mesh or null if not found at all.
  29001. */
  29002. Scene.prototype.getLastMeshByID = function (id) {
  29003. for (var index = this.meshes.length - 1; index >= 0; index--) {
  29004. if (this.meshes[index].id === id) {
  29005. return this.meshes[index];
  29006. }
  29007. }
  29008. return null;
  29009. };
  29010. /**
  29011. * Gets a the last added node (Mesh, Camera, Light) using a given id
  29012. * @param id defines the id to search for
  29013. * @return the found node or null if not found at all
  29014. */
  29015. Scene.prototype.getLastEntryByID = function (id) {
  29016. var index;
  29017. for (index = this.meshes.length - 1; index >= 0; index--) {
  29018. if (this.meshes[index].id === id) {
  29019. return this.meshes[index];
  29020. }
  29021. }
  29022. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  29023. if (this.transformNodes[index].id === id) {
  29024. return this.transformNodes[index];
  29025. }
  29026. }
  29027. for (index = this.cameras.length - 1; index >= 0; index--) {
  29028. if (this.cameras[index].id === id) {
  29029. return this.cameras[index];
  29030. }
  29031. }
  29032. for (index = this.lights.length - 1; index >= 0; index--) {
  29033. if (this.lights[index].id === id) {
  29034. return this.lights[index];
  29035. }
  29036. }
  29037. return null;
  29038. };
  29039. /**
  29040. * Gets a node (Mesh, Camera, Light) using a given id
  29041. * @param id defines the id to search for
  29042. * @return the found node or null if not found at all
  29043. */
  29044. Scene.prototype.getNodeByID = function (id) {
  29045. var mesh = this.getMeshByID(id);
  29046. if (mesh) {
  29047. return mesh;
  29048. }
  29049. var transformNode = this.getTransformNodeByID(id);
  29050. if (transformNode) {
  29051. return transformNode;
  29052. }
  29053. var light = this.getLightByID(id);
  29054. if (light) {
  29055. return light;
  29056. }
  29057. var camera = this.getCameraByID(id);
  29058. if (camera) {
  29059. return camera;
  29060. }
  29061. var bone = this.getBoneByID(id);
  29062. if (bone) {
  29063. return bone;
  29064. }
  29065. return null;
  29066. };
  29067. /**
  29068. * Gets a node (Mesh, Camera, Light) using a given name
  29069. * @param name defines the name to search for
  29070. * @return the found node or null if not found at all.
  29071. */
  29072. Scene.prototype.getNodeByName = function (name) {
  29073. var mesh = this.getMeshByName(name);
  29074. if (mesh) {
  29075. return mesh;
  29076. }
  29077. var transformNode = this.getTransformNodeByName(name);
  29078. if (transformNode) {
  29079. return transformNode;
  29080. }
  29081. var light = this.getLightByName(name);
  29082. if (light) {
  29083. return light;
  29084. }
  29085. var camera = this.getCameraByName(name);
  29086. if (camera) {
  29087. return camera;
  29088. }
  29089. var bone = this.getBoneByName(name);
  29090. if (bone) {
  29091. return bone;
  29092. }
  29093. return null;
  29094. };
  29095. /**
  29096. * Gets a mesh using a given name
  29097. * @param name defines the name to search for
  29098. * @return the found mesh or null if not found at all.
  29099. */
  29100. Scene.prototype.getMeshByName = function (name) {
  29101. for (var index = 0; index < this.meshes.length; index++) {
  29102. if (this.meshes[index].name === name) {
  29103. return this.meshes[index];
  29104. }
  29105. }
  29106. return null;
  29107. };
  29108. /**
  29109. * Gets a transform node using a given name
  29110. * @param name defines the name to search for
  29111. * @return the found transform node or null if not found at all.
  29112. */
  29113. Scene.prototype.getTransformNodeByName = function (name) {
  29114. for (var index = 0; index < this.transformNodes.length; index++) {
  29115. if (this.transformNodes[index].name === name) {
  29116. return this.transformNodes[index];
  29117. }
  29118. }
  29119. return null;
  29120. };
  29121. /**
  29122. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  29123. * @param id defines the id to search for
  29124. * @return the found skeleton or null if not found at all.
  29125. */
  29126. Scene.prototype.getLastSkeletonByID = function (id) {
  29127. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  29128. if (this.skeletons[index].id === id) {
  29129. return this.skeletons[index];
  29130. }
  29131. }
  29132. return null;
  29133. };
  29134. /**
  29135. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  29136. * @param id defines the id to search for
  29137. * @return the found skeleton or null if not found at all.
  29138. */
  29139. Scene.prototype.getSkeletonById = function (id) {
  29140. for (var index = 0; index < this.skeletons.length; index++) {
  29141. if (this.skeletons[index].id === id) {
  29142. return this.skeletons[index];
  29143. }
  29144. }
  29145. return null;
  29146. };
  29147. /**
  29148. * Gets a skeleton using a given name
  29149. * @param name defines the name to search for
  29150. * @return the found skeleton or null if not found at all.
  29151. */
  29152. Scene.prototype.getSkeletonByName = function (name) {
  29153. for (var index = 0; index < this.skeletons.length; index++) {
  29154. if (this.skeletons[index].name === name) {
  29155. return this.skeletons[index];
  29156. }
  29157. }
  29158. return null;
  29159. };
  29160. /**
  29161. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  29162. * @param id defines the id to search for
  29163. * @return the found morph target manager or null if not found at all.
  29164. */
  29165. Scene.prototype.getMorphTargetManagerById = function (id) {
  29166. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  29167. if (this.morphTargetManagers[index].uniqueId === id) {
  29168. return this.morphTargetManagers[index];
  29169. }
  29170. }
  29171. return null;
  29172. };
  29173. /**
  29174. * Gets a morph target using a given id (if many are found, this function will pick the first one)
  29175. * @param id defines the id to search for
  29176. * @return the found morph target or null if not found at all.
  29177. */
  29178. Scene.prototype.getMorphTargetById = function (id) {
  29179. for (var managerIndex = 0; managerIndex < this.morphTargetManagers.length; ++managerIndex) {
  29180. var morphTargetManager = this.morphTargetManagers[managerIndex];
  29181. for (var index = 0; index < morphTargetManager.numTargets; ++index) {
  29182. var target = morphTargetManager.getTarget(index);
  29183. if (target.id === id) {
  29184. return target;
  29185. }
  29186. }
  29187. }
  29188. return null;
  29189. };
  29190. /**
  29191. * Gets a boolean indicating if the given mesh is active
  29192. * @param mesh defines the mesh to look for
  29193. * @returns true if the mesh is in the active list
  29194. */
  29195. Scene.prototype.isActiveMesh = function (mesh) {
  29196. return (this._activeMeshes.indexOf(mesh) !== -1);
  29197. };
  29198. Object.defineProperty(Scene.prototype, "uid", {
  29199. /**
  29200. * Return a unique id as a string which can serve as an identifier for the scene
  29201. */
  29202. get: function () {
  29203. if (!this._uid) {
  29204. this._uid = BABYLON.Tools.RandomId();
  29205. }
  29206. return this._uid;
  29207. },
  29208. enumerable: true,
  29209. configurable: true
  29210. });
  29211. /**
  29212. * Add an externaly attached data from its key.
  29213. * This method call will fail and return false, if such key already exists.
  29214. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  29215. * @param key the unique key that identifies the data
  29216. * @param data the data object to associate to the key for this Engine instance
  29217. * @return true if no such key were already present and the data was added successfully, false otherwise
  29218. */
  29219. Scene.prototype.addExternalData = function (key, data) {
  29220. if (!this._externalData) {
  29221. this._externalData = new BABYLON.StringDictionary();
  29222. }
  29223. return this._externalData.add(key, data);
  29224. };
  29225. /**
  29226. * Get an externaly attached data from its key
  29227. * @param key the unique key that identifies the data
  29228. * @return the associated data, if present (can be null), or undefined if not present
  29229. */
  29230. Scene.prototype.getExternalData = function (key) {
  29231. if (!this._externalData) {
  29232. return null;
  29233. }
  29234. return this._externalData.get(key);
  29235. };
  29236. /**
  29237. * Get an externaly attached data from its key, create it using a factory if it's not already present
  29238. * @param key the unique key that identifies the data
  29239. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  29240. * @return the associated data, can be null if the factory returned null.
  29241. */
  29242. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  29243. if (!this._externalData) {
  29244. this._externalData = new BABYLON.StringDictionary();
  29245. }
  29246. return this._externalData.getOrAddWithFactory(key, factory);
  29247. };
  29248. /**
  29249. * Remove an externaly attached data from the Engine instance
  29250. * @param key the unique key that identifies the data
  29251. * @return true if the data was successfully removed, false if it doesn't exist
  29252. */
  29253. Scene.prototype.removeExternalData = function (key) {
  29254. return this._externalData.remove(key);
  29255. };
  29256. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  29257. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  29258. for (var _i = 0, _a = this._evaluateSubMeshStage; _i < _a.length; _i++) {
  29259. var step = _a[_i];
  29260. step.action(mesh, subMesh);
  29261. }
  29262. var material = subMesh.getMaterial();
  29263. if (material !== null && material !== undefined) {
  29264. // Render targets
  29265. if (material.hasRenderTargetTextures && material.getRenderTargetTextures !== undefined) {
  29266. if (this._processedMaterials.indexOf(material) === -1) {
  29267. this._processedMaterials.push(material);
  29268. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  29269. }
  29270. }
  29271. // Dispatch
  29272. this._activeIndices.addCount(subMesh.indexCount, false);
  29273. this._renderingManager.dispatch(subMesh, mesh, material);
  29274. }
  29275. }
  29276. };
  29277. /**
  29278. * Clear the processed materials smart array preventing retention point in material dispose.
  29279. */
  29280. Scene.prototype.freeProcessedMaterials = function () {
  29281. this._processedMaterials.dispose();
  29282. };
  29283. Object.defineProperty(Scene.prototype, "blockfreeActiveMeshesAndRenderingGroups", {
  29284. /** Gets or sets a boolean blocking all the calls to freeActiveMeshes and freeRenderingGroups
  29285. * It can be used in order to prevent going through methods freeRenderingGroups and freeActiveMeshes several times to improve performance
  29286. * when disposing several meshes in a row or a hierarchy of meshes.
  29287. * When used, it is the responsability of the user to blockfreeActiveMeshesAndRenderingGroups back to false.
  29288. */
  29289. get: function () {
  29290. return this._preventFreeActiveMeshesAndRenderingGroups;
  29291. },
  29292. set: function (value) {
  29293. if (this._preventFreeActiveMeshesAndRenderingGroups === value) {
  29294. return;
  29295. }
  29296. if (value) {
  29297. this.freeActiveMeshes();
  29298. this.freeRenderingGroups();
  29299. }
  29300. this._preventFreeActiveMeshesAndRenderingGroups = value;
  29301. },
  29302. enumerable: true,
  29303. configurable: true
  29304. });
  29305. /**
  29306. * Clear the active meshes smart array preventing retention point in mesh dispose.
  29307. */
  29308. Scene.prototype.freeActiveMeshes = function () {
  29309. if (this.blockfreeActiveMeshesAndRenderingGroups) {
  29310. return;
  29311. }
  29312. this._activeMeshes.dispose();
  29313. if (this.activeCamera && this.activeCamera._activeMeshes) {
  29314. this.activeCamera._activeMeshes.dispose();
  29315. }
  29316. if (this.activeCameras) {
  29317. for (var i = 0; i < this.activeCameras.length; i++) {
  29318. var activeCamera = this.activeCameras[i];
  29319. if (activeCamera && activeCamera._activeMeshes) {
  29320. activeCamera._activeMeshes.dispose();
  29321. }
  29322. }
  29323. }
  29324. };
  29325. /**
  29326. * Clear the info related to rendering groups preventing retention points during dispose.
  29327. */
  29328. Scene.prototype.freeRenderingGroups = function () {
  29329. if (this.blockfreeActiveMeshesAndRenderingGroups) {
  29330. return;
  29331. }
  29332. if (this._renderingManager) {
  29333. this._renderingManager.freeRenderingGroups();
  29334. }
  29335. if (this.textures) {
  29336. for (var i = 0; i < this.textures.length; i++) {
  29337. var texture = this.textures[i];
  29338. if (texture && texture.renderList) {
  29339. texture.freeRenderingGroups();
  29340. }
  29341. }
  29342. }
  29343. };
  29344. /** @hidden */
  29345. Scene.prototype._isInIntermediateRendering = function () {
  29346. return this._intermediateRendering;
  29347. };
  29348. /**
  29349. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  29350. * @returns the current scene
  29351. */
  29352. Scene.prototype.freezeActiveMeshes = function () {
  29353. if (!this.activeCamera) {
  29354. return this;
  29355. }
  29356. if (!this._frustumPlanes) {
  29357. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  29358. }
  29359. this._evaluateActiveMeshes();
  29360. this._activeMeshesFrozen = true;
  29361. return this;
  29362. };
  29363. /**
  29364. * Use this function to restart evaluating active meshes on every frame
  29365. * @returns the current scene
  29366. */
  29367. Scene.prototype.unfreezeActiveMeshes = function () {
  29368. this._activeMeshesFrozen = false;
  29369. return this;
  29370. };
  29371. Scene.prototype._evaluateActiveMeshes = function () {
  29372. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  29373. return;
  29374. }
  29375. if (!this.activeCamera) {
  29376. return;
  29377. }
  29378. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  29379. this.activeCamera._activeMeshes.reset();
  29380. this._activeMeshes.reset();
  29381. this._renderingManager.reset();
  29382. this._processedMaterials.reset();
  29383. this._activeParticleSystems.reset();
  29384. this._activeSkeletons.reset();
  29385. this._softwareSkinnedMeshes.reset();
  29386. for (var _i = 0, _a = this._beforeEvaluateActiveMeshStage; _i < _a.length; _i++) {
  29387. var step = _a[_i];
  29388. step.action();
  29389. }
  29390. // Determine mesh candidates
  29391. var meshes = this.getActiveMeshCandidates();
  29392. // Check each mesh
  29393. var len = meshes.length;
  29394. for (var i = 0; i < len; i++) {
  29395. var mesh = meshes.data[i];
  29396. if (mesh.isBlocked) {
  29397. continue;
  29398. }
  29399. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  29400. if (!mesh.isReady() || !mesh.isEnabled()) {
  29401. continue;
  29402. }
  29403. mesh.computeWorldMatrix();
  29404. // Intersections
  29405. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers2(BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger)) {
  29406. this._meshesForIntersections.pushNoDuplicate(mesh);
  29407. }
  29408. // Switch to current LOD
  29409. var meshLOD = mesh.getLOD(this.activeCamera);
  29410. if (meshLOD === undefined || meshLOD === null) {
  29411. continue;
  29412. }
  29413. mesh._preActivate();
  29414. if (mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && (mesh.alwaysSelectAsActiveMesh || mesh.isInFrustum(this._frustumPlanes))) {
  29415. this._activeMeshes.push(mesh);
  29416. this.activeCamera._activeMeshes.push(mesh);
  29417. mesh._activate(this._renderId);
  29418. if (meshLOD !== mesh) {
  29419. meshLOD._activate(this._renderId);
  29420. }
  29421. this._activeMesh(mesh, meshLOD);
  29422. }
  29423. }
  29424. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  29425. // Particle systems
  29426. if (this.particlesEnabled) {
  29427. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  29428. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  29429. var particleSystem = this.particleSystems[particleIndex];
  29430. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  29431. continue;
  29432. }
  29433. var emitter = particleSystem.emitter;
  29434. if (!emitter.position || emitter.isEnabled()) {
  29435. this._activeParticleSystems.push(particleSystem);
  29436. particleSystem.animate();
  29437. this._renderingManager.dispatchParticles(particleSystem);
  29438. }
  29439. }
  29440. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  29441. }
  29442. };
  29443. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  29444. if (this._skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  29445. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  29446. mesh.skeleton.prepare();
  29447. }
  29448. if (!mesh.computeBonesUsingShaders) {
  29449. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  29450. }
  29451. }
  29452. for (var _i = 0, _a = this._activeMeshStage; _i < _a.length; _i++) {
  29453. var step = _a[_i];
  29454. step.action(sourceMesh, mesh);
  29455. }
  29456. if (mesh !== undefined && mesh !== null
  29457. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  29458. var subMeshes = this.getActiveSubMeshCandidates(mesh);
  29459. var len = subMeshes.length;
  29460. for (var i = 0; i < len; i++) {
  29461. var subMesh = subMeshes.data[i];
  29462. this._evaluateSubMesh(subMesh, mesh);
  29463. }
  29464. }
  29465. };
  29466. /**
  29467. * Update the transform matrix to update from the current active camera
  29468. * @param force defines a boolean used to force the update even if cache is up to date
  29469. */
  29470. Scene.prototype.updateTransformMatrix = function (force) {
  29471. if (!this.activeCamera) {
  29472. return;
  29473. }
  29474. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  29475. };
  29476. /**
  29477. * 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)
  29478. * @param alternateCamera defines the camera to use
  29479. */
  29480. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  29481. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  29482. };
  29483. Scene.prototype._renderForCamera = function (camera, rigParent) {
  29484. if (camera && camera._skipRendering) {
  29485. return;
  29486. }
  29487. var engine = this._engine;
  29488. this.activeCamera = camera;
  29489. if (!this.activeCamera) {
  29490. throw new Error("Active camera not set");
  29491. }
  29492. // Viewport
  29493. engine.setViewport(this.activeCamera.viewport);
  29494. // Camera
  29495. this.resetCachedMaterial();
  29496. this._renderId++;
  29497. this.updateTransformMatrix();
  29498. if (camera._alternateCamera) {
  29499. this.updateAlternateTransformMatrix(camera._alternateCamera);
  29500. this._alternateRendering = true;
  29501. }
  29502. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  29503. // Meshes
  29504. this._evaluateActiveMeshes();
  29505. // Software skinning
  29506. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  29507. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  29508. mesh.applySkeleton(mesh.skeleton);
  29509. }
  29510. // Render targets
  29511. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  29512. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  29513. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  29514. }
  29515. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  29516. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  29517. }
  29518. // Collects render targets from external components.
  29519. for (var _i = 0, _a = this._gatherActiveCameraRenderTargetsStage; _i < _a.length; _i++) {
  29520. var step = _a[_i];
  29521. step.action(this._renderTargets);
  29522. }
  29523. if (this.renderTargetsEnabled) {
  29524. this._intermediateRendering = true;
  29525. if (this._renderTargets.length > 0) {
  29526. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  29527. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  29528. var renderTarget = this._renderTargets.data[renderIndex];
  29529. if (renderTarget._shouldRender()) {
  29530. this._renderId++;
  29531. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  29532. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  29533. }
  29534. }
  29535. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  29536. this._renderId++;
  29537. }
  29538. for (var _b = 0, _c = this._cameraDrawRenderTargetStage; _b < _c.length; _b++) {
  29539. var step = _c[_b];
  29540. step.action(this.activeCamera);
  29541. }
  29542. this._intermediateRendering = false;
  29543. if (this.activeCamera.outputRenderTarget) {
  29544. var internalTexture = this.activeCamera.outputRenderTarget.getInternalTexture();
  29545. if (internalTexture) {
  29546. engine.bindFramebuffer(internalTexture);
  29547. }
  29548. else {
  29549. BABYLON.Tools.Error("Camera contains invalid customDefaultRenderTarget");
  29550. }
  29551. }
  29552. else {
  29553. engine.restoreDefaultFramebuffer(); // Restore back buffer if needed
  29554. }
  29555. }
  29556. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  29557. // Prepare Frame
  29558. if (this.postProcessManager) {
  29559. this.postProcessManager._prepareFrame();
  29560. }
  29561. // Before Camera Draw
  29562. for (var _d = 0, _e = this._beforeCameraDrawStage; _d < _e.length; _d++) {
  29563. var step = _e[_d];
  29564. step.action(this.activeCamera);
  29565. }
  29566. // Render
  29567. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  29568. this._renderingManager.render(null, null, true, true);
  29569. this.onAfterDrawPhaseObservable.notifyObservers(this);
  29570. // After Camera Draw
  29571. for (var _f = 0, _g = this._afterCameraDrawStage; _f < _g.length; _f++) {
  29572. var step = _g[_f];
  29573. step.action(this.activeCamera);
  29574. }
  29575. // Finalize frame
  29576. if (this.postProcessManager) {
  29577. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  29578. }
  29579. // Reset some special arrays
  29580. this._renderTargets.reset();
  29581. this._alternateRendering = false;
  29582. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  29583. };
  29584. Scene.prototype._processSubCameras = function (camera) {
  29585. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  29586. this._renderForCamera(camera);
  29587. return;
  29588. }
  29589. // rig cameras
  29590. for (var index = 0; index < camera._rigCameras.length; index++) {
  29591. this._renderForCamera(camera._rigCameras[index], camera);
  29592. }
  29593. this.activeCamera = camera;
  29594. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  29595. };
  29596. Scene.prototype._checkIntersections = function () {
  29597. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  29598. var sourceMesh = this._meshesForIntersections.data[index];
  29599. if (!sourceMesh.actionManager) {
  29600. continue;
  29601. }
  29602. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  29603. var action = sourceMesh.actionManager.actions[actionIndex];
  29604. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  29605. var parameters = action.getTriggerParameter();
  29606. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  29607. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  29608. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  29609. if (areIntersecting && currentIntersectionInProgress === -1) {
  29610. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  29611. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  29612. sourceMesh._intersectionsInProgress.push(otherMesh);
  29613. }
  29614. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  29615. sourceMesh._intersectionsInProgress.push(otherMesh);
  29616. }
  29617. }
  29618. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  29619. //They intersected, and now they don't.
  29620. //is this trigger an exit trigger? execute an event.
  29621. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  29622. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  29623. }
  29624. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  29625. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {
  29626. var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;
  29627. return otherMesh === parameterMesh;
  29628. }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  29629. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  29630. }
  29631. }
  29632. }
  29633. }
  29634. }
  29635. };
  29636. /** @hidden */
  29637. Scene.prototype._advancePhysicsEngineStep = function (step) {
  29638. // Do nothing. Code will be replaced if physics engine component is referenced
  29639. };
  29640. /**
  29641. * Render the scene
  29642. * @param updateCameras defines a boolean indicating if cameras must update according to their inputs (true by default)
  29643. */
  29644. Scene.prototype.render = function (updateCameras) {
  29645. if (updateCameras === void 0) { updateCameras = true; }
  29646. if (this.isDisposed) {
  29647. return;
  29648. }
  29649. this._frameId++;
  29650. // Register components that have been associated lately to the scene.
  29651. this._registerTransientComponents();
  29652. this._activeParticles.fetchNewFrame();
  29653. this._totalVertices.fetchNewFrame();
  29654. this._activeIndices.fetchNewFrame();
  29655. this._activeBones.fetchNewFrame();
  29656. this._meshesForIntersections.reset();
  29657. this.resetCachedMaterial();
  29658. this.onBeforeAnimationsObservable.notifyObservers(this);
  29659. // Actions
  29660. if (this.actionManager) {
  29661. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  29662. }
  29663. if (this._engine.isDeterministicLockStep()) {
  29664. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  29665. var defaultFPS = (60.0 / 1000.0);
  29666. var defaultFrameTime = this.getDeterministicFrameTime();
  29667. var stepsTaken = 0;
  29668. var maxSubSteps = this._engine.getLockstepMaxSteps();
  29669. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  29670. internalSteps = Math.min(internalSteps, maxSubSteps);
  29671. do {
  29672. this.onBeforeStepObservable.notifyObservers(this);
  29673. // Animations
  29674. this._animationRatio = defaultFrameTime * defaultFPS;
  29675. this._animate();
  29676. this.onAfterAnimationsObservable.notifyObservers(this);
  29677. // Physics
  29678. this._advancePhysicsEngineStep(defaultFrameTime);
  29679. this.onAfterStepObservable.notifyObservers(this);
  29680. this._currentStepId++;
  29681. stepsTaken++;
  29682. deltaTime -= defaultFrameTime;
  29683. } while (deltaTime > 0 && stepsTaken < internalSteps);
  29684. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  29685. }
  29686. else {
  29687. // Animations
  29688. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  29689. this._animationRatio = deltaTime * (60.0 / 1000.0);
  29690. this._animate();
  29691. this.onAfterAnimationsObservable.notifyObservers(this);
  29692. // Physics
  29693. this._advancePhysicsEngineStep(deltaTime);
  29694. }
  29695. // Before camera update steps
  29696. for (var _i = 0, _a = this._beforeCameraUpdateStage; _i < _a.length; _i++) {
  29697. var step = _a[_i];
  29698. step.action();
  29699. }
  29700. // Update Cameras
  29701. if (updateCameras) {
  29702. if (this.activeCameras.length > 0) {
  29703. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  29704. var camera = this.activeCameras[cameraIndex];
  29705. camera.update();
  29706. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  29707. // rig cameras
  29708. for (var index = 0; index < camera._rigCameras.length; index++) {
  29709. camera._rigCameras[index].update();
  29710. }
  29711. }
  29712. }
  29713. }
  29714. else if (this.activeCamera) {
  29715. this.activeCamera.update();
  29716. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  29717. // rig cameras
  29718. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  29719. this.activeCamera._rigCameras[index].update();
  29720. }
  29721. }
  29722. }
  29723. }
  29724. // Before render
  29725. this.onBeforeRenderObservable.notifyObservers(this);
  29726. // Customs render targets
  29727. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  29728. var engine = this.getEngine();
  29729. var currentActiveCamera = this.activeCamera;
  29730. if (this.renderTargetsEnabled) {
  29731. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  29732. this._intermediateRendering = true;
  29733. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  29734. var renderTarget = this.customRenderTargets[customIndex];
  29735. if (renderTarget._shouldRender()) {
  29736. this._renderId++;
  29737. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  29738. if (!this.activeCamera) {
  29739. throw new Error("Active camera not set");
  29740. }
  29741. // Viewport
  29742. engine.setViewport(this.activeCamera.viewport);
  29743. // Camera
  29744. this.updateTransformMatrix();
  29745. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  29746. }
  29747. }
  29748. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  29749. this._intermediateRendering = false;
  29750. this._renderId++;
  29751. }
  29752. // Restore back buffer
  29753. if (this.customRenderTargets.length > 0) {
  29754. engine.restoreDefaultFramebuffer();
  29755. }
  29756. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  29757. this.activeCamera = currentActiveCamera;
  29758. for (var _b = 0, _c = this._beforeClearStage; _b < _c.length; _b++) {
  29759. var step = _c[_b];
  29760. step.action();
  29761. }
  29762. // Clear
  29763. if (this.autoClearDepthAndStencil || this.autoClear) {
  29764. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  29765. }
  29766. // Collects render targets from external components.
  29767. for (var _d = 0, _e = this._gatherRenderTargetsStage; _d < _e.length; _d++) {
  29768. var step = _e[_d];
  29769. step.action(this._renderTargets);
  29770. }
  29771. // Multi-cameras?
  29772. if (this.activeCameras.length > 0) {
  29773. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  29774. if (cameraIndex > 0) {
  29775. this._engine.clear(null, false, true, true);
  29776. }
  29777. this._processSubCameras(this.activeCameras[cameraIndex]);
  29778. }
  29779. }
  29780. else {
  29781. if (!this.activeCamera) {
  29782. throw new Error("No camera defined");
  29783. }
  29784. this._processSubCameras(this.activeCamera);
  29785. }
  29786. // Intersection checks
  29787. this._checkIntersections();
  29788. // Executes the after render stage actions.
  29789. for (var _f = 0, _g = this._afterRenderStage; _f < _g.length; _f++) {
  29790. var step = _g[_f];
  29791. step.action();
  29792. }
  29793. // After render
  29794. if (this.afterRender) {
  29795. this.afterRender();
  29796. }
  29797. this.onAfterRenderObservable.notifyObservers(this);
  29798. // Cleaning
  29799. if (this._toBeDisposed.length) {
  29800. for (var index = 0; index < this._toBeDisposed.length; index++) {
  29801. var data = this._toBeDisposed[index];
  29802. if (data) {
  29803. data.dispose();
  29804. }
  29805. }
  29806. this._toBeDisposed = [];
  29807. }
  29808. if (this.dumpNextRenderTargets) {
  29809. this.dumpNextRenderTargets = false;
  29810. }
  29811. this._activeBones.addCount(0, true);
  29812. this._activeIndices.addCount(0, true);
  29813. this._activeParticles.addCount(0, true);
  29814. };
  29815. /**
  29816. * Freeze all materials
  29817. * A frozen material will not be updatable but should be faster to render
  29818. */
  29819. Scene.prototype.freezeMaterials = function () {
  29820. for (var i = 0; i < this.materials.length; i++) {
  29821. this.materials[i].freeze();
  29822. }
  29823. };
  29824. /**
  29825. * Unfreeze all materials
  29826. * A frozen material will not be updatable but should be faster to render
  29827. */
  29828. Scene.prototype.unfreezeMaterials = function () {
  29829. for (var i = 0; i < this.materials.length; i++) {
  29830. this.materials[i].unfreeze();
  29831. }
  29832. };
  29833. /**
  29834. * Releases all held ressources
  29835. */
  29836. Scene.prototype.dispose = function () {
  29837. this.beforeRender = null;
  29838. this.afterRender = null;
  29839. this.skeletons = [];
  29840. this.morphTargetManagers = [];
  29841. this._transientComponents = [];
  29842. this._isReadyForMeshStage.clear();
  29843. this._beforeEvaluateActiveMeshStage.clear();
  29844. this._evaluateSubMeshStage.clear();
  29845. this._activeMeshStage.clear();
  29846. this._cameraDrawRenderTargetStage.clear();
  29847. this._beforeCameraDrawStage.clear();
  29848. this._beforeRenderTargetDrawStage.clear();
  29849. this._beforeRenderingGroupDrawStage.clear();
  29850. this._beforeRenderingMeshStage.clear();
  29851. this._afterRenderingMeshStage.clear();
  29852. this._afterRenderingGroupDrawStage.clear();
  29853. this._afterCameraDrawStage.clear();
  29854. this._afterRenderTargetDrawStage.clear();
  29855. this._afterRenderStage.clear();
  29856. this._beforeCameraUpdateStage.clear();
  29857. this._beforeClearStage.clear();
  29858. this._gatherRenderTargetsStage.clear();
  29859. this._gatherActiveCameraRenderTargetsStage.clear();
  29860. this._pointerMoveStage.clear();
  29861. this._pointerDownStage.clear();
  29862. this._pointerUpStage.clear();
  29863. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  29864. var component = _a[_i];
  29865. component.dispose();
  29866. }
  29867. this.importedMeshesFiles = new Array();
  29868. this.stopAllAnimations();
  29869. this.resetCachedMaterial();
  29870. // Smart arrays
  29871. if (this.activeCamera) {
  29872. this.activeCamera._activeMeshes.dispose();
  29873. this.activeCamera = null;
  29874. }
  29875. this._activeMeshes.dispose();
  29876. this._renderingManager.dispose();
  29877. this._processedMaterials.dispose();
  29878. this._activeParticleSystems.dispose();
  29879. this._activeSkeletons.dispose();
  29880. this._softwareSkinnedMeshes.dispose();
  29881. this._renderTargets.dispose();
  29882. this._registeredForLateAnimationBindings.dispose();
  29883. this._meshesForIntersections.dispose();
  29884. this._toBeDisposed = [];
  29885. // Abort active requests
  29886. for (var _b = 0, _c = this._activeRequests; _b < _c.length; _b++) {
  29887. var request = _c[_b];
  29888. request.abort();
  29889. }
  29890. // Events
  29891. this.onDisposeObservable.notifyObservers(this);
  29892. this.onDisposeObservable.clear();
  29893. this.onBeforeRenderObservable.clear();
  29894. this.onAfterRenderObservable.clear();
  29895. this.onBeforeRenderTargetsRenderObservable.clear();
  29896. this.onAfterRenderTargetsRenderObservable.clear();
  29897. this.onAfterStepObservable.clear();
  29898. this.onBeforeStepObservable.clear();
  29899. this.onBeforeActiveMeshesEvaluationObservable.clear();
  29900. this.onAfterActiveMeshesEvaluationObservable.clear();
  29901. this.onBeforeParticlesRenderingObservable.clear();
  29902. this.onAfterParticlesRenderingObservable.clear();
  29903. this.onBeforeDrawPhaseObservable.clear();
  29904. this.onAfterDrawPhaseObservable.clear();
  29905. this.onBeforeAnimationsObservable.clear();
  29906. this.onAfterAnimationsObservable.clear();
  29907. this.onDataLoadedObservable.clear();
  29908. this.onBeforeRenderingGroupObservable.clear();
  29909. this.onAfterRenderingGroupObservable.clear();
  29910. this.onMeshImportedObservable.clear();
  29911. this.onBeforeCameraRenderObservable.clear();
  29912. this.onAfterCameraRenderObservable.clear();
  29913. this.onReadyObservable.clear();
  29914. this.onNewCameraAddedObservable.clear();
  29915. this.onCameraRemovedObservable.clear();
  29916. this.onNewLightAddedObservable.clear();
  29917. this.onLightRemovedObservable.clear();
  29918. this.onNewGeometryAddedObservable.clear();
  29919. this.onGeometryRemovedObservable.clear();
  29920. this.onNewTransformNodeAddedObservable.clear();
  29921. this.onTransformNodeRemovedObservable.clear();
  29922. this.onNewMeshAddedObservable.clear();
  29923. this.onMeshRemovedObservable.clear();
  29924. this.onNewMaterialAddedObservable.clear();
  29925. this.onMaterialRemovedObservable.clear();
  29926. this.onNewTextureAddedObservable.clear();
  29927. this.onTextureRemovedObservable.clear();
  29928. this.onPrePointerObservable.clear();
  29929. this.onPointerObservable.clear();
  29930. this.onPreKeyboardObservable.clear();
  29931. this.onKeyboardObservable.clear();
  29932. this.onActiveCameraChanged.clear();
  29933. this.detachControl();
  29934. // Detach cameras
  29935. var canvas = this._engine.getRenderingCanvas();
  29936. if (canvas) {
  29937. var index;
  29938. for (index = 0; index < this.cameras.length; index++) {
  29939. this.cameras[index].detachControl(canvas);
  29940. }
  29941. }
  29942. // Release animation groups
  29943. while (this.animationGroups.length) {
  29944. this.animationGroups[0].dispose();
  29945. }
  29946. // Release lights
  29947. while (this.lights.length) {
  29948. this.lights[0].dispose();
  29949. }
  29950. // Release meshes
  29951. while (this.meshes.length) {
  29952. this.meshes[0].dispose(true);
  29953. }
  29954. while (this.transformNodes.length) {
  29955. this.removeTransformNode(this.transformNodes[0]);
  29956. }
  29957. // Release cameras
  29958. while (this.cameras.length) {
  29959. this.cameras[0].dispose();
  29960. }
  29961. // Release materials
  29962. if (this.defaultMaterial) {
  29963. this.defaultMaterial.dispose();
  29964. }
  29965. while (this.multiMaterials.length) {
  29966. this.multiMaterials[0].dispose();
  29967. }
  29968. while (this.materials.length) {
  29969. this.materials[0].dispose();
  29970. }
  29971. // Release particles
  29972. while (this.particleSystems.length) {
  29973. this.particleSystems[0].dispose();
  29974. }
  29975. // Release postProcesses
  29976. while (this.postProcesses.length) {
  29977. this.postProcesses[0].dispose();
  29978. }
  29979. // Release textures
  29980. while (this.textures.length) {
  29981. this.textures[0].dispose();
  29982. }
  29983. // Release UBO
  29984. this._sceneUbo.dispose();
  29985. if (this._alternateSceneUbo) {
  29986. this._alternateSceneUbo.dispose();
  29987. }
  29988. // Post-processes
  29989. this.postProcessManager.dispose();
  29990. // Remove from engine
  29991. index = this._engine.scenes.indexOf(this);
  29992. if (index > -1) {
  29993. this._engine.scenes.splice(index, 1);
  29994. }
  29995. this._engine.wipeCaches(true);
  29996. this._isDisposed = true;
  29997. };
  29998. Object.defineProperty(Scene.prototype, "isDisposed", {
  29999. /**
  30000. * Gets if the scene is already disposed
  30001. */
  30002. get: function () {
  30003. return this._isDisposed;
  30004. },
  30005. enumerable: true,
  30006. configurable: true
  30007. });
  30008. /**
  30009. * Call this function to reduce memory footprint of the scene.
  30010. * Vertex buffers will not store CPU data anymore (this will prevent picking, collisions or physics to work correctly)
  30011. */
  30012. Scene.prototype.clearCachedVertexData = function () {
  30013. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  30014. var mesh = this.meshes[meshIndex];
  30015. var geometry = mesh.geometry;
  30016. if (geometry) {
  30017. geometry._indices = [];
  30018. for (var vbName in geometry._vertexBuffers) {
  30019. if (!geometry._vertexBuffers.hasOwnProperty(vbName)) {
  30020. continue;
  30021. }
  30022. geometry._vertexBuffers[vbName]._buffer._data = null;
  30023. }
  30024. }
  30025. }
  30026. };
  30027. /**
  30028. * This function will remove the local cached buffer data from texture.
  30029. * It will save memory but will prevent the texture from being rebuilt
  30030. */
  30031. Scene.prototype.cleanCachedTextureBuffer = function () {
  30032. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  30033. var baseTexture = _a[_i];
  30034. var buffer = baseTexture._buffer;
  30035. if (buffer) {
  30036. baseTexture._buffer = null;
  30037. }
  30038. }
  30039. };
  30040. /**
  30041. * Get the world extend vectors with an optional filter
  30042. *
  30043. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  30044. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  30045. */
  30046. Scene.prototype.getWorldExtends = function (filterPredicate) {
  30047. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  30048. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  30049. filterPredicate = filterPredicate || (function () { return true; });
  30050. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  30051. mesh.computeWorldMatrix(true);
  30052. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  30053. return;
  30054. }
  30055. var boundingInfo = mesh.getBoundingInfo();
  30056. var minBox = boundingInfo.boundingBox.minimumWorld;
  30057. var maxBox = boundingInfo.boundingBox.maximumWorld;
  30058. BABYLON.Tools.CheckExtends(minBox, min, max);
  30059. BABYLON.Tools.CheckExtends(maxBox, min, max);
  30060. });
  30061. return {
  30062. min: min,
  30063. max: max
  30064. };
  30065. };
  30066. // Picking
  30067. /**
  30068. * Creates a ray that can be used to pick in the scene
  30069. * @param x defines the x coordinate of the origin (on-screen)
  30070. * @param y defines the y coordinate of the origin (on-screen)
  30071. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  30072. * @param camera defines the camera to use for the picking
  30073. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  30074. * @returns a Ray
  30075. */
  30076. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  30077. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  30078. var result = BABYLON.Ray.Zero();
  30079. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  30080. return result;
  30081. };
  30082. /**
  30083. * Creates a ray that can be used to pick in the scene
  30084. * @param x defines the x coordinate of the origin (on-screen)
  30085. * @param y defines the y coordinate of the origin (on-screen)
  30086. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  30087. * @param result defines the ray where to store the picking ray
  30088. * @param camera defines the camera to use for the picking
  30089. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  30090. * @returns the current scene
  30091. */
  30092. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  30093. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  30094. var engine = this._engine;
  30095. if (!camera) {
  30096. if (!this.activeCamera) {
  30097. throw new Error("Active camera not set");
  30098. }
  30099. camera = this.activeCamera;
  30100. }
  30101. var cameraViewport = camera.viewport;
  30102. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  30103. // Moving coordinates to local viewport world
  30104. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  30105. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  30106. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.IdentityReadOnly, cameraViewSpace ? BABYLON.Matrix.IdentityReadOnly : camera.getViewMatrix(), camera.getProjectionMatrix());
  30107. return this;
  30108. };
  30109. /**
  30110. * Creates a ray that can be used to pick in the scene
  30111. * @param x defines the x coordinate of the origin (on-screen)
  30112. * @param y defines the y coordinate of the origin (on-screen)
  30113. * @param camera defines the camera to use for the picking
  30114. * @returns a Ray
  30115. */
  30116. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  30117. var result = BABYLON.Ray.Zero();
  30118. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  30119. return result;
  30120. };
  30121. /**
  30122. * Creates a ray that can be used to pick in the scene
  30123. * @param x defines the x coordinate of the origin (on-screen)
  30124. * @param y defines the y coordinate of the origin (on-screen)
  30125. * @param result defines the ray where to store the picking ray
  30126. * @param camera defines the camera to use for the picking
  30127. * @returns the current scene
  30128. */
  30129. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  30130. if (!BABYLON.PickingInfo) {
  30131. return this;
  30132. }
  30133. var engine = this._engine;
  30134. if (!camera) {
  30135. if (!this.activeCamera) {
  30136. throw new Error("Active camera not set");
  30137. }
  30138. camera = this.activeCamera;
  30139. }
  30140. var cameraViewport = camera.viewport;
  30141. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  30142. var identity = BABYLON.Matrix.Identity();
  30143. // Moving coordinates to local viewport world
  30144. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  30145. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  30146. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  30147. return this;
  30148. };
  30149. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  30150. if (!BABYLON.PickingInfo) {
  30151. return null;
  30152. }
  30153. var pickingInfo = null;
  30154. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  30155. var mesh = this.meshes[meshIndex];
  30156. if (predicate) {
  30157. if (!predicate(mesh)) {
  30158. continue;
  30159. }
  30160. }
  30161. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  30162. continue;
  30163. }
  30164. var world = mesh.getWorldMatrix();
  30165. var ray = rayFunction(world);
  30166. var result = mesh.intersects(ray, fastCheck);
  30167. if (!result || !result.hit) {
  30168. continue;
  30169. }
  30170. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance) {
  30171. continue;
  30172. }
  30173. pickingInfo = result;
  30174. if (fastCheck) {
  30175. break;
  30176. }
  30177. }
  30178. return pickingInfo || new BABYLON.PickingInfo();
  30179. };
  30180. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  30181. if (!BABYLON.PickingInfo) {
  30182. return null;
  30183. }
  30184. var pickingInfos = new Array();
  30185. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  30186. var mesh = this.meshes[meshIndex];
  30187. if (predicate) {
  30188. if (!predicate(mesh)) {
  30189. continue;
  30190. }
  30191. }
  30192. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  30193. continue;
  30194. }
  30195. var world = mesh.getWorldMatrix();
  30196. var ray = rayFunction(world);
  30197. var result = mesh.intersects(ray, false);
  30198. if (!result || !result.hit) {
  30199. continue;
  30200. }
  30201. pickingInfos.push(result);
  30202. }
  30203. return pickingInfos;
  30204. };
  30205. /** Launch a ray to try to pick a mesh in the scene
  30206. * @param x position on screen
  30207. * @param y position on screen
  30208. * @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
  30209. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  30210. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  30211. * @returns a PickingInfo
  30212. */
  30213. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  30214. var _this = this;
  30215. if (!BABYLON.PickingInfo) {
  30216. return null;
  30217. }
  30218. var result = this._internalPick(function (world) {
  30219. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  30220. return _this._tempPickingRay;
  30221. }, predicate, fastCheck);
  30222. if (result) {
  30223. result.ray = this.createPickingRay(x, y, BABYLON.Matrix.Identity(), camera || null);
  30224. }
  30225. return result;
  30226. };
  30227. /** Use the given ray to pick a mesh in the scene
  30228. * @param ray The ray to use to pick meshes
  30229. * @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
  30230. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  30231. * @returns a PickingInfo
  30232. */
  30233. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  30234. var _this = this;
  30235. var result = this._internalPick(function (world) {
  30236. if (!_this._pickWithRayInverseMatrix) {
  30237. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  30238. }
  30239. world.invertToRef(_this._pickWithRayInverseMatrix);
  30240. if (!_this._cachedRayForTransform) {
  30241. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  30242. }
  30243. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  30244. return _this._cachedRayForTransform;
  30245. }, predicate, fastCheck);
  30246. if (result) {
  30247. result.ray = ray;
  30248. }
  30249. return result;
  30250. };
  30251. /**
  30252. * Launch a ray to try to pick a mesh in the scene
  30253. * @param x X position on screen
  30254. * @param y Y position on screen
  30255. * @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
  30256. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  30257. * @returns an array of PickingInfo
  30258. */
  30259. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  30260. var _this = this;
  30261. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  30262. };
  30263. /**
  30264. * Launch a ray to try to pick a mesh in the scene
  30265. * @param ray Ray to use
  30266. * @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
  30267. * @returns an array of PickingInfo
  30268. */
  30269. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  30270. var _this = this;
  30271. return this._internalMultiPick(function (world) {
  30272. if (!_this._pickWithRayInverseMatrix) {
  30273. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  30274. }
  30275. world.invertToRef(_this._pickWithRayInverseMatrix);
  30276. if (!_this._cachedRayForTransform) {
  30277. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  30278. }
  30279. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  30280. return _this._cachedRayForTransform;
  30281. }, predicate);
  30282. };
  30283. /**
  30284. * Force the value of meshUnderPointer
  30285. * @param mesh defines the mesh to use
  30286. */
  30287. Scene.prototype.setPointerOverMesh = function (mesh) {
  30288. if (this._pointerOverMesh === mesh) {
  30289. return;
  30290. }
  30291. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  30292. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  30293. }
  30294. this._pointerOverMesh = mesh;
  30295. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  30296. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  30297. }
  30298. };
  30299. /**
  30300. * Gets the mesh under the pointer
  30301. * @returns a Mesh or null if no mesh is under the pointer
  30302. */
  30303. Scene.prototype.getPointerOverMesh = function () {
  30304. return this._pointerOverMesh;
  30305. };
  30306. // Misc.
  30307. /** @hidden */
  30308. Scene.prototype._rebuildGeometries = function () {
  30309. for (var _i = 0, _a = this.geometries; _i < _a.length; _i++) {
  30310. var geometry = _a[_i];
  30311. geometry._rebuild();
  30312. }
  30313. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  30314. var mesh = _c[_b];
  30315. mesh._rebuild();
  30316. }
  30317. if (this.postProcessManager) {
  30318. this.postProcessManager._rebuild();
  30319. }
  30320. for (var _d = 0, _e = this._components; _d < _e.length; _d++) {
  30321. var component = _e[_d];
  30322. component.rebuild();
  30323. }
  30324. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  30325. var system = _g[_f];
  30326. system.rebuild();
  30327. }
  30328. };
  30329. /** @hidden */
  30330. Scene.prototype._rebuildTextures = function () {
  30331. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  30332. var texture = _a[_i];
  30333. texture._rebuild();
  30334. }
  30335. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30336. };
  30337. // Tags
  30338. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  30339. if (tagsQuery === undefined) {
  30340. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  30341. return list;
  30342. }
  30343. var listByTags = [];
  30344. forEach = forEach || (function (item) { return; });
  30345. for (var i in list) {
  30346. var item = list[i];
  30347. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  30348. listByTags.push(item);
  30349. forEach(item);
  30350. }
  30351. }
  30352. return listByTags;
  30353. };
  30354. /**
  30355. * Get a list of meshes by tags
  30356. * @param tagsQuery defines the tags query to use
  30357. * @param forEach defines a predicate used to filter results
  30358. * @returns an array of Mesh
  30359. */
  30360. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  30361. return this._getByTags(this.meshes, tagsQuery, forEach);
  30362. };
  30363. /**
  30364. * Get a list of cameras by tags
  30365. * @param tagsQuery defines the tags query to use
  30366. * @param forEach defines a predicate used to filter results
  30367. * @returns an array of Camera
  30368. */
  30369. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  30370. return this._getByTags(this.cameras, tagsQuery, forEach);
  30371. };
  30372. /**
  30373. * Get a list of lights by tags
  30374. * @param tagsQuery defines the tags query to use
  30375. * @param forEach defines a predicate used to filter results
  30376. * @returns an array of Light
  30377. */
  30378. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  30379. return this._getByTags(this.lights, tagsQuery, forEach);
  30380. };
  30381. /**
  30382. * Get a list of materials by tags
  30383. * @param tagsQuery defines the tags query to use
  30384. * @param forEach defines a predicate used to filter results
  30385. * @returns an array of Material
  30386. */
  30387. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  30388. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  30389. };
  30390. /**
  30391. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  30392. * This allowed control for front to back rendering or reversly depending of the special needs.
  30393. *
  30394. * @param renderingGroupId The rendering group id corresponding to its index
  30395. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  30396. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  30397. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  30398. */
  30399. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  30400. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  30401. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  30402. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  30403. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  30404. };
  30405. /**
  30406. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  30407. *
  30408. * @param renderingGroupId The rendering group id corresponding to its index
  30409. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  30410. * @param depth Automatically clears depth between groups if true and autoClear is true.
  30411. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  30412. */
  30413. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  30414. if (depth === void 0) { depth = true; }
  30415. if (stencil === void 0) { stencil = true; }
  30416. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  30417. };
  30418. /**
  30419. * Gets the current auto clear configuration for one rendering group of the rendering
  30420. * manager.
  30421. * @param index the rendering group index to get the information for
  30422. * @returns The auto clear setup for the requested rendering group
  30423. */
  30424. Scene.prototype.getAutoClearDepthStencilSetup = function (index) {
  30425. return this._renderingManager.getAutoClearDepthStencilSetup(index);
  30426. };
  30427. Object.defineProperty(Scene.prototype, "blockMaterialDirtyMechanism", {
  30428. /** Gets or sets a boolean blocking all the calls to markAllMaterialsAsDirty (ie. the materials won't be updated if they are out of sync) */
  30429. get: function () {
  30430. return this._blockMaterialDirtyMechanism;
  30431. },
  30432. set: function (value) {
  30433. if (this._blockMaterialDirtyMechanism === value) {
  30434. return;
  30435. }
  30436. this._blockMaterialDirtyMechanism = value;
  30437. if (!value) { // Do a complete update
  30438. this.markAllMaterialsAsDirty(BABYLON.Material.AllDirtyFlag);
  30439. }
  30440. },
  30441. enumerable: true,
  30442. configurable: true
  30443. });
  30444. /**
  30445. * Will flag all materials as dirty to trigger new shader compilation
  30446. * @param flag defines the flag used to specify which material part must be marked as dirty
  30447. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  30448. */
  30449. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  30450. if (this._blockMaterialDirtyMechanism) {
  30451. return;
  30452. }
  30453. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  30454. var material = _a[_i];
  30455. if (predicate && !predicate(material)) {
  30456. continue;
  30457. }
  30458. material.markAsDirty(flag);
  30459. }
  30460. };
  30461. /** @hidden */
  30462. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useOfflineSupport, useArrayBuffer, onError) {
  30463. var _this = this;
  30464. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useOfflineSupport ? this.offlineProvider : undefined, useArrayBuffer, onError);
  30465. this._activeRequests.push(request);
  30466. request.onCompleteObservable.add(function (request) {
  30467. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  30468. });
  30469. return request;
  30470. };
  30471. /** @hidden */
  30472. Scene.prototype._loadFileAsync = function (url, useOfflineSupport, useArrayBuffer) {
  30473. var _this = this;
  30474. return new Promise(function (resolve, reject) {
  30475. _this._loadFile(url, function (data) {
  30476. resolve(data);
  30477. }, undefined, useOfflineSupport, useArrayBuffer, function (request, exception) {
  30478. reject(exception);
  30479. });
  30480. });
  30481. };
  30482. // Statics
  30483. Scene._uniqueIdCounter = 0;
  30484. /** The fog is deactivated */
  30485. Scene.FOGMODE_NONE = 0;
  30486. /** The fog density is following an exponential function */
  30487. Scene.FOGMODE_EXP = 1;
  30488. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  30489. Scene.FOGMODE_EXP2 = 2;
  30490. /** The fog density is following a linear function. */
  30491. Scene.FOGMODE_LINEAR = 3;
  30492. /**
  30493. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  30494. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  30495. */
  30496. Scene.MinDeltaTime = 1.0;
  30497. /**
  30498. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  30499. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  30500. */
  30501. Scene.MaxDeltaTime = 1000.0;
  30502. /** The distance in pixel that you have to move to prevent some events */
  30503. Scene.DragMovementThreshold = 10; // in pixels
  30504. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  30505. Scene.LongPressDelay = 500; // in milliseconds
  30506. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  30507. Scene.DoubleClickDelay = 300; // in milliseconds
  30508. /** If you need to check double click without raising a single click at first click, enable this flag */
  30509. Scene.ExclusiveDoubleClickMode = false;
  30510. return Scene;
  30511. }(BABYLON.AbstractScene));
  30512. BABYLON.Scene = Scene;
  30513. })(BABYLON || (BABYLON = {}));
  30514. //# sourceMappingURL=babylon.scene.js.map
  30515. var BABYLON;
  30516. (function (BABYLON) {
  30517. /**
  30518. * Set of assets to keep when moving a scene into an asset container.
  30519. */
  30520. var KeepAssets = /** @class */ (function (_super) {
  30521. __extends(KeepAssets, _super);
  30522. function KeepAssets() {
  30523. return _super !== null && _super.apply(this, arguments) || this;
  30524. }
  30525. return KeepAssets;
  30526. }(BABYLON.AbstractScene));
  30527. BABYLON.KeepAssets = KeepAssets;
  30528. /**
  30529. * Container with a set of assets that can be added or removed from a scene.
  30530. */
  30531. var AssetContainer = /** @class */ (function (_super) {
  30532. __extends(AssetContainer, _super);
  30533. /**
  30534. * Instantiates an AssetContainer.
  30535. * @param scene The scene the AssetContainer belongs to.
  30536. */
  30537. function AssetContainer(scene) {
  30538. var _this = _super.call(this) || this;
  30539. _this.scene = scene;
  30540. _this["sounds"] = [];
  30541. _this["effectLayers"] = [];
  30542. _this["layers"] = [];
  30543. _this["lensFlareSystems"] = [];
  30544. _this["proceduralTextures"] = [];
  30545. _this["reflectionProbes"] = [];
  30546. return _this;
  30547. }
  30548. /**
  30549. * Adds all the assets from the container to the scene.
  30550. */
  30551. AssetContainer.prototype.addAllToScene = function () {
  30552. var _this = this;
  30553. this.cameras.forEach(function (o) {
  30554. _this.scene.addCamera(o);
  30555. });
  30556. this.lights.forEach(function (o) {
  30557. _this.scene.addLight(o);
  30558. });
  30559. this.meshes.forEach(function (o) {
  30560. _this.scene.addMesh(o);
  30561. });
  30562. this.skeletons.forEach(function (o) {
  30563. _this.scene.addSkeleton(o);
  30564. });
  30565. this.animations.forEach(function (o) {
  30566. _this.scene.addAnimation(o);
  30567. });
  30568. this.animationGroups.forEach(function (o) {
  30569. _this.scene.addAnimationGroup(o);
  30570. });
  30571. this.multiMaterials.forEach(function (o) {
  30572. _this.scene.addMultiMaterial(o);
  30573. });
  30574. this.materials.forEach(function (o) {
  30575. _this.scene.addMaterial(o);
  30576. });
  30577. this.morphTargetManagers.forEach(function (o) {
  30578. _this.scene.addMorphTargetManager(o);
  30579. });
  30580. this.geometries.forEach(function (o) {
  30581. _this.scene.addGeometry(o);
  30582. });
  30583. this.transformNodes.forEach(function (o) {
  30584. _this.scene.addTransformNode(o);
  30585. });
  30586. this.actionManagers.forEach(function (o) {
  30587. _this.scene.addActionManager(o);
  30588. });
  30589. this.textures.forEach(function (o) {
  30590. _this.scene.addTexture(o);
  30591. });
  30592. this.reflectionProbes.forEach(function (o) {
  30593. _this.scene.addReflectionProbe(o);
  30594. });
  30595. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  30596. var component = _a[_i];
  30597. component.addFromContainer(this);
  30598. }
  30599. };
  30600. /**
  30601. * Removes all the assets in the container from the scene
  30602. */
  30603. AssetContainer.prototype.removeAllFromScene = function () {
  30604. var _this = this;
  30605. this.cameras.forEach(function (o) {
  30606. _this.scene.removeCamera(o);
  30607. });
  30608. this.lights.forEach(function (o) {
  30609. _this.scene.removeLight(o);
  30610. });
  30611. this.meshes.forEach(function (o) {
  30612. _this.scene.removeMesh(o);
  30613. });
  30614. this.skeletons.forEach(function (o) {
  30615. _this.scene.removeSkeleton(o);
  30616. });
  30617. this.animations.forEach(function (o) {
  30618. _this.scene.removeAnimation(o);
  30619. });
  30620. this.animationGroups.forEach(function (o) {
  30621. _this.scene.removeAnimationGroup(o);
  30622. });
  30623. this.multiMaterials.forEach(function (o) {
  30624. _this.scene.removeMultiMaterial(o);
  30625. });
  30626. this.materials.forEach(function (o) {
  30627. _this.scene.removeMaterial(o);
  30628. });
  30629. this.morphTargetManagers.forEach(function (o) {
  30630. _this.scene.removeMorphTargetManager(o);
  30631. });
  30632. this.geometries.forEach(function (o) {
  30633. _this.scene.removeGeometry(o);
  30634. });
  30635. this.transformNodes.forEach(function (o) {
  30636. _this.scene.removeTransformNode(o);
  30637. });
  30638. this.actionManagers.forEach(function (o) {
  30639. _this.scene.removeActionManager(o);
  30640. });
  30641. this.textures.forEach(function (o) {
  30642. _this.scene.removeTexture(o);
  30643. });
  30644. this.reflectionProbes.forEach(function (o) {
  30645. _this.scene.removeReflectionProbe(o);
  30646. });
  30647. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  30648. var component = _a[_i];
  30649. component.removeFromContainer(this);
  30650. }
  30651. };
  30652. /**
  30653. * Disposes all the assets in the container
  30654. */
  30655. AssetContainer.prototype.dispose = function () {
  30656. this.cameras.forEach(function (o) {
  30657. o.dispose();
  30658. });
  30659. this.lights.forEach(function (o) {
  30660. o.dispose();
  30661. });
  30662. this.meshes.forEach(function (o) {
  30663. o.dispose();
  30664. });
  30665. this.skeletons.forEach(function (o) {
  30666. o.dispose();
  30667. });
  30668. this.animationGroups.forEach(function (o) {
  30669. o.dispose();
  30670. });
  30671. this.multiMaterials.forEach(function (o) {
  30672. o.dispose();
  30673. });
  30674. this.materials.forEach(function (o) {
  30675. o.dispose();
  30676. });
  30677. this.geometries.forEach(function (o) {
  30678. o.dispose();
  30679. });
  30680. this.transformNodes.forEach(function (o) {
  30681. o.dispose();
  30682. });
  30683. this.actionManagers.forEach(function (o) {
  30684. o.dispose();
  30685. });
  30686. this.textures.forEach(function (o) {
  30687. o.dispose();
  30688. });
  30689. this.reflectionProbes.forEach(function (o) {
  30690. o.dispose();
  30691. });
  30692. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  30693. var component = _a[_i];
  30694. component.dispose();
  30695. }
  30696. };
  30697. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  30698. if (!sourceAssets) {
  30699. return;
  30700. }
  30701. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  30702. var asset = sourceAssets_1[_i];
  30703. var move = true;
  30704. if (keepAssets) {
  30705. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  30706. var keepAsset = keepAssets_1[_a];
  30707. if (asset === keepAsset) {
  30708. move = false;
  30709. break;
  30710. }
  30711. }
  30712. }
  30713. if (move) {
  30714. targetAssets.push(asset);
  30715. }
  30716. }
  30717. };
  30718. /**
  30719. * Removes all the assets contained in the scene and adds them to the container.
  30720. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  30721. */
  30722. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  30723. if (keepAssets === undefined) {
  30724. keepAssets = new KeepAssets();
  30725. }
  30726. for (var key in this) {
  30727. if (this.hasOwnProperty(key)) {
  30728. this[key] = this[key] || [];
  30729. this._moveAssets(this.scene[key], this[key], keepAssets[key]);
  30730. }
  30731. }
  30732. this.removeAllFromScene();
  30733. };
  30734. /**
  30735. * 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.
  30736. * @returns the root mesh
  30737. */
  30738. AssetContainer.prototype.createRootMesh = function () {
  30739. var rootMesh = new BABYLON.Mesh("assetContainerRootMesh", this.scene);
  30740. this.meshes.forEach(function (m) {
  30741. if (!m.parent) {
  30742. rootMesh.addChild(m);
  30743. }
  30744. });
  30745. this.meshes.unshift(rootMesh);
  30746. return rootMesh;
  30747. };
  30748. return AssetContainer;
  30749. }(BABYLON.AbstractScene));
  30750. BABYLON.AssetContainer = AssetContainer;
  30751. })(BABYLON || (BABYLON = {}));
  30752. //# sourceMappingURL=babylon.assetContainer.js.map
  30753. var BABYLON;
  30754. (function (BABYLON) {
  30755. /**
  30756. * Class used to store data that will be store in GPU memory
  30757. */
  30758. var Buffer = /** @class */ (function () {
  30759. /**
  30760. * Constructor
  30761. * @param engine the engine
  30762. * @param data the data to use for this buffer
  30763. * @param updatable whether the data is updatable
  30764. * @param stride the stride (optional)
  30765. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  30766. * @param instanced whether the buffer is instanced (optional)
  30767. * @param useBytes set to true if the stride in in bytes (optional)
  30768. */
  30769. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  30770. if (stride === void 0) { stride = 0; }
  30771. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  30772. if (instanced === void 0) { instanced = false; }
  30773. if (useBytes === void 0) { useBytes = false; }
  30774. if (engine instanceof BABYLON.Mesh) { // old versions of BABYLON.VertexBuffer accepted 'mesh' instead of 'engine'
  30775. this._engine = engine.getScene().getEngine();
  30776. }
  30777. else {
  30778. this._engine = engine;
  30779. }
  30780. this._updatable = updatable;
  30781. this._instanced = instanced;
  30782. this._data = data;
  30783. this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
  30784. if (!postponeInternalCreation) { // by default
  30785. this.create();
  30786. }
  30787. }
  30788. /**
  30789. * Create a new VertexBuffer based on the current buffer
  30790. * @param kind defines the vertex buffer kind (position, normal, etc.)
  30791. * @param offset defines offset in the buffer (0 by default)
  30792. * @param size defines the size in floats of attributes (position is 3 for instance)
  30793. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  30794. * @param instanced defines if the vertex buffer contains indexed data
  30795. * @param useBytes defines if the offset and stride are in bytes
  30796. * @returns the new vertex buffer
  30797. */
  30798. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  30799. if (useBytes === void 0) { useBytes = false; }
  30800. var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
  30801. var byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;
  30802. // a lot of these parameters are ignored as they are overriden by the buffer
  30803. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  30804. };
  30805. // Properties
  30806. /**
  30807. * Gets a boolean indicating if the Buffer is updatable?
  30808. * @returns true if the buffer is updatable
  30809. */
  30810. Buffer.prototype.isUpdatable = function () {
  30811. return this._updatable;
  30812. };
  30813. /**
  30814. * Gets current buffer's data
  30815. * @returns a DataArray or null
  30816. */
  30817. Buffer.prototype.getData = function () {
  30818. return this._data;
  30819. };
  30820. /**
  30821. * Gets underlying native buffer
  30822. * @returns underlying native buffer
  30823. */
  30824. Buffer.prototype.getBuffer = function () {
  30825. return this._buffer;
  30826. };
  30827. /**
  30828. * Gets the stride in float32 units (i.e. byte stride / 4).
  30829. * May not be an integer if the byte stride is not divisible by 4.
  30830. * DEPRECATED. Use byteStride instead.
  30831. * @returns the stride in float32 units
  30832. */
  30833. Buffer.prototype.getStrideSize = function () {
  30834. return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
  30835. };
  30836. // Methods
  30837. /**
  30838. * Store data into the buffer. If the buffer was already used it will be either recreated or updated depending on isUpdatable property
  30839. * @param data defines the data to store
  30840. */
  30841. Buffer.prototype.create = function (data) {
  30842. if (data === void 0) { data = null; }
  30843. if (!data && this._buffer) {
  30844. return; // nothing to do
  30845. }
  30846. data = data || this._data;
  30847. if (!data) {
  30848. return;
  30849. }
  30850. if (!this._buffer) { // create buffer
  30851. if (this._updatable) {
  30852. this._buffer = this._engine.createDynamicVertexBuffer(data);
  30853. this._data = data;
  30854. }
  30855. else {
  30856. this._buffer = this._engine.createVertexBuffer(data);
  30857. }
  30858. }
  30859. else if (this._updatable) { // update buffer
  30860. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  30861. this._data = data;
  30862. }
  30863. };
  30864. /** @hidden */
  30865. Buffer.prototype._rebuild = function () {
  30866. this._buffer = null;
  30867. this.create(this._data);
  30868. };
  30869. /**
  30870. * Update current buffer data
  30871. * @param data defines the data to store
  30872. */
  30873. Buffer.prototype.update = function (data) {
  30874. this.create(data);
  30875. };
  30876. /**
  30877. * Updates the data directly.
  30878. * @param data the new data
  30879. * @param offset the new offset
  30880. * @param vertexCount the vertex count (optional)
  30881. * @param useBytes set to true if the offset is in bytes
  30882. */
  30883. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  30884. if (useBytes === void 0) { useBytes = false; }
  30885. if (!this._buffer) {
  30886. return;
  30887. }
  30888. if (this._updatable) { // update buffer
  30889. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));
  30890. this._data = null;
  30891. }
  30892. };
  30893. /**
  30894. * Release all resources
  30895. */
  30896. Buffer.prototype.dispose = function () {
  30897. if (!this._buffer) {
  30898. return;
  30899. }
  30900. if (this._engine._releaseBuffer(this._buffer)) {
  30901. this._buffer = null;
  30902. }
  30903. };
  30904. return Buffer;
  30905. }());
  30906. BABYLON.Buffer = Buffer;
  30907. })(BABYLON || (BABYLON = {}));
  30908. //# sourceMappingURL=babylon.buffer.js.map
  30909. var BABYLON;
  30910. (function (BABYLON) {
  30911. /**
  30912. * Specialized buffer used to store vertex data
  30913. */
  30914. var VertexBuffer = /** @class */ (function () {
  30915. /**
  30916. * Constructor
  30917. * @param engine the engine
  30918. * @param data the data to use for this vertex buffer
  30919. * @param kind the vertex buffer kind
  30920. * @param updatable whether the data is updatable
  30921. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  30922. * @param stride the stride (optional)
  30923. * @param instanced whether the buffer is instanced (optional)
  30924. * @param offset the offset of the data (optional)
  30925. * @param size the number of components (optional)
  30926. * @param type the type of the component (optional)
  30927. * @param normalized whether the data contains normalized data (optional)
  30928. * @param useBytes set to true if stride and offset are in bytes (optional)
  30929. */
  30930. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  30931. if (normalized === void 0) { normalized = false; }
  30932. if (useBytes === void 0) { useBytes = false; }
  30933. if (data instanceof BABYLON.Buffer) {
  30934. this._buffer = data;
  30935. this._ownsBuffer = false;
  30936. }
  30937. else {
  30938. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  30939. this._ownsBuffer = true;
  30940. }
  30941. this._kind = kind;
  30942. if (type == undefined) {
  30943. var data_1 = this.getData();
  30944. this.type = VertexBuffer.FLOAT;
  30945. if (data_1 instanceof Int8Array) {
  30946. this.type = VertexBuffer.BYTE;
  30947. }
  30948. else if (data_1 instanceof Uint8Array) {
  30949. this.type = VertexBuffer.UNSIGNED_BYTE;
  30950. }
  30951. else if (data_1 instanceof Int16Array) {
  30952. this.type = VertexBuffer.SHORT;
  30953. }
  30954. else if (data_1 instanceof Uint16Array) {
  30955. this.type = VertexBuffer.UNSIGNED_SHORT;
  30956. }
  30957. else if (data_1 instanceof Int32Array) {
  30958. this.type = VertexBuffer.INT;
  30959. }
  30960. else if (data_1 instanceof Uint32Array) {
  30961. this.type = VertexBuffer.UNSIGNED_INT;
  30962. }
  30963. }
  30964. else {
  30965. this.type = type;
  30966. }
  30967. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  30968. if (useBytes) {
  30969. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  30970. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  30971. this.byteOffset = offset || 0;
  30972. }
  30973. else {
  30974. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  30975. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  30976. this.byteOffset = (offset || 0) * typeByteLength;
  30977. }
  30978. this.normalized = normalized;
  30979. this._instanced = instanced !== undefined ? instanced : false;
  30980. this._instanceDivisor = instanced ? 1 : 0;
  30981. }
  30982. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  30983. /**
  30984. * Gets or sets the instance divisor when in instanced mode
  30985. */
  30986. get: function () {
  30987. return this._instanceDivisor;
  30988. },
  30989. set: function (value) {
  30990. this._instanceDivisor = value;
  30991. if (value == 0) {
  30992. this._instanced = false;
  30993. }
  30994. else {
  30995. this._instanced = true;
  30996. }
  30997. },
  30998. enumerable: true,
  30999. configurable: true
  31000. });
  31001. /** @hidden */
  31002. VertexBuffer.prototype._rebuild = function () {
  31003. if (!this._buffer) {
  31004. return;
  31005. }
  31006. this._buffer._rebuild();
  31007. };
  31008. /**
  31009. * Returns the kind of the VertexBuffer (string)
  31010. * @returns a string
  31011. */
  31012. VertexBuffer.prototype.getKind = function () {
  31013. return this._kind;
  31014. };
  31015. // Properties
  31016. /**
  31017. * Gets a boolean indicating if the VertexBuffer is updatable?
  31018. * @returns true if the buffer is updatable
  31019. */
  31020. VertexBuffer.prototype.isUpdatable = function () {
  31021. return this._buffer.isUpdatable();
  31022. };
  31023. /**
  31024. * Gets current buffer's data
  31025. * @returns a DataArray or null
  31026. */
  31027. VertexBuffer.prototype.getData = function () {
  31028. return this._buffer.getData();
  31029. };
  31030. /**
  31031. * Gets underlying native buffer
  31032. * @returns underlying native buffer
  31033. */
  31034. VertexBuffer.prototype.getBuffer = function () {
  31035. return this._buffer.getBuffer();
  31036. };
  31037. /**
  31038. * Gets the stride in float32 units (i.e. byte stride / 4).
  31039. * May not be an integer if the byte stride is not divisible by 4.
  31040. * DEPRECATED. Use byteStride instead.
  31041. * @returns the stride in float32 units
  31042. */
  31043. VertexBuffer.prototype.getStrideSize = function () {
  31044. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  31045. };
  31046. /**
  31047. * Returns the offset as a multiple of the type byte length.
  31048. * DEPRECATED. Use byteOffset instead.
  31049. * @returns the offset in bytes
  31050. */
  31051. VertexBuffer.prototype.getOffset = function () {
  31052. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  31053. };
  31054. /**
  31055. * Returns the number of components per vertex attribute (integer)
  31056. * @returns the size in float
  31057. */
  31058. VertexBuffer.prototype.getSize = function () {
  31059. return this._size;
  31060. };
  31061. /**
  31062. * Gets a boolean indicating is the internal buffer of the VertexBuffer is instanced
  31063. * @returns true if this buffer is instanced
  31064. */
  31065. VertexBuffer.prototype.getIsInstanced = function () {
  31066. return this._instanced;
  31067. };
  31068. /**
  31069. * Returns the instancing divisor, zero for non-instanced (integer).
  31070. * @returns a number
  31071. */
  31072. VertexBuffer.prototype.getInstanceDivisor = function () {
  31073. return this._instanceDivisor;
  31074. };
  31075. // Methods
  31076. /**
  31077. * Store data into the buffer. If the buffer was already used it will be either recreated or updated depending on isUpdatable property
  31078. * @param data defines the data to store
  31079. */
  31080. VertexBuffer.prototype.create = function (data) {
  31081. this._buffer.create(data);
  31082. };
  31083. /**
  31084. * Updates the underlying buffer according to the passed numeric array or Float32Array.
  31085. * This function will create a new buffer if the current one is not updatable
  31086. * @param data defines the data to store
  31087. */
  31088. VertexBuffer.prototype.update = function (data) {
  31089. this._buffer.update(data);
  31090. };
  31091. /**
  31092. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  31093. * Returns the directly updated WebGLBuffer.
  31094. * @param data the new data
  31095. * @param offset the new offset
  31096. * @param useBytes set to true if the offset is in bytes
  31097. */
  31098. VertexBuffer.prototype.updateDirectly = function (data, offset, useBytes) {
  31099. if (useBytes === void 0) { useBytes = false; }
  31100. this._buffer.updateDirectly(data, offset, undefined, useBytes);
  31101. };
  31102. /**
  31103. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  31104. */
  31105. VertexBuffer.prototype.dispose = function () {
  31106. if (this._ownsBuffer) {
  31107. this._buffer.dispose();
  31108. }
  31109. };
  31110. /**
  31111. * Enumerates each value of this vertex buffer as numbers.
  31112. * @param count the number of values to enumerate
  31113. * @param callback the callback function called for each value
  31114. */
  31115. VertexBuffer.prototype.forEach = function (count, callback) {
  31116. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  31117. };
  31118. /**
  31119. * Deduces the stride given a kind.
  31120. * @param kind The kind string to deduce
  31121. * @returns The deduced stride
  31122. */
  31123. VertexBuffer.DeduceStride = function (kind) {
  31124. switch (kind) {
  31125. case VertexBuffer.UVKind:
  31126. case VertexBuffer.UV2Kind:
  31127. case VertexBuffer.UV3Kind:
  31128. case VertexBuffer.UV4Kind:
  31129. case VertexBuffer.UV5Kind:
  31130. case VertexBuffer.UV6Kind:
  31131. return 2;
  31132. case VertexBuffer.NormalKind:
  31133. case VertexBuffer.PositionKind:
  31134. return 3;
  31135. case VertexBuffer.ColorKind:
  31136. case VertexBuffer.MatricesIndicesKind:
  31137. case VertexBuffer.MatricesIndicesExtraKind:
  31138. case VertexBuffer.MatricesWeightsKind:
  31139. case VertexBuffer.MatricesWeightsExtraKind:
  31140. case VertexBuffer.TangentKind:
  31141. return 4;
  31142. default:
  31143. throw new Error("Invalid kind '" + kind + "'");
  31144. }
  31145. };
  31146. /**
  31147. * Gets the byte length of the given type.
  31148. * @param type the type
  31149. * @returns the number of bytes
  31150. */
  31151. VertexBuffer.GetTypeByteLength = function (type) {
  31152. switch (type) {
  31153. case VertexBuffer.BYTE:
  31154. case VertexBuffer.UNSIGNED_BYTE:
  31155. return 1;
  31156. case VertexBuffer.SHORT:
  31157. case VertexBuffer.UNSIGNED_SHORT:
  31158. return 2;
  31159. case VertexBuffer.INT:
  31160. case VertexBuffer.FLOAT:
  31161. return 4;
  31162. default:
  31163. throw new Error("Invalid type '" + type + "'");
  31164. }
  31165. };
  31166. /**
  31167. * Enumerates each value of the given parameters as numbers.
  31168. * @param data the data to enumerate
  31169. * @param byteOffset the byte offset of the data
  31170. * @param byteStride the byte stride of the data
  31171. * @param componentCount the number of components per element
  31172. * @param componentType the type of the component
  31173. * @param count the total number of components
  31174. * @param normalized whether the data is normalized
  31175. * @param callback the callback function called for each value
  31176. */
  31177. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  31178. if (data instanceof Array) {
  31179. var offset = byteOffset / 4;
  31180. var stride = byteStride / 4;
  31181. for (var index = 0; index < count; index += componentCount) {
  31182. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  31183. callback(data[offset + componentIndex], index + componentIndex);
  31184. }
  31185. offset += stride;
  31186. }
  31187. }
  31188. else {
  31189. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  31190. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  31191. for (var index = 0; index < count; index += componentCount) {
  31192. var componentByteOffset = byteOffset;
  31193. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  31194. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  31195. callback(value, index + componentIndex);
  31196. componentByteOffset += componentByteLength;
  31197. }
  31198. byteOffset += byteStride;
  31199. }
  31200. }
  31201. };
  31202. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  31203. switch (type) {
  31204. case VertexBuffer.BYTE: {
  31205. var value = dataView.getInt8(byteOffset);
  31206. if (normalized) {
  31207. value = Math.max(value / 127, -1);
  31208. }
  31209. return value;
  31210. }
  31211. case VertexBuffer.UNSIGNED_BYTE: {
  31212. var value = dataView.getUint8(byteOffset);
  31213. if (normalized) {
  31214. value = value / 255;
  31215. }
  31216. return value;
  31217. }
  31218. case VertexBuffer.SHORT: {
  31219. var value = dataView.getInt16(byteOffset, true);
  31220. if (normalized) {
  31221. value = Math.max(value / 16383, -1);
  31222. }
  31223. return value;
  31224. }
  31225. case VertexBuffer.UNSIGNED_SHORT: {
  31226. var value = dataView.getUint16(byteOffset, true);
  31227. if (normalized) {
  31228. value = value / 65535;
  31229. }
  31230. return value;
  31231. }
  31232. case VertexBuffer.FLOAT: {
  31233. return dataView.getFloat32(byteOffset, true);
  31234. }
  31235. default: {
  31236. throw new Error("Invalid component type " + type);
  31237. }
  31238. }
  31239. };
  31240. /**
  31241. * The byte type.
  31242. */
  31243. VertexBuffer.BYTE = 5120;
  31244. /**
  31245. * The unsigned byte type.
  31246. */
  31247. VertexBuffer.UNSIGNED_BYTE = 5121;
  31248. /**
  31249. * The short type.
  31250. */
  31251. VertexBuffer.SHORT = 5122;
  31252. /**
  31253. * The unsigned short type.
  31254. */
  31255. VertexBuffer.UNSIGNED_SHORT = 5123;
  31256. /**
  31257. * The integer type.
  31258. */
  31259. VertexBuffer.INT = 5124;
  31260. /**
  31261. * The unsigned integer type.
  31262. */
  31263. VertexBuffer.UNSIGNED_INT = 5125;
  31264. /**
  31265. * The float type.
  31266. */
  31267. VertexBuffer.FLOAT = 5126;
  31268. // Enums
  31269. /**
  31270. * Positions
  31271. */
  31272. VertexBuffer.PositionKind = "position";
  31273. /**
  31274. * Normals
  31275. */
  31276. VertexBuffer.NormalKind = "normal";
  31277. /**
  31278. * Tangents
  31279. */
  31280. VertexBuffer.TangentKind = "tangent";
  31281. /**
  31282. * Texture coordinates
  31283. */
  31284. VertexBuffer.UVKind = "uv";
  31285. /**
  31286. * Texture coordinates 2
  31287. */
  31288. VertexBuffer.UV2Kind = "uv2";
  31289. /**
  31290. * Texture coordinates 3
  31291. */
  31292. VertexBuffer.UV3Kind = "uv3";
  31293. /**
  31294. * Texture coordinates 4
  31295. */
  31296. VertexBuffer.UV4Kind = "uv4";
  31297. /**
  31298. * Texture coordinates 5
  31299. */
  31300. VertexBuffer.UV5Kind = "uv5";
  31301. /**
  31302. * Texture coordinates 6
  31303. */
  31304. VertexBuffer.UV6Kind = "uv6";
  31305. /**
  31306. * Colors
  31307. */
  31308. VertexBuffer.ColorKind = "color";
  31309. /**
  31310. * Matrix indices (for bones)
  31311. */
  31312. VertexBuffer.MatricesIndicesKind = "matricesIndices";
  31313. /**
  31314. * Matrix weights (for bones)
  31315. */
  31316. VertexBuffer.MatricesWeightsKind = "matricesWeights";
  31317. /**
  31318. * Additional matrix indices (for bones)
  31319. */
  31320. VertexBuffer.MatricesIndicesExtraKind = "matricesIndicesExtra";
  31321. /**
  31322. * Additional matrix weights (for bones)
  31323. */
  31324. VertexBuffer.MatricesWeightsExtraKind = "matricesWeightsExtra";
  31325. return VertexBuffer;
  31326. }());
  31327. BABYLON.VertexBuffer = VertexBuffer;
  31328. })(BABYLON || (BABYLON = {}));
  31329. //# sourceMappingURL=babylon.vertexBuffer.js.map
  31330. //# sourceMappingURL=babylon.internalTextureLoader.js.map
  31331. var BABYLON;
  31332. (function (BABYLON) {
  31333. /**
  31334. * Internal class used by the engine to get list of InternalTexture already bound to the GL context
  31335. */
  31336. var DummyInternalTextureTracker = /** @class */ (function () {
  31337. function DummyInternalTextureTracker() {
  31338. /**
  31339. * Gets or set the previous tracker in the list
  31340. */
  31341. this.previous = null;
  31342. /**
  31343. * Gets or set the next tracker in the list
  31344. */
  31345. this.next = null;
  31346. }
  31347. return DummyInternalTextureTracker;
  31348. }());
  31349. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  31350. })(BABYLON || (BABYLON = {}));
  31351. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  31352. var BABYLON;
  31353. (function (BABYLON) {
  31354. /**
  31355. * Class used to store data associated with WebGL texture data for the engine
  31356. * This class should not be used directly
  31357. */
  31358. var InternalTexture = /** @class */ (function () {
  31359. /**
  31360. * Creates a new InternalTexture
  31361. * @param engine defines the engine to use
  31362. * @param dataSource defines the type of data that will be used
  31363. * @param delayAllocation if the texture allocation should be delayed (default: false)
  31364. */
  31365. function InternalTexture(engine, dataSource, delayAllocation) {
  31366. if (delayAllocation === void 0) { delayAllocation = false; }
  31367. /**
  31368. * Observable called when the texture is loaded
  31369. */
  31370. this.onLoadedObservable = new BABYLON.Observable();
  31371. /**
  31372. * Gets or set the previous tracker in the list
  31373. */
  31374. this.previous = null;
  31375. /**
  31376. * Gets or set the next tracker in the list
  31377. */
  31378. this.next = null;
  31379. // Private
  31380. /** @hidden */
  31381. this._invertVScale = false;
  31382. /** @hidden */
  31383. this._initialSlot = -1;
  31384. /** @hidden */
  31385. this._designatedSlot = -1;
  31386. /** @hidden */
  31387. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  31388. /** @hidden */
  31389. this._comparisonFunction = 0;
  31390. /** @hidden */
  31391. this._sphericalPolynomial = null;
  31392. /** @hidden */
  31393. this._lodGenerationScale = 0;
  31394. /** @hidden */
  31395. this._lodGenerationOffset = 0;
  31396. /** @hidden */
  31397. this._isRGBD = false;
  31398. /** @hidden */
  31399. this._references = 1;
  31400. this._engine = engine;
  31401. this._dataSource = dataSource;
  31402. if (!delayAllocation) {
  31403. this._webGLTexture = engine._createTexture();
  31404. }
  31405. }
  31406. /**
  31407. * Gets the Engine the texture belongs to.
  31408. * @returns The babylon engine
  31409. */
  31410. InternalTexture.prototype.getEngine = function () {
  31411. return this._engine;
  31412. };
  31413. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  31414. /**
  31415. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  31416. */
  31417. get: function () {
  31418. return this._dataSource;
  31419. },
  31420. enumerable: true,
  31421. configurable: true
  31422. });
  31423. /**
  31424. * Increments the number of references (ie. the number of Texture that point to it)
  31425. */
  31426. InternalTexture.prototype.incrementReferences = function () {
  31427. this._references++;
  31428. };
  31429. /**
  31430. * Change the size of the texture (not the size of the content)
  31431. * @param width defines the new width
  31432. * @param height defines the new height
  31433. * @param depth defines the new depth (1 by default)
  31434. */
  31435. InternalTexture.prototype.updateSize = function (width, height, depth) {
  31436. if (depth === void 0) { depth = 1; }
  31437. this.width = width;
  31438. this.height = height;
  31439. this.depth = depth;
  31440. this.baseWidth = width;
  31441. this.baseHeight = height;
  31442. this.baseDepth = depth;
  31443. this._size = width * height * depth;
  31444. };
  31445. /** @hidden */
  31446. InternalTexture.prototype._rebuild = function () {
  31447. var _this = this;
  31448. var proxy;
  31449. this.isReady = false;
  31450. this._cachedCoordinatesMode = null;
  31451. this._cachedWrapU = null;
  31452. this._cachedWrapV = null;
  31453. this._cachedAnisotropicFilteringLevel = null;
  31454. switch (this._dataSource) {
  31455. case InternalTexture.DATASOURCE_TEMP:
  31456. return;
  31457. case InternalTexture.DATASOURCE_URL:
  31458. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  31459. proxy._swapAndDie(_this);
  31460. _this.isReady = true;
  31461. }, null, this._buffer, undefined, this.format);
  31462. return;
  31463. case InternalTexture.DATASOURCE_RAW:
  31464. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  31465. proxy._swapAndDie(this);
  31466. this.isReady = true;
  31467. return;
  31468. case InternalTexture.DATASOURCE_RAW3D:
  31469. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  31470. proxy._swapAndDie(this);
  31471. this.isReady = true;
  31472. return;
  31473. case InternalTexture.DATASOURCE_DYNAMIC:
  31474. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  31475. proxy._swapAndDie(this);
  31476. this._engine.updateDynamicTexture(this, this._engine.getRenderingCanvas(), this.invertY, undefined, undefined, true);
  31477. // The engine will make sure to update content so no need to flag it as isReady = true
  31478. return;
  31479. case InternalTexture.DATASOURCE_RENDERTARGET:
  31480. var options = new BABYLON.RenderTargetCreationOptions();
  31481. options.generateDepthBuffer = this._generateDepthBuffer;
  31482. options.generateMipMaps = this.generateMipMaps;
  31483. options.generateStencilBuffer = this._generateStencilBuffer;
  31484. options.samplingMode = this.samplingMode;
  31485. options.type = this.type;
  31486. if (this.isCube) {
  31487. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  31488. }
  31489. else {
  31490. var size = {
  31491. width: this.width,
  31492. height: this.height
  31493. };
  31494. proxy = this._engine.createRenderTargetTexture(size, options);
  31495. }
  31496. proxy._swapAndDie(this);
  31497. this.isReady = true;
  31498. return;
  31499. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  31500. var depthTextureOptions = {
  31501. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  31502. comparisonFunction: this._comparisonFunction,
  31503. generateStencil: this._generateStencilBuffer,
  31504. isCube: this.isCube
  31505. };
  31506. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  31507. proxy._swapAndDie(this);
  31508. this.isReady = true;
  31509. return;
  31510. case InternalTexture.DATASOURCE_CUBE:
  31511. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  31512. proxy._swapAndDie(_this);
  31513. _this.isReady = true;
  31514. }, null, this.format, this._extension);
  31515. return;
  31516. case InternalTexture.DATASOURCE_CUBERAW:
  31517. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  31518. proxy._swapAndDie(this);
  31519. this.isReady = true;
  31520. return;
  31521. case InternalTexture.DATASOURCE_CUBERAW_RGBD:
  31522. proxy = this._engine.createRawCubeTexture(null, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  31523. BABYLON.RawCubeTexture._UpdateRGBDAsync(proxy, this._bufferViewArrayArray, this._sphericalPolynomial, this._lodGenerationScale, this._lodGenerationOffset).then(function () {
  31524. proxy._swapAndDie(_this);
  31525. _this.isReady = true;
  31526. });
  31527. return;
  31528. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  31529. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  31530. if (proxy) {
  31531. proxy._swapAndDie(_this);
  31532. }
  31533. _this.isReady = true;
  31534. }, null, this.format, this._extension);
  31535. proxy._sphericalPolynomial = this._sphericalPolynomial;
  31536. return;
  31537. }
  31538. };
  31539. /** @hidden */
  31540. InternalTexture.prototype._swapAndDie = function (target) {
  31541. target._webGLTexture = this._webGLTexture;
  31542. if (this._framebuffer) {
  31543. target._framebuffer = this._framebuffer;
  31544. }
  31545. if (this._depthStencilBuffer) {
  31546. target._depthStencilBuffer = this._depthStencilBuffer;
  31547. }
  31548. if (this._lodTextureHigh) {
  31549. if (target._lodTextureHigh) {
  31550. target._lodTextureHigh.dispose();
  31551. }
  31552. target._lodTextureHigh = this._lodTextureHigh;
  31553. }
  31554. if (this._lodTextureMid) {
  31555. if (target._lodTextureMid) {
  31556. target._lodTextureMid.dispose();
  31557. }
  31558. target._lodTextureMid = this._lodTextureMid;
  31559. }
  31560. if (this._lodTextureLow) {
  31561. if (target._lodTextureLow) {
  31562. target._lodTextureLow.dispose();
  31563. }
  31564. target._lodTextureLow = this._lodTextureLow;
  31565. }
  31566. var cache = this._engine.getLoadedTexturesCache();
  31567. var index = cache.indexOf(this);
  31568. if (index !== -1) {
  31569. cache.splice(index, 1);
  31570. }
  31571. };
  31572. /**
  31573. * Dispose the current allocated resources
  31574. */
  31575. InternalTexture.prototype.dispose = function () {
  31576. if (!this._webGLTexture) {
  31577. return;
  31578. }
  31579. this._references--;
  31580. if (this._references === 0) {
  31581. this._engine._releaseTexture(this);
  31582. this._webGLTexture = null;
  31583. this.previous = null;
  31584. this.next = null;
  31585. }
  31586. };
  31587. /**
  31588. * The source of the texture data is unknown
  31589. */
  31590. InternalTexture.DATASOURCE_UNKNOWN = 0;
  31591. /**
  31592. * Texture data comes from an URL
  31593. */
  31594. InternalTexture.DATASOURCE_URL = 1;
  31595. /**
  31596. * Texture data is only used for temporary storage
  31597. */
  31598. InternalTexture.DATASOURCE_TEMP = 2;
  31599. /**
  31600. * Texture data comes from raw data (ArrayBuffer)
  31601. */
  31602. InternalTexture.DATASOURCE_RAW = 3;
  31603. /**
  31604. * Texture content is dynamic (video or dynamic texture)
  31605. */
  31606. InternalTexture.DATASOURCE_DYNAMIC = 4;
  31607. /**
  31608. * Texture content is generated by rendering to it
  31609. */
  31610. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  31611. /**
  31612. * Texture content is part of a multi render target process
  31613. */
  31614. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  31615. /**
  31616. * Texture data comes from a cube data file
  31617. */
  31618. InternalTexture.DATASOURCE_CUBE = 7;
  31619. /**
  31620. * Texture data comes from a raw cube data
  31621. */
  31622. InternalTexture.DATASOURCE_CUBERAW = 8;
  31623. /**
  31624. * Texture data come from a prefiltered cube data file
  31625. */
  31626. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  31627. /**
  31628. * Texture content is raw 3D data
  31629. */
  31630. InternalTexture.DATASOURCE_RAW3D = 10;
  31631. /**
  31632. * Texture content is a depth texture
  31633. */
  31634. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  31635. /**
  31636. * Texture data comes from a raw cube data encoded with RGBD
  31637. */
  31638. InternalTexture.DATASOURCE_CUBERAW_RGBD = 12;
  31639. return InternalTexture;
  31640. }());
  31641. BABYLON.InternalTexture = InternalTexture;
  31642. })(BABYLON || (BABYLON = {}));
  31643. //# sourceMappingURL=babylon.internalTexture.js.map
  31644. var BABYLON;
  31645. (function (BABYLON) {
  31646. /**
  31647. * Base class of all the textures in babylon.
  31648. * It groups all the common properties the materials, post process, lights... might need
  31649. * in order to make a correct use of the texture.
  31650. */
  31651. var BaseTexture = /** @class */ (function () {
  31652. /**
  31653. * Instantiates a new BaseTexture.
  31654. * Base class of all the textures in babylon.
  31655. * It groups all the common properties the materials, post process, lights... might need
  31656. * in order to make a correct use of the texture.
  31657. * @param scene Define the scene the texture blongs to
  31658. */
  31659. function BaseTexture(scene) {
  31660. /**
  31661. * Gets or sets an object used to store user defined information.
  31662. */
  31663. this.metadata = null;
  31664. /**
  31665. * For internal use only. Please do not use.
  31666. */
  31667. this.reservedDataStore = null;
  31668. this._hasAlpha = false;
  31669. /**
  31670. * Defines if the alpha value should be determined via the rgb values.
  31671. * If true the luminance of the pixel might be used to find the corresponding alpha value.
  31672. */
  31673. this.getAlphaFromRGB = false;
  31674. /**
  31675. * Intensity or strength of the texture.
  31676. * It is commonly used by materials to fine tune the intensity of the texture
  31677. */
  31678. this.level = 1;
  31679. /**
  31680. * Define the UV chanel to use starting from 0 and defaulting to 0.
  31681. * This is part of the texture as textures usually maps to one uv set.
  31682. */
  31683. this.coordinatesIndex = 0;
  31684. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  31685. /**
  31686. * | Value | Type | Description |
  31687. * | ----- | ------------------ | ----------- |
  31688. * | 0 | CLAMP_ADDRESSMODE | |
  31689. * | 1 | WRAP_ADDRESSMODE | |
  31690. * | 2 | MIRROR_ADDRESSMODE | |
  31691. */
  31692. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  31693. /**
  31694. * | Value | Type | Description |
  31695. * | ----- | ------------------ | ----------- |
  31696. * | 0 | CLAMP_ADDRESSMODE | |
  31697. * | 1 | WRAP_ADDRESSMODE | |
  31698. * | 2 | MIRROR_ADDRESSMODE | |
  31699. */
  31700. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  31701. /**
  31702. * | Value | Type | Description |
  31703. * | ----- | ------------------ | ----------- |
  31704. * | 0 | CLAMP_ADDRESSMODE | |
  31705. * | 1 | WRAP_ADDRESSMODE | |
  31706. * | 2 | MIRROR_ADDRESSMODE | |
  31707. */
  31708. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  31709. /**
  31710. * With compliant hardware and browser (supporting anisotropic filtering)
  31711. * this defines the level of anisotropic filtering in the texture.
  31712. * The higher the better but the slower. This defaults to 4 as it seems to be the best tradeoff.
  31713. */
  31714. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  31715. /**
  31716. * Define if the texture contains data in gamma space (most of the png/jpg aside bump).
  31717. * HDR texture are usually stored in linear space.
  31718. * This only impacts the PBR and Background materials
  31719. */
  31720. this.gammaSpace = true;
  31721. /**
  31722. * Is Z inverted in the texture (useful in a cube texture).
  31723. */
  31724. this.invertZ = false;
  31725. /**
  31726. * @hidden
  31727. */
  31728. this.lodLevelInAlpha = false;
  31729. /**
  31730. * Define if the texture is a render target.
  31731. */
  31732. this.isRenderTarget = false;
  31733. /**
  31734. * Define the list of animation attached to the texture.
  31735. */
  31736. this.animations = new Array();
  31737. /**
  31738. * An event triggered when the texture is disposed.
  31739. */
  31740. this.onDisposeObservable = new BABYLON.Observable();
  31741. /**
  31742. * Define the current state of the loading sequence when in delayed load mode.
  31743. */
  31744. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  31745. this._cachedSize = BABYLON.Size.Zero();
  31746. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  31747. if (this._scene) {
  31748. this.uniqueId = this._scene.getUniqueId();
  31749. this._scene.addTexture(this);
  31750. }
  31751. this._uid = null;
  31752. }
  31753. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  31754. get: function () {
  31755. return this._hasAlpha;
  31756. },
  31757. /**
  31758. * Define if the texture is having a usable alpha value (can be use for transparency or glossiness for instance).
  31759. */
  31760. set: function (value) {
  31761. if (this._hasAlpha === value) {
  31762. return;
  31763. }
  31764. this._hasAlpha = value;
  31765. if (this._scene) {
  31766. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  31767. }
  31768. },
  31769. enumerable: true,
  31770. configurable: true
  31771. });
  31772. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  31773. get: function () {
  31774. return this._coordinatesMode;
  31775. },
  31776. /**
  31777. * How a texture is mapped.
  31778. *
  31779. * | Value | Type | Description |
  31780. * | ----- | ----------------------------------- | ----------- |
  31781. * | 0 | EXPLICIT_MODE | |
  31782. * | 1 | SPHERICAL_MODE | |
  31783. * | 2 | PLANAR_MODE | |
  31784. * | 3 | CUBIC_MODE | |
  31785. * | 4 | PROJECTION_MODE | |
  31786. * | 5 | SKYBOX_MODE | |
  31787. * | 6 | INVCUBIC_MODE | |
  31788. * | 7 | EQUIRECTANGULAR_MODE | |
  31789. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  31790. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  31791. */
  31792. set: function (value) {
  31793. if (this._coordinatesMode === value) {
  31794. return;
  31795. }
  31796. this._coordinatesMode = value;
  31797. if (this._scene) {
  31798. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  31799. }
  31800. },
  31801. enumerable: true,
  31802. configurable: true
  31803. });
  31804. Object.defineProperty(BaseTexture.prototype, "isCube", {
  31805. /**
  31806. * Define if the texture is a cube texture or if false a 2d texture.
  31807. */
  31808. get: function () {
  31809. if (!this._texture) {
  31810. return false;
  31811. }
  31812. return this._texture.isCube;
  31813. },
  31814. set: function (value) {
  31815. if (!this._texture) {
  31816. return;
  31817. }
  31818. this._texture.isCube = value;
  31819. },
  31820. enumerable: true,
  31821. configurable: true
  31822. });
  31823. Object.defineProperty(BaseTexture.prototype, "is3D", {
  31824. /**
  31825. * Define if the texture is a 3d texture (webgl 2) or if false a 2d texture.
  31826. */
  31827. get: function () {
  31828. if (!this._texture) {
  31829. return false;
  31830. }
  31831. return this._texture.is3D;
  31832. },
  31833. set: function (value) {
  31834. if (!this._texture) {
  31835. return;
  31836. }
  31837. this._texture.is3D = value;
  31838. },
  31839. enumerable: true,
  31840. configurable: true
  31841. });
  31842. Object.defineProperty(BaseTexture.prototype, "isRGBD", {
  31843. /**
  31844. * Gets whether or not the texture contains RGBD data.
  31845. */
  31846. get: function () {
  31847. return this._texture != null && this._texture._isRGBD;
  31848. },
  31849. enumerable: true,
  31850. configurable: true
  31851. });
  31852. Object.defineProperty(BaseTexture.prototype, "noMipmap", {
  31853. /**
  31854. * Are mip maps generated for this texture or not.
  31855. */
  31856. get: function () {
  31857. return false;
  31858. },
  31859. enumerable: true,
  31860. configurable: true
  31861. });
  31862. Object.defineProperty(BaseTexture.prototype, "lodGenerationOffset", {
  31863. /**
  31864. * With prefiltered texture, defined the offset used during the prefiltering steps.
  31865. */
  31866. get: function () {
  31867. if (this._texture) {
  31868. return this._texture._lodGenerationOffset;
  31869. }
  31870. return 0.0;
  31871. },
  31872. set: function (value) {
  31873. if (this._texture) {
  31874. this._texture._lodGenerationOffset = value;
  31875. }
  31876. },
  31877. enumerable: true,
  31878. configurable: true
  31879. });
  31880. Object.defineProperty(BaseTexture.prototype, "lodGenerationScale", {
  31881. /**
  31882. * With prefiltered texture, defined the scale used during the prefiltering steps.
  31883. */
  31884. get: function () {
  31885. if (this._texture) {
  31886. return this._texture._lodGenerationScale;
  31887. }
  31888. return 0.0;
  31889. },
  31890. set: function (value) {
  31891. if (this._texture) {
  31892. this._texture._lodGenerationScale = value;
  31893. }
  31894. },
  31895. enumerable: true,
  31896. configurable: true
  31897. });
  31898. Object.defineProperty(BaseTexture.prototype, "uid", {
  31899. /**
  31900. * Define the unique id of the texture in the scene.
  31901. */
  31902. get: function () {
  31903. if (!this._uid) {
  31904. this._uid = BABYLON.Tools.RandomId();
  31905. }
  31906. return this._uid;
  31907. },
  31908. enumerable: true,
  31909. configurable: true
  31910. });
  31911. /**
  31912. * Return a string representation of the texture.
  31913. * @returns the texture as a string
  31914. */
  31915. BaseTexture.prototype.toString = function () {
  31916. return this.name;
  31917. };
  31918. /**
  31919. * Get the class name of the texture.
  31920. * @returns "BaseTexture"
  31921. */
  31922. BaseTexture.prototype.getClassName = function () {
  31923. return "BaseTexture";
  31924. };
  31925. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  31926. /**
  31927. * Callback triggered when the texture has been disposed.
  31928. * Kept for back compatibility, you can use the onDisposeObservable instead.
  31929. */
  31930. set: function (callback) {
  31931. if (this._onDisposeObserver) {
  31932. this.onDisposeObservable.remove(this._onDisposeObserver);
  31933. }
  31934. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  31935. },
  31936. enumerable: true,
  31937. configurable: true
  31938. });
  31939. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  31940. /**
  31941. * Define if the texture is preventinga material to render or not.
  31942. * If not and the texture is not ready, the engine will use a default black texture instead.
  31943. */
  31944. get: function () {
  31945. return true;
  31946. },
  31947. enumerable: true,
  31948. configurable: true
  31949. });
  31950. /**
  31951. * Get the scene the texture belongs to.
  31952. * @returns the scene or null if undefined
  31953. */
  31954. BaseTexture.prototype.getScene = function () {
  31955. return this._scene;
  31956. };
  31957. /**
  31958. * Get the texture transform matrix used to offset tile the texture for istance.
  31959. * @returns the transformation matrix
  31960. */
  31961. BaseTexture.prototype.getTextureMatrix = function () {
  31962. return BABYLON.Matrix.IdentityReadOnly;
  31963. };
  31964. /**
  31965. * Get the texture reflection matrix used to rotate/transform the reflection.
  31966. * @returns the reflection matrix
  31967. */
  31968. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  31969. return BABYLON.Matrix.IdentityReadOnly;
  31970. };
  31971. /**
  31972. * Get the underlying lower level texture from Babylon.
  31973. * @returns the insternal texture
  31974. */
  31975. BaseTexture.prototype.getInternalTexture = function () {
  31976. return this._texture;
  31977. };
  31978. /**
  31979. * Get if the texture is ready to be consumed (either it is ready or it is not blocking)
  31980. * @returns true if ready or not blocking
  31981. */
  31982. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  31983. return !this.isBlocking || this.isReady();
  31984. };
  31985. /**
  31986. * Get if the texture is ready to be used (downloaded, converted, mip mapped...).
  31987. * @returns true if fully ready
  31988. */
  31989. BaseTexture.prototype.isReady = function () {
  31990. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  31991. this.delayLoad();
  31992. return false;
  31993. }
  31994. if (this._texture) {
  31995. return this._texture.isReady;
  31996. }
  31997. return false;
  31998. };
  31999. /**
  32000. * Get the size of the texture.
  32001. * @returns the texture size.
  32002. */
  32003. BaseTexture.prototype.getSize = function () {
  32004. if (this._texture) {
  32005. if (this._texture.width) {
  32006. this._cachedSize.width = this._texture.width;
  32007. this._cachedSize.height = this._texture.height;
  32008. return this._cachedSize;
  32009. }
  32010. if (this._texture._size) {
  32011. this._cachedSize.width = this._texture._size;
  32012. this._cachedSize.height = this._texture._size;
  32013. return this._cachedSize;
  32014. }
  32015. }
  32016. return this._cachedSize;
  32017. };
  32018. /**
  32019. * Get the base size of the texture.
  32020. * It can be different from the size if the texture has been resized for POT for instance
  32021. * @returns the base size
  32022. */
  32023. BaseTexture.prototype.getBaseSize = function () {
  32024. if (!this.isReady() || !this._texture) {
  32025. return BABYLON.Size.Zero();
  32026. }
  32027. if (this._texture._size) {
  32028. return new BABYLON.Size(this._texture._size, this._texture._size);
  32029. }
  32030. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  32031. };
  32032. /**
  32033. * Update the sampling mode of the texture.
  32034. * Default is Trilinear mode.
  32035. *
  32036. * | Value | Type | Description |
  32037. * | ----- | ------------------ | ----------- |
  32038. * | 1 | NEAREST_SAMPLINGMODE or NEAREST_NEAREST_MIPLINEAR | Nearest is: mag = nearest, min = nearest, mip = linear |
  32039. * | 2 | BILINEAR_SAMPLINGMODE or LINEAR_LINEAR_MIPNEAREST | Bilinear is: mag = linear, min = linear, mip = nearest |
  32040. * | 3 | TRILINEAR_SAMPLINGMODE or LINEAR_LINEAR_MIPLINEAR | Trilinear is: mag = linear, min = linear, mip = linear |
  32041. * | 4 | NEAREST_NEAREST_MIPNEAREST | |
  32042. * | 5 | NEAREST_LINEAR_MIPNEAREST | |
  32043. * | 6 | NEAREST_LINEAR_MIPLINEAR | |
  32044. * | 7 | NEAREST_LINEAR | |
  32045. * | 8 | NEAREST_NEAREST | |
  32046. * | 9 | LINEAR_NEAREST_MIPNEAREST | |
  32047. * | 10 | LINEAR_NEAREST_MIPLINEAR | |
  32048. * | 11 | LINEAR_LINEAR | |
  32049. * | 12 | LINEAR_NEAREST | |
  32050. *
  32051. * > _mag_: magnification filter (close to the viewer)
  32052. * > _min_: minification filter (far from the viewer)
  32053. * > _mip_: filter used between mip map levels
  32054. *@param samplingMode Define the new sampling mode of the texture
  32055. */
  32056. BaseTexture.prototype.updateSamplingMode = function (samplingMode) {
  32057. if (!this._texture) {
  32058. return;
  32059. }
  32060. var scene = this.getScene();
  32061. if (!scene) {
  32062. return;
  32063. }
  32064. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  32065. };
  32066. /**
  32067. * Scales the texture if is `canRescale()`
  32068. * @param ratio the resize factor we want to use to rescale
  32069. */
  32070. BaseTexture.prototype.scale = function (ratio) {
  32071. };
  32072. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  32073. /**
  32074. * Get if the texture can rescale.
  32075. */
  32076. get: function () {
  32077. return false;
  32078. },
  32079. enumerable: true,
  32080. configurable: true
  32081. });
  32082. /** @hidden */
  32083. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  32084. if (!this._scene) {
  32085. return null;
  32086. }
  32087. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  32088. for (var index = 0; index < texturesCache.length; index++) {
  32089. var texturesCacheEntry = texturesCache[index];
  32090. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  32091. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  32092. texturesCacheEntry.incrementReferences();
  32093. return texturesCacheEntry;
  32094. }
  32095. }
  32096. }
  32097. return null;
  32098. };
  32099. /** @hidden */
  32100. BaseTexture.prototype._rebuild = function () {
  32101. };
  32102. /**
  32103. * Triggers the load sequence in delayed load mode.
  32104. */
  32105. BaseTexture.prototype.delayLoad = function () {
  32106. };
  32107. /**
  32108. * Clones the texture.
  32109. * @returns the cloned texture
  32110. */
  32111. BaseTexture.prototype.clone = function () {
  32112. return null;
  32113. };
  32114. Object.defineProperty(BaseTexture.prototype, "textureType", {
  32115. /**
  32116. * Get the texture underlying type (INT, FLOAT...)
  32117. */
  32118. get: function () {
  32119. if (!this._texture) {
  32120. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  32121. }
  32122. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  32123. },
  32124. enumerable: true,
  32125. configurable: true
  32126. });
  32127. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  32128. /**
  32129. * Get the texture underlying format (RGB, RGBA...)
  32130. */
  32131. get: function () {
  32132. if (!this._texture) {
  32133. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  32134. }
  32135. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  32136. },
  32137. enumerable: true,
  32138. configurable: true
  32139. });
  32140. /**
  32141. * Reads the pixels stored in the webgl texture and returns them as an ArrayBuffer.
  32142. * This will returns an RGBA array buffer containing either in values (0-255) or
  32143. * float values (0-1) depending of the underlying buffer type.
  32144. * @param faceIndex defines the face of the texture to read (in case of cube texture)
  32145. * @param level defines the LOD level of the texture to read (in case of Mip Maps)
  32146. * @param buffer defines a user defined buffer to fill with data (can be null)
  32147. * @returns The Array buffer containing the pixels data.
  32148. */
  32149. BaseTexture.prototype.readPixels = function (faceIndex, level, buffer) {
  32150. if (faceIndex === void 0) { faceIndex = 0; }
  32151. if (level === void 0) { level = 0; }
  32152. if (buffer === void 0) { buffer = null; }
  32153. if (!this._texture) {
  32154. return null;
  32155. }
  32156. var size = this.getSize();
  32157. var width = size.width;
  32158. var height = size.height;
  32159. var scene = this.getScene();
  32160. if (!scene) {
  32161. return null;
  32162. }
  32163. var engine = scene.getEngine();
  32164. if (level != 0) {
  32165. width = width / Math.pow(2, level);
  32166. height = height / Math.pow(2, level);
  32167. width = Math.round(width);
  32168. height = Math.round(height);
  32169. }
  32170. if (this._texture.isCube) {
  32171. return engine._readTexturePixels(this._texture, width, height, faceIndex, level, buffer);
  32172. }
  32173. return engine._readTexturePixels(this._texture, width, height, -1, level, buffer);
  32174. };
  32175. /**
  32176. * Release and destroy the underlying lower level texture aka internalTexture.
  32177. */
  32178. BaseTexture.prototype.releaseInternalTexture = function () {
  32179. if (this._texture) {
  32180. this._texture.dispose();
  32181. this._texture = null;
  32182. }
  32183. };
  32184. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  32185. /**
  32186. * Get the polynomial representation of the texture data.
  32187. * This is mainly use as a fast way to recover IBL Diffuse irradiance data.
  32188. * @see https://learnopengl.com/PBR/IBL/Diffuse-irradiance
  32189. */
  32190. get: function () {
  32191. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  32192. return null;
  32193. }
  32194. if (!this._texture._sphericalPolynomial) {
  32195. this._texture._sphericalPolynomial =
  32196. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  32197. }
  32198. return this._texture._sphericalPolynomial;
  32199. },
  32200. set: function (value) {
  32201. if (this._texture) {
  32202. this._texture._sphericalPolynomial = value;
  32203. }
  32204. },
  32205. enumerable: true,
  32206. configurable: true
  32207. });
  32208. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  32209. /** @hidden */
  32210. get: function () {
  32211. if (this._texture) {
  32212. return this._texture._lodTextureHigh;
  32213. }
  32214. return null;
  32215. },
  32216. enumerable: true,
  32217. configurable: true
  32218. });
  32219. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  32220. /** @hidden */
  32221. get: function () {
  32222. if (this._texture) {
  32223. return this._texture._lodTextureMid;
  32224. }
  32225. return null;
  32226. },
  32227. enumerable: true,
  32228. configurable: true
  32229. });
  32230. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  32231. /** @hidden */
  32232. get: function () {
  32233. if (this._texture) {
  32234. return this._texture._lodTextureLow;
  32235. }
  32236. return null;
  32237. },
  32238. enumerable: true,
  32239. configurable: true
  32240. });
  32241. /**
  32242. * Dispose the texture and release its associated resources.
  32243. */
  32244. BaseTexture.prototype.dispose = function () {
  32245. if (!this._scene) {
  32246. return;
  32247. }
  32248. // Animations
  32249. this._scene.stopAnimation(this);
  32250. // Remove from scene
  32251. this._scene._removePendingData(this);
  32252. var index = this._scene.textures.indexOf(this);
  32253. if (index >= 0) {
  32254. this._scene.textures.splice(index, 1);
  32255. }
  32256. this._scene.onTextureRemovedObservable.notifyObservers(this);
  32257. if (this._texture === undefined) {
  32258. return;
  32259. }
  32260. // Release
  32261. this.releaseInternalTexture();
  32262. // Callback
  32263. this.onDisposeObservable.notifyObservers(this);
  32264. this.onDisposeObservable.clear();
  32265. };
  32266. /**
  32267. * Serialize the texture into a JSON representation that can be parsed later on.
  32268. * @returns the JSON representation of the texture
  32269. */
  32270. BaseTexture.prototype.serialize = function () {
  32271. if (!this.name) {
  32272. return null;
  32273. }
  32274. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  32275. // Animations
  32276. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  32277. return serializationObject;
  32278. };
  32279. /**
  32280. * Helper function to be called back once a list of texture contains only ready textures.
  32281. * @param textures Define the list of textures to wait for
  32282. * @param callback Define the callback triggered once the entire list will be ready
  32283. */
  32284. BaseTexture.WhenAllReady = function (textures, callback) {
  32285. var numRemaining = textures.length;
  32286. if (numRemaining === 0) {
  32287. callback();
  32288. return;
  32289. }
  32290. var _loop_1 = function () {
  32291. texture = textures[i];
  32292. if (texture.isReady()) {
  32293. if (--numRemaining === 0) {
  32294. callback();
  32295. }
  32296. }
  32297. else {
  32298. onLoadObservable = texture.onLoadObservable;
  32299. var onLoadCallback_1 = function () {
  32300. onLoadObservable.removeCallback(onLoadCallback_1);
  32301. if (--numRemaining === 0) {
  32302. callback();
  32303. }
  32304. };
  32305. onLoadObservable.add(onLoadCallback_1);
  32306. }
  32307. };
  32308. var texture, onLoadObservable;
  32309. for (var i = 0; i < textures.length; i++) {
  32310. _loop_1();
  32311. }
  32312. };
  32313. /**
  32314. * Default anisotropic filtering level for the application.
  32315. * It is set to 4 as a good tradeoff between perf and quality.
  32316. */
  32317. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  32318. __decorate([
  32319. BABYLON.serialize()
  32320. ], BaseTexture.prototype, "uniqueId", void 0);
  32321. __decorate([
  32322. BABYLON.serialize()
  32323. ], BaseTexture.prototype, "name", void 0);
  32324. __decorate([
  32325. BABYLON.serialize()
  32326. ], BaseTexture.prototype, "metadata", void 0);
  32327. __decorate([
  32328. BABYLON.serialize("hasAlpha")
  32329. ], BaseTexture.prototype, "_hasAlpha", void 0);
  32330. __decorate([
  32331. BABYLON.serialize()
  32332. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  32333. __decorate([
  32334. BABYLON.serialize()
  32335. ], BaseTexture.prototype, "level", void 0);
  32336. __decorate([
  32337. BABYLON.serialize()
  32338. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  32339. __decorate([
  32340. BABYLON.serialize("coordinatesMode")
  32341. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  32342. __decorate([
  32343. BABYLON.serialize()
  32344. ], BaseTexture.prototype, "wrapU", void 0);
  32345. __decorate([
  32346. BABYLON.serialize()
  32347. ], BaseTexture.prototype, "wrapV", void 0);
  32348. __decorate([
  32349. BABYLON.serialize()
  32350. ], BaseTexture.prototype, "wrapR", void 0);
  32351. __decorate([
  32352. BABYLON.serialize()
  32353. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  32354. __decorate([
  32355. BABYLON.serialize()
  32356. ], BaseTexture.prototype, "isCube", null);
  32357. __decorate([
  32358. BABYLON.serialize()
  32359. ], BaseTexture.prototype, "is3D", null);
  32360. __decorate([
  32361. BABYLON.serialize()
  32362. ], BaseTexture.prototype, "gammaSpace", void 0);
  32363. __decorate([
  32364. BABYLON.serialize()
  32365. ], BaseTexture.prototype, "invertZ", void 0);
  32366. __decorate([
  32367. BABYLON.serialize()
  32368. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  32369. __decorate([
  32370. BABYLON.serialize()
  32371. ], BaseTexture.prototype, "lodGenerationOffset", null);
  32372. __decorate([
  32373. BABYLON.serialize()
  32374. ], BaseTexture.prototype, "lodGenerationScale", null);
  32375. __decorate([
  32376. BABYLON.serialize()
  32377. ], BaseTexture.prototype, "isRenderTarget", void 0);
  32378. return BaseTexture;
  32379. }());
  32380. BABYLON.BaseTexture = BaseTexture;
  32381. })(BABYLON || (BABYLON = {}));
  32382. //# sourceMappingURL=babylon.baseTexture.js.map
  32383. var BABYLON;
  32384. (function (BABYLON) {
  32385. /**
  32386. * This represents a texture in babylon. It can be easily loaded from a network, base64 or html input.
  32387. * @see http://doc.babylonjs.com/babylon101/materials#texture
  32388. */
  32389. var Texture = /** @class */ (function (_super) {
  32390. __extends(Texture, _super);
  32391. /**
  32392. * Instantiates a new texture.
  32393. * This represents a texture in babylon. It can be easily loaded from a network, base64 or html input.
  32394. * @see http://doc.babylonjs.com/babylon101/materials#texture
  32395. * @param url define the url of the picture to load as a texture
  32396. * @param scene define the scene the texture will belong to
  32397. * @param noMipmap define if the texture will require mip maps or not
  32398. * @param invertY define if the texture needs to be inverted on the y axis during loading
  32399. * @param samplingMode define the sampling mode we want for the texture while fectching from it (Texture.NEAREST_SAMPLINGMODE...)
  32400. * @param onLoad define a callback triggered when the texture has been loaded
  32401. * @param onError define a callback triggered when an error occurred during the loading session
  32402. * @param buffer define the buffer to load the texture from in case the texture is loaded from a buffer representation
  32403. * @param deleteBuffer define if the buffer we are loading the texture from should be deleted after load
  32404. * @param format define the format of the texture we are trying to load (Engine.TEXTUREFORMAT_RGBA...)
  32405. */
  32406. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  32407. if (noMipmap === void 0) { noMipmap = false; }
  32408. if (invertY === void 0) { invertY = true; }
  32409. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  32410. if (onLoad === void 0) { onLoad = null; }
  32411. if (onError === void 0) { onError = null; }
  32412. if (buffer === void 0) { buffer = null; }
  32413. if (deleteBuffer === void 0) { deleteBuffer = false; }
  32414. var _this = _super.call(this, scene) || this;
  32415. /**
  32416. * Define an offset on the texture to offset the u coordinates of the UVs
  32417. * @see http://doc.babylonjs.com/how_to/more_materials#offsetting
  32418. */
  32419. _this.uOffset = 0;
  32420. /**
  32421. * Define an offset on the texture to offset the v coordinates of the UVs
  32422. * @see http://doc.babylonjs.com/how_to/more_materials#offsetting
  32423. */
  32424. _this.vOffset = 0;
  32425. /**
  32426. * Define an offset on the texture to scale the u coordinates of the UVs
  32427. * @see http://doc.babylonjs.com/how_to/more_materials#tiling
  32428. */
  32429. _this.uScale = 1.0;
  32430. /**
  32431. * Define an offset on the texture to scale the v coordinates of the UVs
  32432. * @see http://doc.babylonjs.com/how_to/more_materials#tiling
  32433. */
  32434. _this.vScale = 1.0;
  32435. /**
  32436. * Define an offset on the texture to rotate around the u coordinates of the UVs
  32437. * @see http://doc.babylonjs.com/how_to/more_materials
  32438. */
  32439. _this.uAng = 0;
  32440. /**
  32441. * Define an offset on the texture to rotate around the v coordinates of the UVs
  32442. * @see http://doc.babylonjs.com/how_to/more_materials
  32443. */
  32444. _this.vAng = 0;
  32445. /**
  32446. * Define an offset on the texture to rotate around the w coordinates of the UVs (in case of 3d texture)
  32447. * @see http://doc.babylonjs.com/how_to/more_materials
  32448. */
  32449. _this.wAng = 0;
  32450. /**
  32451. * Defines the center of rotation (U)
  32452. */
  32453. _this.uRotationCenter = 0.5;
  32454. /**
  32455. * Defines the center of rotation (V)
  32456. */
  32457. _this.vRotationCenter = 0.5;
  32458. /**
  32459. * Defines the center of rotation (W)
  32460. */
  32461. _this.wRotationCenter = 0.5;
  32462. /** @hidden */
  32463. _this._initialSamplingMode = Texture.BILINEAR_SAMPLINGMODE;
  32464. /**
  32465. * Observable triggered once the texture has been loaded.
  32466. */
  32467. _this.onLoadObservable = new BABYLON.Observable();
  32468. _this._isBlocking = true;
  32469. _this.name = url || "";
  32470. _this.url = url;
  32471. _this._noMipmap = noMipmap;
  32472. _this._invertY = invertY;
  32473. _this._initialSamplingMode = samplingMode;
  32474. _this._buffer = buffer;
  32475. _this._deleteBuffer = deleteBuffer;
  32476. if (format) {
  32477. _this._format = format;
  32478. }
  32479. scene = _this.getScene();
  32480. if (!scene) {
  32481. return _this;
  32482. }
  32483. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  32484. var load = function () {
  32485. if (_this._texture && _this._texture._invertVScale) {
  32486. _this.vScale = -1;
  32487. }
  32488. if (_this.onLoadObservable.hasObservers()) {
  32489. _this.onLoadObservable.notifyObservers(_this);
  32490. }
  32491. if (onLoad) {
  32492. onLoad();
  32493. }
  32494. if (!_this.isBlocking && scene) {
  32495. scene.resetCachedMaterial();
  32496. }
  32497. };
  32498. if (!_this.url) {
  32499. _this._delayedOnLoad = load;
  32500. _this._delayedOnError = onError;
  32501. return _this;
  32502. }
  32503. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  32504. if (!_this._texture) {
  32505. if (!scene.useDelayedTextureLoading) {
  32506. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, samplingMode, load, onError, _this._buffer, undefined, _this._format);
  32507. if (deleteBuffer) {
  32508. delete _this._buffer;
  32509. }
  32510. }
  32511. else {
  32512. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  32513. _this._delayedOnLoad = load;
  32514. _this._delayedOnError = onError;
  32515. }
  32516. }
  32517. else {
  32518. if (_this._texture.isReady) {
  32519. BABYLON.Tools.SetImmediate(function () { return load(); });
  32520. }
  32521. else {
  32522. _this._texture.onLoadedObservable.add(load);
  32523. }
  32524. }
  32525. return _this;
  32526. }
  32527. Object.defineProperty(Texture.prototype, "noMipmap", {
  32528. /**
  32529. * Are mip maps generated for this texture or not.
  32530. */
  32531. get: function () {
  32532. return this._noMipmap;
  32533. },
  32534. enumerable: true,
  32535. configurable: true
  32536. });
  32537. Object.defineProperty(Texture.prototype, "isBlocking", {
  32538. get: function () {
  32539. return this._isBlocking;
  32540. },
  32541. /**
  32542. * Is the texture preventing material to render while loading.
  32543. * If false, a default texture will be used instead of the loading one during the preparation step.
  32544. */
  32545. set: function (value) {
  32546. this._isBlocking = value;
  32547. },
  32548. enumerable: true,
  32549. configurable: true
  32550. });
  32551. Object.defineProperty(Texture.prototype, "samplingMode", {
  32552. /**
  32553. * Get the current sampling mode associated with the texture.
  32554. */
  32555. get: function () {
  32556. if (!this._texture) {
  32557. return this._initialSamplingMode;
  32558. }
  32559. return this._texture.samplingMode;
  32560. },
  32561. enumerable: true,
  32562. configurable: true
  32563. });
  32564. Object.defineProperty(Texture.prototype, "invertY", {
  32565. /**
  32566. * Gets a boolean indicating if the texture needs to be inverted on the y axis during loading
  32567. */
  32568. get: function () {
  32569. return this._invertY;
  32570. },
  32571. enumerable: true,
  32572. configurable: true
  32573. });
  32574. /**
  32575. * Update the url (and optional buffer) of this texture if url was null during construction.
  32576. * @param url the url of the texture
  32577. * @param buffer the buffer of the texture (defaults to null)
  32578. * @param onLoad callback called when the texture is loaded (defaults to null)
  32579. */
  32580. Texture.prototype.updateURL = function (url, buffer, onLoad) {
  32581. if (buffer === void 0) { buffer = null; }
  32582. if (this.url) {
  32583. this.releaseInternalTexture();
  32584. this.getScene().markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  32585. }
  32586. this.url = url;
  32587. this._buffer = buffer;
  32588. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  32589. if (onLoad) {
  32590. this._delayedOnLoad = onLoad;
  32591. }
  32592. this.delayLoad();
  32593. };
  32594. /**
  32595. * Finish the loading sequence of a texture flagged as delayed load.
  32596. * @hidden
  32597. */
  32598. Texture.prototype.delayLoad = function () {
  32599. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  32600. return;
  32601. }
  32602. var scene = this.getScene();
  32603. if (!scene) {
  32604. return;
  32605. }
  32606. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32607. this._texture = this._getFromCache(this.url, this._noMipmap, this.samplingMode);
  32608. if (!this._texture) {
  32609. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this.samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  32610. if (this._deleteBuffer) {
  32611. delete this._buffer;
  32612. }
  32613. }
  32614. else {
  32615. if (this._delayedOnLoad) {
  32616. if (this._texture.isReady) {
  32617. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  32618. }
  32619. else {
  32620. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  32621. }
  32622. }
  32623. }
  32624. this._delayedOnLoad = null;
  32625. this._delayedOnError = null;
  32626. };
  32627. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  32628. x *= this.uScale;
  32629. y *= this.vScale;
  32630. x -= this.uRotationCenter * this.uScale;
  32631. y -= this.vRotationCenter * this.vScale;
  32632. z -= this.wRotationCenter;
  32633. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  32634. t.x += this.uRotationCenter * this.uScale + this.uOffset;
  32635. t.y += this.vRotationCenter * this.vScale + this.vOffset;
  32636. t.z += this.wRotationCenter;
  32637. };
  32638. /**
  32639. * Get the current texture matrix which includes the requested offsetting, tiling and rotation components.
  32640. * @returns the transform matrix of the texture.
  32641. */
  32642. Texture.prototype.getTextureMatrix = function () {
  32643. var _this = this;
  32644. if (this.uOffset === this._cachedUOffset &&
  32645. this.vOffset === this._cachedVOffset &&
  32646. this.uScale === this._cachedUScale &&
  32647. this.vScale === this._cachedVScale &&
  32648. this.uAng === this._cachedUAng &&
  32649. this.vAng === this._cachedVAng &&
  32650. this.wAng === this._cachedWAng) {
  32651. return this._cachedTextureMatrix;
  32652. }
  32653. this._cachedUOffset = this.uOffset;
  32654. this._cachedVOffset = this.vOffset;
  32655. this._cachedUScale = this.uScale;
  32656. this._cachedVScale = this.vScale;
  32657. this._cachedUAng = this.uAng;
  32658. this._cachedVAng = this.vAng;
  32659. this._cachedWAng = this.wAng;
  32660. if (!this._cachedTextureMatrix) {
  32661. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  32662. this._rowGenerationMatrix = new BABYLON.Matrix();
  32663. this._t0 = BABYLON.Vector3.Zero();
  32664. this._t1 = BABYLON.Vector3.Zero();
  32665. this._t2 = BABYLON.Vector3.Zero();
  32666. }
  32667. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  32668. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  32669. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  32670. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  32671. this._t1.subtractInPlace(this._t0);
  32672. this._t2.subtractInPlace(this._t0);
  32673. BABYLON.Matrix.FromValuesToRef(this._t1.x, this._t1.y, this._t1.z, 0.0, this._t2.x, this._t2.y, this._t2.z, 0.0, this._t0.x, this._t0.y, this._t0.z, 0.0, 0.0, 0.0, 0.0, 1.0, this._cachedTextureMatrix);
  32674. var scene = this.getScene();
  32675. if (!scene) {
  32676. return this._cachedTextureMatrix;
  32677. }
  32678. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  32679. return mat.hasTexture(_this);
  32680. });
  32681. return this._cachedTextureMatrix;
  32682. };
  32683. /**
  32684. * Get the current matrix used to apply reflection. This is useful to rotate an environment texture for instance.
  32685. * @returns The reflection texture transform
  32686. */
  32687. Texture.prototype.getReflectionTextureMatrix = function () {
  32688. var _this = this;
  32689. var scene = this.getScene();
  32690. if (!scene) {
  32691. return this._cachedTextureMatrix;
  32692. }
  32693. if (this.uOffset === this._cachedUOffset &&
  32694. this.vOffset === this._cachedVOffset &&
  32695. this.uScale === this._cachedUScale &&
  32696. this.vScale === this._cachedVScale &&
  32697. this.coordinatesMode === this._cachedCoordinatesMode) {
  32698. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  32699. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  32700. return this._cachedTextureMatrix;
  32701. }
  32702. }
  32703. else {
  32704. return this._cachedTextureMatrix;
  32705. }
  32706. }
  32707. if (!this._cachedTextureMatrix) {
  32708. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  32709. }
  32710. if (!this._projectionModeMatrix) {
  32711. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  32712. }
  32713. this._cachedUOffset = this.uOffset;
  32714. this._cachedVOffset = this.vOffset;
  32715. this._cachedUScale = this.uScale;
  32716. this._cachedVScale = this.vScale;
  32717. this._cachedCoordinatesMode = this.coordinatesMode;
  32718. switch (this.coordinatesMode) {
  32719. case Texture.PLANAR_MODE:
  32720. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  32721. this._cachedTextureMatrix[0] = this.uScale;
  32722. this._cachedTextureMatrix[5] = this.vScale;
  32723. this._cachedTextureMatrix[12] = this.uOffset;
  32724. this._cachedTextureMatrix[13] = this.vOffset;
  32725. break;
  32726. case Texture.PROJECTION_MODE:
  32727. BABYLON.Matrix.FromValuesToRef(0.5, 0.0, 0.0, 0.0, 0.0, -0.5, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.5, 0.5, 1.0, 1.0, this._projectionModeMatrix);
  32728. var projectionMatrix = scene.getProjectionMatrix();
  32729. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  32730. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  32731. break;
  32732. default:
  32733. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  32734. break;
  32735. }
  32736. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  32737. return (mat.getActiveTextures().indexOf(_this) !== -1);
  32738. });
  32739. return this._cachedTextureMatrix;
  32740. };
  32741. /**
  32742. * Clones the texture.
  32743. * @returns the cloned texture
  32744. */
  32745. Texture.prototype.clone = function () {
  32746. var _this = this;
  32747. return BABYLON.SerializationHelper.Clone(function () {
  32748. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this.samplingMode);
  32749. }, this);
  32750. };
  32751. /**
  32752. * Serialize the texture to a JSON representation we can easily use in the resepective Parse function.
  32753. * @returns The JSON representation of the texture
  32754. */
  32755. Texture.prototype.serialize = function () {
  32756. var serializationObject = _super.prototype.serialize.call(this);
  32757. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  32758. serializationObject.base64String = this._buffer;
  32759. serializationObject.name = serializationObject.name.replace("data:", "");
  32760. }
  32761. serializationObject.invertY = this._invertY;
  32762. serializationObject.samplingMode = this.samplingMode;
  32763. return serializationObject;
  32764. };
  32765. /**
  32766. * Get the current class name of the texture useful for serialization or dynamic coding.
  32767. * @returns "Texture"
  32768. */
  32769. Texture.prototype.getClassName = function () {
  32770. return "Texture";
  32771. };
  32772. /**
  32773. * Dispose the texture and release its associated resources.
  32774. */
  32775. Texture.prototype.dispose = function () {
  32776. _super.prototype.dispose.call(this);
  32777. this.onLoadObservable.clear();
  32778. this._delayedOnLoad = null;
  32779. this._delayedOnError = null;
  32780. };
  32781. /**
  32782. * Parse the JSON representation of a texture in order to recreate the texture in the given scene.
  32783. * @param parsedTexture Define the JSON representation of the texture
  32784. * @param scene Define the scene the parsed texture should be instantiated in
  32785. * @param rootUrl Define the root url of the parsing sequence in the case of relative dependencies
  32786. * @returns The parsed texture if successful
  32787. */
  32788. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  32789. if (parsedTexture.customType) {
  32790. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  32791. // Update Sampling Mode
  32792. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  32793. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  32794. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  32795. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  32796. }
  32797. }
  32798. return parsedCustomTexture;
  32799. }
  32800. if (parsedTexture.isCube && !parsedTexture.isRenderTarget) {
  32801. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  32802. }
  32803. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  32804. return null;
  32805. }
  32806. var texture = BABYLON.SerializationHelper.Parse(function () {
  32807. var generateMipMaps = true;
  32808. if (parsedTexture.noMipmap) {
  32809. generateMipMaps = false;
  32810. }
  32811. if (parsedTexture.mirrorPlane) {
  32812. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  32813. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  32814. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  32815. return mirrorTexture;
  32816. }
  32817. else if (parsedTexture.isRenderTarget) {
  32818. var renderTargetTexture = null;
  32819. if (parsedTexture.isCube) {
  32820. // Search for an existing reflection probe (which contains a cube render target texture)
  32821. if (scene.reflectionProbes) {
  32822. for (var index = 0; index < scene.reflectionProbes.length; index++) {
  32823. var probe = scene.reflectionProbes[index];
  32824. if (probe.name === parsedTexture.name) {
  32825. return probe.cubeTexture;
  32826. }
  32827. }
  32828. }
  32829. }
  32830. else {
  32831. renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  32832. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  32833. }
  32834. return renderTargetTexture;
  32835. }
  32836. else {
  32837. var texture;
  32838. if (parsedTexture.base64String) {
  32839. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  32840. }
  32841. else {
  32842. var url = rootUrl + parsedTexture.name;
  32843. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  32844. url = parsedTexture.url;
  32845. }
  32846. texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);
  32847. }
  32848. return texture;
  32849. }
  32850. }, parsedTexture, scene);
  32851. // Update Sampling Mode
  32852. if (parsedTexture.samplingMode) {
  32853. var sampling = parsedTexture.samplingMode;
  32854. if (texture && texture.samplingMode !== sampling) {
  32855. texture.updateSamplingMode(sampling);
  32856. }
  32857. }
  32858. // Animations
  32859. if (texture && parsedTexture.animations) {
  32860. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  32861. var parsedAnimation = parsedTexture.animations[animationIndex];
  32862. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  32863. }
  32864. }
  32865. return texture;
  32866. };
  32867. /**
  32868. * Creates a texture from its base 64 representation.
  32869. * @param data Define the base64 payload without the data: prefix
  32870. * @param name Define the name of the texture in the scene useful fo caching purpose for instance
  32871. * @param scene Define the scene the texture should belong to
  32872. * @param noMipmap Forces the texture to not create mip map information if true
  32873. * @param invertY define if the texture needs to be inverted on the y axis during loading
  32874. * @param samplingMode define the sampling mode we want for the texture while fectching from it (Texture.NEAREST_SAMPLINGMODE...)
  32875. * @param onLoad define a callback triggered when the texture has been loaded
  32876. * @param onError define a callback triggered when an error occurred during the loading session
  32877. * @param format define the format of the texture we are trying to load (Engine.TEXTUREFORMAT_RGBA...)
  32878. * @returns the created texture
  32879. */
  32880. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  32881. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  32882. if (onLoad === void 0) { onLoad = null; }
  32883. if (onError === void 0) { onError = null; }
  32884. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  32885. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  32886. };
  32887. /**
  32888. * Creates a texture from its data: representation. (data: will be added in case only the payload has been passed in)
  32889. * @param data Define the base64 payload without the data: prefix
  32890. * @param name Define the name of the texture in the scene useful fo caching purpose for instance
  32891. * @param buffer define the buffer to load the texture from in case the texture is loaded from a buffer representation
  32892. * @param scene Define the scene the texture should belong to
  32893. * @param deleteBuffer define if the buffer we are loading the texture from should be deleted after load
  32894. * @param noMipmap Forces the texture to not create mip map information if true
  32895. * @param invertY define if the texture needs to be inverted on the y axis during loading
  32896. * @param samplingMode define the sampling mode we want for the texture while fectching from it (Texture.NEAREST_SAMPLINGMODE...)
  32897. * @param onLoad define a callback triggered when the texture has been loaded
  32898. * @param onError define a callback triggered when an error occurred during the loading session
  32899. * @param format define the format of the texture we are trying to load (Engine.TEXTUREFORMAT_RGBA...)
  32900. * @returns the created texture
  32901. */
  32902. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  32903. if (deleteBuffer === void 0) { deleteBuffer = false; }
  32904. if (noMipmap === void 0) { noMipmap = false; }
  32905. if (invertY === void 0) { invertY = true; }
  32906. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  32907. if (onLoad === void 0) { onLoad = null; }
  32908. if (onError === void 0) { onError = null; }
  32909. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  32910. if (name.substr(0, 5) !== "data:") {
  32911. name = "data:" + name;
  32912. }
  32913. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  32914. };
  32915. /** nearest is mag = nearest and min = nearest and mip = linear */
  32916. Texture.NEAREST_SAMPLINGMODE = BABYLON.Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  32917. /** nearest is mag = nearest and min = nearest and mip = linear */
  32918. Texture.NEAREST_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR; // nearest is mag = nearest and min = nearest and mip = linear
  32919. /** Bilinear is mag = linear and min = linear and mip = nearest */
  32920. Texture.BILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_BILINEAR_SAMPLINGMODE;
  32921. /** Bilinear is mag = linear and min = linear and mip = nearest */
  32922. Texture.LINEAR_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST; // Bilinear is mag = linear and min = linear and mip = nearest
  32923. /** Trilinear is mag = linear and min = linear and mip = linear */
  32924. Texture.TRILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  32925. /** Trilinear is mag = linear and min = linear and mip = linear */
  32926. Texture.LINEAR_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR; // Trilinear is mag = linear and min = linear and mip = linear
  32927. /** mag = nearest and min = nearest and mip = nearest */
  32928. Texture.NEAREST_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST;
  32929. /** mag = nearest and min = linear and mip = nearest */
  32930. Texture.NEAREST_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST;
  32931. /** mag = nearest and min = linear and mip = linear */
  32932. Texture.NEAREST_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR;
  32933. /** mag = nearest and min = linear and mip = none */
  32934. Texture.NEAREST_LINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR;
  32935. /** mag = nearest and min = nearest and mip = none */
  32936. Texture.NEAREST_NEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST;
  32937. /** mag = linear and min = nearest and mip = nearest */
  32938. Texture.LINEAR_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST;
  32939. /** mag = linear and min = nearest and mip = linear */
  32940. Texture.LINEAR_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR;
  32941. /** mag = linear and min = linear and mip = none */
  32942. Texture.LINEAR_LINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR;
  32943. /** mag = linear and min = nearest and mip = none */
  32944. Texture.LINEAR_NEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST;
  32945. /** Explicit coordinates mode */
  32946. Texture.EXPLICIT_MODE = BABYLON.Engine.TEXTURE_EXPLICIT_MODE;
  32947. /** Spherical coordinates mode */
  32948. Texture.SPHERICAL_MODE = BABYLON.Engine.TEXTURE_SPHERICAL_MODE;
  32949. /** Planar coordinates mode */
  32950. Texture.PLANAR_MODE = BABYLON.Engine.TEXTURE_PLANAR_MODE;
  32951. /** Cubic coordinates mode */
  32952. Texture.CUBIC_MODE = BABYLON.Engine.TEXTURE_CUBIC_MODE;
  32953. /** Projection coordinates mode */
  32954. Texture.PROJECTION_MODE = BABYLON.Engine.TEXTURE_PROJECTION_MODE;
  32955. /** Inverse Cubic coordinates mode */
  32956. Texture.SKYBOX_MODE = BABYLON.Engine.TEXTURE_SKYBOX_MODE;
  32957. /** Inverse Cubic coordinates mode */
  32958. Texture.INVCUBIC_MODE = BABYLON.Engine.TEXTURE_INVCUBIC_MODE;
  32959. /** Equirectangular coordinates mode */
  32960. Texture.EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_EQUIRECTANGULAR_MODE;
  32961. /** Equirectangular Fixed coordinates mode */
  32962. Texture.FIXED_EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE;
  32963. /** Equirectangular Fixed Mirrored coordinates mode */
  32964. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE;
  32965. /** Texture is not repeating outside of 0..1 UVs */
  32966. Texture.CLAMP_ADDRESSMODE = BABYLON.Engine.TEXTURE_CLAMP_ADDRESSMODE;
  32967. /** Texture is repeating outside of 0..1 UVs */
  32968. Texture.WRAP_ADDRESSMODE = BABYLON.Engine.TEXTURE_WRAP_ADDRESSMODE;
  32969. /** Texture is repeating and mirrored */
  32970. Texture.MIRROR_ADDRESSMODE = BABYLON.Engine.TEXTURE_MIRROR_ADDRESSMODE;
  32971. /**
  32972. * 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
  32973. */
  32974. Texture.UseSerializedUrlIfAny = false;
  32975. __decorate([
  32976. BABYLON.serialize()
  32977. ], Texture.prototype, "url", void 0);
  32978. __decorate([
  32979. BABYLON.serialize()
  32980. ], Texture.prototype, "uOffset", void 0);
  32981. __decorate([
  32982. BABYLON.serialize()
  32983. ], Texture.prototype, "vOffset", void 0);
  32984. __decorate([
  32985. BABYLON.serialize()
  32986. ], Texture.prototype, "uScale", void 0);
  32987. __decorate([
  32988. BABYLON.serialize()
  32989. ], Texture.prototype, "vScale", void 0);
  32990. __decorate([
  32991. BABYLON.serialize()
  32992. ], Texture.prototype, "uAng", void 0);
  32993. __decorate([
  32994. BABYLON.serialize()
  32995. ], Texture.prototype, "vAng", void 0);
  32996. __decorate([
  32997. BABYLON.serialize()
  32998. ], Texture.prototype, "wAng", void 0);
  32999. __decorate([
  33000. BABYLON.serialize()
  33001. ], Texture.prototype, "uRotationCenter", void 0);
  33002. __decorate([
  33003. BABYLON.serialize()
  33004. ], Texture.prototype, "vRotationCenter", void 0);
  33005. __decorate([
  33006. BABYLON.serialize()
  33007. ], Texture.prototype, "wRotationCenter", void 0);
  33008. __decorate([
  33009. BABYLON.serialize()
  33010. ], Texture.prototype, "isBlocking", null);
  33011. return Texture;
  33012. }(BABYLON.BaseTexture));
  33013. BABYLON.Texture = Texture;
  33014. })(BABYLON || (BABYLON = {}));
  33015. //# sourceMappingURL=babylon.texture.js.map
  33016. var BABYLON;
  33017. (function (BABYLON) {
  33018. /**
  33019. * @hidden
  33020. **/
  33021. var _CreationDataStorage = /** @class */ (function () {
  33022. function _CreationDataStorage() {
  33023. }
  33024. return _CreationDataStorage;
  33025. }());
  33026. BABYLON._CreationDataStorage = _CreationDataStorage;
  33027. /**
  33028. * @hidden
  33029. **/
  33030. var _InstanceDataStorage = /** @class */ (function () {
  33031. function _InstanceDataStorage() {
  33032. this.visibleInstances = {};
  33033. this.renderIdForInstances = new Array();
  33034. this.batchCache = new _InstancesBatch();
  33035. this.instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  33036. }
  33037. return _InstanceDataStorage;
  33038. }());
  33039. /**
  33040. * @hidden
  33041. **/
  33042. var _InstancesBatch = /** @class */ (function () {
  33043. function _InstancesBatch() {
  33044. this.mustReturn = false;
  33045. this.visibleInstances = new Array();
  33046. this.renderSelf = new Array();
  33047. }
  33048. return _InstancesBatch;
  33049. }());
  33050. BABYLON._InstancesBatch = _InstancesBatch;
  33051. /**
  33052. * Class used to represent renderable models
  33053. */
  33054. var Mesh = /** @class */ (function (_super) {
  33055. __extends(Mesh, _super);
  33056. /**
  33057. * @constructor
  33058. * @param name The value used by scene.getMeshByName() to do a lookup.
  33059. * @param scene The scene to add this mesh to.
  33060. * @param parent The parent of this mesh, if it has one
  33061. * @param source An optional Mesh from which geometry is shared, cloned.
  33062. * @param doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  33063. * When false, achieved by calling a clone(), also passing False.
  33064. * This will make creation of children, recursive.
  33065. * @param clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  33066. */
  33067. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  33068. if (scene === void 0) { scene = null; }
  33069. if (parent === void 0) { parent = null; }
  33070. if (source === void 0) { source = null; }
  33071. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  33072. var _this = _super.call(this, name, scene) || this;
  33073. // Members
  33074. /**
  33075. * Gets the delay loading state of the mesh (when delay loading is turned on)
  33076. * @see http://doc.babylonjs.com/how_to/using_the_incremental_loading_system
  33077. */
  33078. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  33079. /**
  33080. * Gets the list of instances created from this mesh
  33081. * it is not supposed to be modified manually.
  33082. * Note also that the order of the InstancedMesh wihin the array is not significant and might change.
  33083. * @see http://doc.babylonjs.com/how_to/how_to_use_instances
  33084. */
  33085. _this.instances = new Array();
  33086. _this._LODLevels = new Array();
  33087. /** @hidden */
  33088. _this._instanceDataStorage = new _InstanceDataStorage();
  33089. // Use by builder only to know what orientation were the mesh build in.
  33090. /** @hidden */
  33091. _this._originalBuilderSideOrientation = Mesh.DEFAULTSIDE;
  33092. /**
  33093. * Use this property to change the original side orientation defined at construction time
  33094. */
  33095. _this.overrideMaterialSideOrientation = null;
  33096. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  33097. // Will be used to save a source mesh reference, If any
  33098. _this._source = null;
  33099. scene = _this.getScene();
  33100. if (source) {
  33101. // Geometry
  33102. if (source._geometry) {
  33103. source._geometry.applyToMesh(_this);
  33104. }
  33105. // Deep copy
  33106. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  33107. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen",
  33108. "onBeforeDrawObservable", "onBeforeRenderObservable", "onAfterRenderObservable", "onBeforeDraw",
  33109. "onAfterWorldMatrixUpdateObservable", "onCollideObservable", "onCollisionPositionChangeObservable", "onRebuildObservable",
  33110. "onDisposeObservable"
  33111. ], ["_poseMatrix"]);
  33112. // Source mesh
  33113. _this._source = source;
  33114. if (scene.useClonedMeshhMap) {
  33115. if (!source.meshMap) {
  33116. source.meshMap = {};
  33117. }
  33118. source.meshMap[_this.uniqueId] = _this;
  33119. }
  33120. // Construction Params
  33121. // Clone parameters allowing mesh to be updated in case of parametric shapes.
  33122. _this._originalBuilderSideOrientation = source._originalBuilderSideOrientation;
  33123. _this._creationDataStorage = source._creationDataStorage;
  33124. // Animation ranges
  33125. if (_this._source._ranges) {
  33126. var ranges = _this._source._ranges;
  33127. for (var name in ranges) {
  33128. if (!ranges.hasOwnProperty(name)) {
  33129. continue;
  33130. }
  33131. if (!ranges[name]) {
  33132. continue;
  33133. }
  33134. _this.createAnimationRange(name, ranges[name].from, ranges[name].to);
  33135. }
  33136. }
  33137. // Metadata
  33138. if (source.metadata && source.metadata.clone) {
  33139. _this.metadata = source.metadata.clone();
  33140. }
  33141. else {
  33142. _this.metadata = source.metadata;
  33143. }
  33144. // Tags
  33145. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  33146. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  33147. }
  33148. // Parent
  33149. _this.parent = source.parent;
  33150. // Pivot
  33151. _this.setPivotMatrix(source.getPivotMatrix());
  33152. _this.id = name + "." + source.id;
  33153. // Material
  33154. _this.material = source.material;
  33155. var index;
  33156. if (!doNotCloneChildren) {
  33157. // Children
  33158. var directDescendants = source.getDescendants(true);
  33159. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  33160. var child = directDescendants[index_1];
  33161. if (child.clone) {
  33162. child.clone(name + "." + child.name, _this);
  33163. }
  33164. }
  33165. }
  33166. // Physics clone
  33167. var physicsEngine = _this.getScene().getPhysicsEngine();
  33168. if (clonePhysicsImpostor && physicsEngine) {
  33169. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  33170. if (impostor) {
  33171. _this.physicsImpostor = impostor.clone(_this);
  33172. }
  33173. }
  33174. // Particles
  33175. for (index = 0; index < scene.particleSystems.length; index++) {
  33176. var system = scene.particleSystems[index];
  33177. if (system.emitter === source) {
  33178. system.clone(system.name, _this);
  33179. }
  33180. }
  33181. _this.refreshBoundingInfo();
  33182. _this.computeWorldMatrix(true);
  33183. }
  33184. // Parent
  33185. if (parent !== null) {
  33186. _this.parent = parent;
  33187. }
  33188. return _this;
  33189. }
  33190. Object.defineProperty(Mesh.prototype, "onBeforeRenderObservable", {
  33191. /**
  33192. * An event triggered before rendering the mesh
  33193. */
  33194. get: function () {
  33195. if (!this._onBeforeRenderObservable) {
  33196. this._onBeforeRenderObservable = new BABYLON.Observable();
  33197. }
  33198. return this._onBeforeRenderObservable;
  33199. },
  33200. enumerable: true,
  33201. configurable: true
  33202. });
  33203. Object.defineProperty(Mesh.prototype, "onAfterRenderObservable", {
  33204. /**
  33205. * An event triggered after rendering the mesh
  33206. */
  33207. get: function () {
  33208. if (!this._onAfterRenderObservable) {
  33209. this._onAfterRenderObservable = new BABYLON.Observable();
  33210. }
  33211. return this._onAfterRenderObservable;
  33212. },
  33213. enumerable: true,
  33214. configurable: true
  33215. });
  33216. Object.defineProperty(Mesh.prototype, "onBeforeDrawObservable", {
  33217. /**
  33218. * An event triggered before drawing the mesh
  33219. */
  33220. get: function () {
  33221. if (!this._onBeforeDrawObservable) {
  33222. this._onBeforeDrawObservable = new BABYLON.Observable();
  33223. }
  33224. return this._onBeforeDrawObservable;
  33225. },
  33226. enumerable: true,
  33227. configurable: true
  33228. });
  33229. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  33230. /**
  33231. * Sets a callback to call before drawing the mesh. It is recommended to use onBeforeDrawObservable instead
  33232. */
  33233. set: function (callback) {
  33234. if (this._onBeforeDrawObserver) {
  33235. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  33236. }
  33237. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  33238. },
  33239. enumerable: true,
  33240. configurable: true
  33241. });
  33242. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  33243. /**
  33244. * Gets or sets the morph target manager
  33245. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  33246. */
  33247. get: function () {
  33248. return this._morphTargetManager;
  33249. },
  33250. set: function (value) {
  33251. if (this._morphTargetManager === value) {
  33252. return;
  33253. }
  33254. this._morphTargetManager = value;
  33255. this._syncGeometryWithMorphTargetManager();
  33256. },
  33257. enumerable: true,
  33258. configurable: true
  33259. });
  33260. Object.defineProperty(Mesh.prototype, "source", {
  33261. /**
  33262. * Gets the source mesh (the one used to clone this one from)
  33263. */
  33264. get: function () {
  33265. return this._source;
  33266. },
  33267. enumerable: true,
  33268. configurable: true
  33269. });
  33270. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  33271. /**
  33272. * Gets or sets a boolean indicating that this mesh does not use index buffer
  33273. */
  33274. get: function () {
  33275. return this._unIndexed;
  33276. },
  33277. set: function (value) {
  33278. if (this._unIndexed !== value) {
  33279. this._unIndexed = value;
  33280. this._markSubMeshesAsAttributesDirty();
  33281. }
  33282. },
  33283. enumerable: true,
  33284. configurable: true
  33285. });
  33286. // Methods
  33287. /**
  33288. * Gets the class name
  33289. * @returns the string "Mesh".
  33290. */
  33291. Mesh.prototype.getClassName = function () {
  33292. return "Mesh";
  33293. };
  33294. /**
  33295. * Returns a description of this mesh
  33296. * @param fullDetails define if full details about this mesh must be used
  33297. * @returns a descriptive string representing this mesh
  33298. */
  33299. Mesh.prototype.toString = function (fullDetails) {
  33300. var ret = _super.prototype.toString.call(this, fullDetails);
  33301. ret += ", n vertices: " + this.getTotalVertices();
  33302. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  33303. if (this.animations) {
  33304. for (var i = 0; i < this.animations.length; i++) {
  33305. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  33306. }
  33307. }
  33308. if (fullDetails) {
  33309. if (this._geometry) {
  33310. var ib = this.getIndices();
  33311. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33312. if (vb && ib) {
  33313. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  33314. }
  33315. }
  33316. else {
  33317. ret += ", flat shading: UNKNOWN";
  33318. }
  33319. }
  33320. return ret;
  33321. };
  33322. /** @hidden */
  33323. Mesh.prototype._unBindEffect = function () {
  33324. _super.prototype._unBindEffect.call(this);
  33325. for (var _i = 0, _a = this.instances; _i < _a.length; _i++) {
  33326. var instance = _a[_i];
  33327. instance._unBindEffect();
  33328. }
  33329. };
  33330. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  33331. /**
  33332. * Gets a boolean indicating if this mesh has LOD
  33333. */
  33334. get: function () {
  33335. return this._LODLevels.length > 0;
  33336. },
  33337. enumerable: true,
  33338. configurable: true
  33339. });
  33340. /**
  33341. * Gets the list of MeshLODLevel associated with the current mesh
  33342. * @returns an array of MeshLODLevel
  33343. */
  33344. Mesh.prototype.getLODLevels = function () {
  33345. return this._LODLevels;
  33346. };
  33347. Mesh.prototype._sortLODLevels = function () {
  33348. this._LODLevels.sort(function (a, b) {
  33349. if (a.distance < b.distance) {
  33350. return 1;
  33351. }
  33352. if (a.distance > b.distance) {
  33353. return -1;
  33354. }
  33355. return 0;
  33356. });
  33357. };
  33358. /**
  33359. * Add a mesh as LOD level triggered at the given distance.
  33360. * @see https://doc.babylonjs.com/how_to/how_to_use_lod
  33361. * @param distance The distance from the center of the object to show this level
  33362. * @param mesh The mesh to be added as LOD level (can be null)
  33363. * @return This mesh (for chaining)
  33364. */
  33365. Mesh.prototype.addLODLevel = function (distance, mesh) {
  33366. if (mesh && mesh._masterMesh) {
  33367. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  33368. return this;
  33369. }
  33370. var level = new BABYLON.MeshLODLevel(distance, mesh);
  33371. this._LODLevels.push(level);
  33372. if (mesh) {
  33373. mesh._masterMesh = this;
  33374. }
  33375. this._sortLODLevels();
  33376. return this;
  33377. };
  33378. /**
  33379. * Returns the LOD level mesh at the passed distance or null if not found.
  33380. * @see https://doc.babylonjs.com/how_to/how_to_use_lod
  33381. * @param distance The distance from the center of the object to show this level
  33382. * @returns a Mesh or `null`
  33383. */
  33384. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  33385. for (var index = 0; index < this._LODLevels.length; index++) {
  33386. var level = this._LODLevels[index];
  33387. if (level.distance === distance) {
  33388. return level.mesh;
  33389. }
  33390. }
  33391. return null;
  33392. };
  33393. /**
  33394. * Remove a mesh from the LOD array
  33395. * @see https://doc.babylonjs.com/how_to/how_to_use_lod
  33396. * @param mesh defines the mesh to be removed
  33397. * @return This mesh (for chaining)
  33398. */
  33399. Mesh.prototype.removeLODLevel = function (mesh) {
  33400. for (var index = 0; index < this._LODLevels.length; index++) {
  33401. if (this._LODLevels[index].mesh === mesh) {
  33402. this._LODLevels.splice(index, 1);
  33403. if (mesh) {
  33404. mesh._masterMesh = null;
  33405. }
  33406. }
  33407. }
  33408. this._sortLODLevels();
  33409. return this;
  33410. };
  33411. /**
  33412. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  33413. * @see https://doc.babylonjs.com/how_to/how_to_use_lod
  33414. * @param camera defines the camera to use to compute distance
  33415. * @param boundingSphere defines a custom bounding sphere to use instead of the one from this mesh
  33416. * @return This mesh (for chaining)
  33417. */
  33418. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  33419. if (!this._LODLevels || this._LODLevels.length === 0) {
  33420. return this;
  33421. }
  33422. var bSphere;
  33423. if (boundingSphere) {
  33424. bSphere = boundingSphere;
  33425. }
  33426. else {
  33427. var boundingInfo = this.getBoundingInfo();
  33428. bSphere = boundingInfo.boundingSphere;
  33429. }
  33430. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  33431. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  33432. if (this.onLODLevelSelection) {
  33433. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  33434. }
  33435. return this;
  33436. }
  33437. for (var index = 0; index < this._LODLevels.length; index++) {
  33438. var level = this._LODLevels[index];
  33439. if (level.distance < distanceToCamera) {
  33440. if (level.mesh) {
  33441. level.mesh._preActivate();
  33442. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  33443. }
  33444. if (this.onLODLevelSelection) {
  33445. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  33446. }
  33447. return level.mesh;
  33448. }
  33449. }
  33450. if (this.onLODLevelSelection) {
  33451. this.onLODLevelSelection(distanceToCamera, this, this);
  33452. }
  33453. return this;
  33454. };
  33455. Object.defineProperty(Mesh.prototype, "geometry", {
  33456. /**
  33457. * Gets the mesh internal Geometry object
  33458. */
  33459. get: function () {
  33460. return this._geometry;
  33461. },
  33462. enumerable: true,
  33463. configurable: true
  33464. });
  33465. /**
  33466. * Returns the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  33467. * @returns the total number of vertices
  33468. */
  33469. Mesh.prototype.getTotalVertices = function () {
  33470. if (this._geometry === null || this._geometry === undefined) {
  33471. return 0;
  33472. }
  33473. return this._geometry.getTotalVertices();
  33474. };
  33475. /**
  33476. * Returns the content of an associated vertex buffer
  33477. * @param kind defines which buffer to read from (positions, indices, normals, etc). Possible `kind` values :
  33478. * - BABYLON.VertexBuffer.PositionKind
  33479. * - BABYLON.VertexBuffer.UVKind
  33480. * - BABYLON.VertexBuffer.UV2Kind
  33481. * - BABYLON.VertexBuffer.UV3Kind
  33482. * - BABYLON.VertexBuffer.UV4Kind
  33483. * - BABYLON.VertexBuffer.UV5Kind
  33484. * - BABYLON.VertexBuffer.UV6Kind
  33485. * - BABYLON.VertexBuffer.ColorKind
  33486. * - BABYLON.VertexBuffer.MatricesIndicesKind
  33487. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  33488. * - BABYLON.VertexBuffer.MatricesWeightsKind
  33489. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  33490. * @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
  33491. * @param forceCopy defines a boolean forcing the copy of the buffer no matter what the value of copyWhenShared is
  33492. * @returns a FloatArray or null if the mesh has no geometry or no vertex buffer for this kind.
  33493. */
  33494. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  33495. if (!this._geometry) {
  33496. return null;
  33497. }
  33498. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  33499. };
  33500. /**
  33501. * Returns the mesh VertexBuffer object from the requested `kind`
  33502. * @param kind defines which buffer to read from (positions, indices, normals, etc). Possible `kind` values :
  33503. * - BABYLON.VertexBuffer.PositionKind
  33504. * - BABYLON.VertexBuffer.UVKind
  33505. * - BABYLON.VertexBuffer.UV2Kind
  33506. * - BABYLON.VertexBuffer.UV3Kind
  33507. * - BABYLON.VertexBuffer.UV4Kind
  33508. * - BABYLON.VertexBuffer.UV5Kind
  33509. * - BABYLON.VertexBuffer.UV6Kind
  33510. * - BABYLON.VertexBuffer.ColorKind
  33511. * - BABYLON.VertexBuffer.MatricesIndicesKind
  33512. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  33513. * - BABYLON.VertexBuffer.MatricesWeightsKind
  33514. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  33515. * @returns a FloatArray or null if the mesh has no vertex buffer for this kind.
  33516. */
  33517. Mesh.prototype.getVertexBuffer = function (kind) {
  33518. if (!this._geometry) {
  33519. return null;
  33520. }
  33521. return this._geometry.getVertexBuffer(kind);
  33522. };
  33523. /**
  33524. * Tests if a specific vertex buffer is associated with this mesh
  33525. * @param kind defines which buffer to check (positions, indices, normals, etc). Possible `kind` values :
  33526. * - BABYLON.VertexBuffer.PositionKind
  33527. * - BABYLON.VertexBuffer.UVKind
  33528. * - BABYLON.VertexBuffer.UV2Kind
  33529. * - BABYLON.VertexBuffer.UV3Kind
  33530. * - BABYLON.VertexBuffer.UV4Kind
  33531. * - BABYLON.VertexBuffer.UV5Kind
  33532. * - BABYLON.VertexBuffer.UV6Kind
  33533. * - BABYLON.VertexBuffer.ColorKind
  33534. * - BABYLON.VertexBuffer.MatricesIndicesKind
  33535. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  33536. * - BABYLON.VertexBuffer.MatricesWeightsKind
  33537. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  33538. * @returns a boolean
  33539. */
  33540. Mesh.prototype.isVerticesDataPresent = function (kind) {
  33541. if (!this._geometry) {
  33542. if (this._delayInfo) {
  33543. return this._delayInfo.indexOf(kind) !== -1;
  33544. }
  33545. return false;
  33546. }
  33547. return this._geometry.isVerticesDataPresent(kind);
  33548. };
  33549. /**
  33550. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  33551. * @param kind defines which buffer to check (positions, indices, normals, etc). Possible `kind` values :
  33552. * - BABYLON.VertexBuffer.PositionKind
  33553. * - BABYLON.VertexBuffer.UVKind
  33554. * - BABYLON.VertexBuffer.UV2Kind
  33555. * - BABYLON.VertexBuffer.UV3Kind
  33556. * - BABYLON.VertexBuffer.UV4Kind
  33557. * - BABYLON.VertexBuffer.UV5Kind
  33558. * - BABYLON.VertexBuffer.UV6Kind
  33559. * - BABYLON.VertexBuffer.ColorKind
  33560. * - BABYLON.VertexBuffer.MatricesIndicesKind
  33561. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  33562. * - BABYLON.VertexBuffer.MatricesWeightsKind
  33563. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  33564. * @returns a boolean
  33565. */
  33566. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  33567. if (!this._geometry) {
  33568. if (this._delayInfo) {
  33569. return this._delayInfo.indexOf(kind) !== -1;
  33570. }
  33571. return false;
  33572. }
  33573. return this._geometry.isVertexBufferUpdatable(kind);
  33574. };
  33575. /**
  33576. * Returns a string which contains the list of existing `kinds` of Vertex Data associated with this mesh.
  33577. * @param kind defines which buffer to read from (positions, indices, normals, etc). Possible `kind` values :
  33578. * - BABYLON.VertexBuffer.PositionKind
  33579. * - BABYLON.VertexBuffer.UVKind
  33580. * - BABYLON.VertexBuffer.UV2Kind
  33581. * - BABYLON.VertexBuffer.UV3Kind
  33582. * - BABYLON.VertexBuffer.UV4Kind
  33583. * - BABYLON.VertexBuffer.UV5Kind
  33584. * - BABYLON.VertexBuffer.UV6Kind
  33585. * - BABYLON.VertexBuffer.ColorKind
  33586. * - BABYLON.VertexBuffer.MatricesIndicesKind
  33587. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  33588. * - BABYLON.VertexBuffer.MatricesWeightsKind
  33589. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  33590. * @returns an array of strings
  33591. */
  33592. Mesh.prototype.getVerticesDataKinds = function () {
  33593. if (!this._geometry) {
  33594. var result = new Array();
  33595. if (this._delayInfo) {
  33596. this._delayInfo.forEach(function (kind, index, array) {
  33597. result.push(kind);
  33598. });
  33599. }
  33600. return result;
  33601. }
  33602. return this._geometry.getVerticesDataKinds();
  33603. };
  33604. /**
  33605. * Returns a positive integer : the total number of indices in this mesh geometry.
  33606. * @returns the numner of indices or zero if the mesh has no geometry.
  33607. */
  33608. Mesh.prototype.getTotalIndices = function () {
  33609. if (!this._geometry) {
  33610. return 0;
  33611. }
  33612. return this._geometry.getTotalIndices();
  33613. };
  33614. /**
  33615. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  33616. * @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.
  33617. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  33618. * @returns the indices array or an empty array if the mesh has no geometry
  33619. */
  33620. Mesh.prototype.getIndices = function (copyWhenShared, forceCopy) {
  33621. if (!this._geometry) {
  33622. return [];
  33623. }
  33624. return this._geometry.getIndices(copyWhenShared, forceCopy);
  33625. };
  33626. Object.defineProperty(Mesh.prototype, "isBlocked", {
  33627. get: function () {
  33628. return this._masterMesh !== null && this._masterMesh !== undefined;
  33629. },
  33630. enumerable: true,
  33631. configurable: true
  33632. });
  33633. /**
  33634. * Determine if the current mesh is ready to be rendered
  33635. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  33636. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  33637. * @returns true if all associated assets are ready (material, textures, shaders)
  33638. */
  33639. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  33640. if (completeCheck === void 0) { completeCheck = false; }
  33641. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  33642. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  33643. return false;
  33644. }
  33645. if (!_super.prototype.isReady.call(this, completeCheck)) {
  33646. return false;
  33647. }
  33648. if (!this.subMeshes || this.subMeshes.length === 0) {
  33649. return true;
  33650. }
  33651. if (!completeCheck) {
  33652. return true;
  33653. }
  33654. var engine = this.getEngine();
  33655. var scene = this.getScene();
  33656. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  33657. this.computeWorldMatrix();
  33658. var mat = this.material || scene.defaultMaterial;
  33659. if (mat) {
  33660. if (mat._storeEffectOnSubMeshes) {
  33661. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  33662. var subMesh = _a[_i];
  33663. var effectiveMaterial = subMesh.getMaterial();
  33664. if (effectiveMaterial) {
  33665. if (effectiveMaterial._storeEffectOnSubMeshes) {
  33666. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  33667. return false;
  33668. }
  33669. }
  33670. else {
  33671. if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  33672. return false;
  33673. }
  33674. }
  33675. }
  33676. }
  33677. }
  33678. else {
  33679. if (!mat.isReady(this, hardwareInstancedRendering)) {
  33680. return false;
  33681. }
  33682. }
  33683. }
  33684. // Shadows
  33685. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  33686. var light = _c[_b];
  33687. var generator = light.getShadowGenerator();
  33688. if (generator) {
  33689. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  33690. var subMesh = _e[_d];
  33691. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  33692. return false;
  33693. }
  33694. }
  33695. }
  33696. }
  33697. // LOD
  33698. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  33699. var lod = _g[_f];
  33700. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  33701. return false;
  33702. }
  33703. }
  33704. return true;
  33705. };
  33706. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  33707. /**
  33708. * 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.
  33709. */
  33710. get: function () {
  33711. return this._areNormalsFrozen;
  33712. },
  33713. enumerable: true,
  33714. configurable: true
  33715. });
  33716. /**
  33717. * 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.
  33718. * @returns the current mesh
  33719. */
  33720. Mesh.prototype.freezeNormals = function () {
  33721. this._areNormalsFrozen = true;
  33722. return this;
  33723. };
  33724. /**
  33725. * 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
  33726. * @returns the current mesh
  33727. */
  33728. Mesh.prototype.unfreezeNormals = function () {
  33729. this._areNormalsFrozen = false;
  33730. return this;
  33731. };
  33732. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  33733. /**
  33734. * Sets a value overriding the instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  33735. */
  33736. set: function (count) {
  33737. this._instanceDataStorage.overridenInstanceCount = count;
  33738. },
  33739. enumerable: true,
  33740. configurable: true
  33741. });
  33742. // Methods
  33743. /** @hidden */
  33744. Mesh.prototype._preActivate = function () {
  33745. var sceneRenderId = this.getScene().getRenderId();
  33746. if (this._preActivateId === sceneRenderId) {
  33747. return this;
  33748. }
  33749. this._preActivateId = sceneRenderId;
  33750. this._instanceDataStorage.visibleInstances = null;
  33751. return this;
  33752. };
  33753. /** @hidden */
  33754. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  33755. if (this._instanceDataStorage.visibleInstances) {
  33756. this._instanceDataStorage.visibleInstances.intermediateDefaultRenderId = renderId;
  33757. }
  33758. return this;
  33759. };
  33760. /** @hidden */
  33761. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  33762. if (!this._instanceDataStorage.visibleInstances) {
  33763. this._instanceDataStorage.visibleInstances = {
  33764. defaultRenderId: renderId,
  33765. selfDefaultRenderId: this._renderId
  33766. };
  33767. }
  33768. if (!this._instanceDataStorage.visibleInstances[renderId]) {
  33769. this._instanceDataStorage.visibleInstances[renderId] = new Array();
  33770. }
  33771. this._instanceDataStorage.visibleInstances[renderId].push(instance);
  33772. return this;
  33773. };
  33774. /**
  33775. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  33776. * This means the mesh underlying bounding box and sphere are recomputed.
  33777. * @param applySkeleton defines whether to apply the skeleton before computing the bounding info
  33778. * @returns the current mesh
  33779. */
  33780. Mesh.prototype.refreshBoundingInfo = function (applySkeleton) {
  33781. if (applySkeleton === void 0) { applySkeleton = false; }
  33782. if (this._boundingInfo && this._boundingInfo.isLocked) {
  33783. return this;
  33784. }
  33785. var bias = this.geometry ? this.geometry.boundingBias : null;
  33786. this._refreshBoundingInfo(this._getPositionData(applySkeleton), bias);
  33787. return this;
  33788. };
  33789. /** @hidden */
  33790. Mesh.prototype._createGlobalSubMesh = function (force) {
  33791. var totalVertices = this.getTotalVertices();
  33792. if (!totalVertices || !this.getIndices()) {
  33793. return null;
  33794. }
  33795. // Check if we need to recreate the submeshes
  33796. if (this.subMeshes && this.subMeshes.length > 0) {
  33797. var ib = this.getIndices();
  33798. if (!ib) {
  33799. return null;
  33800. }
  33801. var totalIndices = ib.length;
  33802. var needToRecreate = false;
  33803. if (force) {
  33804. needToRecreate = true;
  33805. }
  33806. else {
  33807. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  33808. var submesh = _a[_i];
  33809. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  33810. needToRecreate = true;
  33811. break;
  33812. }
  33813. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  33814. needToRecreate = true;
  33815. break;
  33816. }
  33817. }
  33818. }
  33819. if (!needToRecreate) {
  33820. return this.subMeshes[0];
  33821. }
  33822. }
  33823. this.releaseSubMeshes();
  33824. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  33825. };
  33826. /**
  33827. * This function will subdivide the mesh into multiple submeshes
  33828. * @param count defines the expected number of submeshes
  33829. */
  33830. Mesh.prototype.subdivide = function (count) {
  33831. if (count < 1) {
  33832. return;
  33833. }
  33834. var totalIndices = this.getTotalIndices();
  33835. var subdivisionSize = (totalIndices / count) | 0;
  33836. var offset = 0;
  33837. // Ensure that subdivisionSize is a multiple of 3
  33838. while (subdivisionSize % 3 !== 0) {
  33839. subdivisionSize++;
  33840. }
  33841. this.releaseSubMeshes();
  33842. for (var index = 0; index < count; index++) {
  33843. if (offset >= totalIndices) {
  33844. break;
  33845. }
  33846. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  33847. offset += subdivisionSize;
  33848. }
  33849. this.synchronizeInstances();
  33850. };
  33851. /**
  33852. * Copy a FloatArray into a specific associated vertex buffer
  33853. * @param kind defines which buffer to write to (positions, indices, normals, etc). Possible `kind` values :
  33854. * - BABYLON.VertexBuffer.PositionKind
  33855. * - BABYLON.VertexBuffer.UVKind
  33856. * - BABYLON.VertexBuffer.UV2Kind
  33857. * - BABYLON.VertexBuffer.UV3Kind
  33858. * - BABYLON.VertexBuffer.UV4Kind
  33859. * - BABYLON.VertexBuffer.UV5Kind
  33860. * - BABYLON.VertexBuffer.UV6Kind
  33861. * - BABYLON.VertexBuffer.ColorKind
  33862. * - BABYLON.VertexBuffer.MatricesIndicesKind
  33863. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  33864. * - BABYLON.VertexBuffer.MatricesWeightsKind
  33865. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  33866. * @param data defines the data source
  33867. * @param updatable defines if the updated vertex buffer must be flagged as updatable
  33868. * @param stride defines the data stride size (can be null)
  33869. * @returns the current mesh
  33870. */
  33871. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  33872. if (updatable === void 0) { updatable = false; }
  33873. if (!this._geometry) {
  33874. var vertexData = new BABYLON.VertexData();
  33875. vertexData.set(data, kind);
  33876. var scene = this.getScene();
  33877. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  33878. }
  33879. else {
  33880. this._geometry.setVerticesData(kind, data, updatable, stride);
  33881. }
  33882. return this;
  33883. };
  33884. /**
  33885. * Flags an associated vertex buffer as updatable
  33886. * @param kind defines which buffer to use (positions, indices, normals, etc). Possible `kind` values :
  33887. * - BABYLON.VertexBuffer.PositionKind
  33888. * - BABYLON.VertexBuffer.UVKind
  33889. * - BABYLON.VertexBuffer.UV2Kind
  33890. * - BABYLON.VertexBuffer.UV3Kind
  33891. * - BABYLON.VertexBuffer.UV4Kind
  33892. * - BABYLON.VertexBuffer.UV5Kind
  33893. * - BABYLON.VertexBuffer.UV6Kind
  33894. * - BABYLON.VertexBuffer.ColorKind
  33895. * - BABYLON.VertexBuffer.MatricesIndicesKind
  33896. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  33897. * - BABYLON.VertexBuffer.MatricesWeightsKind
  33898. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  33899. * @param updatable defines if the updated vertex buffer must be flagged as updatable
  33900. */
  33901. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  33902. if (updatable === void 0) { updatable = true; }
  33903. var vb = this.getVertexBuffer(kind);
  33904. if (!vb || vb.isUpdatable() === updatable) {
  33905. return;
  33906. }
  33907. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  33908. };
  33909. /**
  33910. * Sets the mesh global Vertex Buffer
  33911. * @param buffer defines the buffer to use
  33912. * @returns the current mesh
  33913. */
  33914. Mesh.prototype.setVerticesBuffer = function (buffer) {
  33915. if (!this._geometry) {
  33916. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  33917. }
  33918. this._geometry.setVerticesBuffer(buffer);
  33919. return this;
  33920. };
  33921. /**
  33922. * Update a specific associated vertex buffer
  33923. * @param kind defines which buffer to write to (positions, indices, normals, etc). Possible `kind` values :
  33924. * - BABYLON.VertexBuffer.PositionKind
  33925. * - BABYLON.VertexBuffer.UVKind
  33926. * - BABYLON.VertexBuffer.UV2Kind
  33927. * - BABYLON.VertexBuffer.UV3Kind
  33928. * - BABYLON.VertexBuffer.UV4Kind
  33929. * - BABYLON.VertexBuffer.UV5Kind
  33930. * - BABYLON.VertexBuffer.UV6Kind
  33931. * - BABYLON.VertexBuffer.ColorKind
  33932. * - BABYLON.VertexBuffer.MatricesIndicesKind
  33933. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  33934. * - BABYLON.VertexBuffer.MatricesWeightsKind
  33935. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  33936. * @param data defines the data source
  33937. * @param updateExtends defines if extends info of the mesh must be updated (can be null). This is mostly useful for "position" kind
  33938. * @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)
  33939. * @returns the current mesh
  33940. */
  33941. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  33942. if (!this._geometry) {
  33943. return this;
  33944. }
  33945. if (!makeItUnique) {
  33946. this._geometry.updateVerticesData(kind, data, updateExtends);
  33947. }
  33948. else {
  33949. this.makeGeometryUnique();
  33950. this.updateVerticesData(kind, data, updateExtends, false);
  33951. }
  33952. return this;
  33953. };
  33954. /**
  33955. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  33956. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  33957. * @param positionFunction is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything
  33958. * @param computeNormals is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update
  33959. * @returns the current mesh
  33960. */
  33961. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  33962. if (computeNormals === void 0) { computeNormals = true; }
  33963. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33964. if (!positions) {
  33965. return this;
  33966. }
  33967. positionFunction(positions);
  33968. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  33969. if (computeNormals) {
  33970. var indices = this.getIndices();
  33971. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33972. if (!normals) {
  33973. return this;
  33974. }
  33975. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  33976. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  33977. }
  33978. return this;
  33979. };
  33980. /**
  33981. * Creates a un-shared specific occurence of the geometry for the mesh.
  33982. * @returns the current mesh
  33983. */
  33984. Mesh.prototype.makeGeometryUnique = function () {
  33985. if (!this._geometry) {
  33986. return this;
  33987. }
  33988. var oldGeometry = this._geometry;
  33989. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  33990. oldGeometry.releaseForMesh(this, true);
  33991. geometry.applyToMesh(this);
  33992. return this;
  33993. };
  33994. /**
  33995. * Set the index buffer of this mesh
  33996. * @param indices defines the source data
  33997. * @param totalVertices defines the total number of vertices referenced by this index data (can be null)
  33998. * @param updatable defines if the updated index buffer must be flagged as updatable (default is false)
  33999. * @returns the current mesh
  34000. */
  34001. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  34002. if (totalVertices === void 0) { totalVertices = null; }
  34003. if (updatable === void 0) { updatable = false; }
  34004. if (!this._geometry) {
  34005. var vertexData = new BABYLON.VertexData();
  34006. vertexData.indices = indices;
  34007. var scene = this.getScene();
  34008. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  34009. }
  34010. else {
  34011. this._geometry.setIndices(indices, totalVertices, updatable);
  34012. }
  34013. return this;
  34014. };
  34015. /**
  34016. * Update the current index buffer
  34017. * @param indices defines the source data
  34018. * @param offset defines the offset in the index buffer where to store the new data (can be null)
  34019. * @returns the current mesh
  34020. */
  34021. Mesh.prototype.updateIndices = function (indices, offset) {
  34022. if (!this._geometry) {
  34023. return this;
  34024. }
  34025. this._geometry.updateIndices(indices, offset);
  34026. return this;
  34027. };
  34028. /**
  34029. * Invert the geometry to move from a right handed system to a left handed one.
  34030. * @returns the current mesh
  34031. */
  34032. Mesh.prototype.toLeftHanded = function () {
  34033. if (!this._geometry) {
  34034. return this;
  34035. }
  34036. this._geometry.toLeftHanded();
  34037. return this;
  34038. };
  34039. /** @hidden */
  34040. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  34041. if (!this._geometry) {
  34042. return this;
  34043. }
  34044. var engine = this.getScene().getEngine();
  34045. // Wireframe
  34046. var indexToBind;
  34047. if (this._unIndexed) {
  34048. indexToBind = null;
  34049. }
  34050. else {
  34051. switch (fillMode) {
  34052. case BABYLON.Material.PointFillMode:
  34053. indexToBind = null;
  34054. break;
  34055. case BABYLON.Material.WireFrameFillMode:
  34056. indexToBind = subMesh._getLinesIndexBuffer(this.getIndices(), engine);
  34057. break;
  34058. default:
  34059. case BABYLON.Material.TriangleFillMode:
  34060. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  34061. break;
  34062. }
  34063. }
  34064. // VBOs
  34065. this._geometry._bind(effect, indexToBind);
  34066. return this;
  34067. };
  34068. /** @hidden */
  34069. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  34070. if (alternate === void 0) { alternate = false; }
  34071. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  34072. return this;
  34073. }
  34074. if (this._onBeforeDrawObservable) {
  34075. this._onBeforeDrawObservable.notifyObservers(this);
  34076. }
  34077. var scene = this.getScene();
  34078. var engine = scene.getEngine();
  34079. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  34080. // or triangles as points
  34081. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  34082. }
  34083. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  34084. // Triangles as wireframe
  34085. engine.drawElementsType(fillMode, 0, subMesh._linesIndexCount, instancesCount);
  34086. }
  34087. else {
  34088. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  34089. }
  34090. if (scene._isAlternateRenderingEnabled && !alternate) {
  34091. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  34092. if (!effect || !scene.activeCamera) {
  34093. return this;
  34094. }
  34095. scene._switchToAlternateCameraConfiguration(true);
  34096. this._effectiveMaterial.bindView(effect);
  34097. this._effectiveMaterial.bindViewProjection(effect);
  34098. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  34099. this._draw(subMesh, fillMode, instancesCount, true);
  34100. engine.setViewport(scene.activeCamera.viewport);
  34101. scene._switchToAlternateCameraConfiguration(false);
  34102. this._effectiveMaterial.bindView(effect);
  34103. this._effectiveMaterial.bindViewProjection(effect);
  34104. }
  34105. return this;
  34106. };
  34107. /**
  34108. * Registers for this mesh a javascript function called just before the rendering process
  34109. * @param func defines the function to call before rendering this mesh
  34110. * @returns the current mesh
  34111. */
  34112. Mesh.prototype.registerBeforeRender = function (func) {
  34113. this.onBeforeRenderObservable.add(func);
  34114. return this;
  34115. };
  34116. /**
  34117. * Disposes a previously registered javascript function called before the rendering
  34118. * @param func defines the function to remove
  34119. * @returns the current mesh
  34120. */
  34121. Mesh.prototype.unregisterBeforeRender = function (func) {
  34122. this.onBeforeRenderObservable.removeCallback(func);
  34123. return this;
  34124. };
  34125. /**
  34126. * Registers for this mesh a javascript function called just after the rendering is complete
  34127. * @param func defines the function to call after rendering this mesh
  34128. * @returns the current mesh
  34129. */
  34130. Mesh.prototype.registerAfterRender = function (func) {
  34131. this.onAfterRenderObservable.add(func);
  34132. return this;
  34133. };
  34134. /**
  34135. * Disposes a previously registered javascript function called after the rendering.
  34136. * @param func defines the function to remove
  34137. * @returns the current mesh
  34138. */
  34139. Mesh.prototype.unregisterAfterRender = function (func) {
  34140. this.onAfterRenderObservable.removeCallback(func);
  34141. return this;
  34142. };
  34143. /** @hidden */
  34144. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  34145. var scene = this.getScene();
  34146. var batchCache = this._instanceDataStorage.batchCache;
  34147. batchCache.mustReturn = false;
  34148. batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  34149. batchCache.visibleInstances[subMeshId] = null;
  34150. if (this._instanceDataStorage.visibleInstances) {
  34151. var visibleInstances = this._instanceDataStorage.visibleInstances;
  34152. var currentRenderId = scene.getRenderId();
  34153. var defaultRenderId = (scene._isInIntermediateRendering() ? visibleInstances.intermediateDefaultRenderId : visibleInstances.defaultRenderId);
  34154. batchCache.visibleInstances[subMeshId] = visibleInstances[currentRenderId];
  34155. var selfRenderId = this._renderId;
  34156. if (!batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  34157. batchCache.visibleInstances[subMeshId] = visibleInstances[defaultRenderId];
  34158. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  34159. selfRenderId = Math.max(visibleInstances.selfDefaultRenderId, currentRenderId);
  34160. }
  34161. var visibleInstancesForSubMesh = batchCache.visibleInstances[subMeshId];
  34162. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  34163. if (this._instanceDataStorage.renderIdForInstances[subMeshId] === currentRenderId) {
  34164. batchCache.mustReturn = true;
  34165. return batchCache;
  34166. }
  34167. if (currentRenderId !== selfRenderId) {
  34168. batchCache.renderSelf[subMeshId] = false;
  34169. }
  34170. }
  34171. this._instanceDataStorage.renderIdForInstances[subMeshId] = currentRenderId;
  34172. }
  34173. return batchCache;
  34174. };
  34175. /** @hidden */
  34176. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  34177. var visibleInstances = batch.visibleInstances[subMesh._id];
  34178. if (!visibleInstances) {
  34179. return this;
  34180. }
  34181. var matricesCount = visibleInstances.length + 1;
  34182. var bufferSize = matricesCount * 16 * 4;
  34183. var instanceStorage = this._instanceDataStorage;
  34184. var currentInstancesBufferSize = instanceStorage.instancesBufferSize;
  34185. var instancesBuffer = instanceStorage.instancesBuffer;
  34186. while (instanceStorage.instancesBufferSize < bufferSize) {
  34187. instanceStorage.instancesBufferSize *= 2;
  34188. }
  34189. if (!instanceStorage.instancesData || currentInstancesBufferSize != instanceStorage.instancesBufferSize) {
  34190. instanceStorage.instancesData = new Float32Array(instanceStorage.instancesBufferSize / 4);
  34191. }
  34192. var offset = 0;
  34193. var instancesCount = 0;
  34194. var world = this.getWorldMatrix();
  34195. if (batch.renderSelf[subMesh._id]) {
  34196. world.copyToArray(instanceStorage.instancesData, offset);
  34197. offset += 16;
  34198. instancesCount++;
  34199. }
  34200. if (visibleInstances) {
  34201. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  34202. var instance = visibleInstances[instanceIndex];
  34203. instance.getWorldMatrix().copyToArray(instanceStorage.instancesData, offset);
  34204. offset += 16;
  34205. instancesCount++;
  34206. }
  34207. }
  34208. if (!instancesBuffer || currentInstancesBufferSize != instanceStorage.instancesBufferSize) {
  34209. if (instancesBuffer) {
  34210. instancesBuffer.dispose();
  34211. }
  34212. instancesBuffer = new BABYLON.Buffer(engine, instanceStorage.instancesData, true, 16, false, true);
  34213. instanceStorage.instancesBuffer = instancesBuffer;
  34214. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  34215. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  34216. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  34217. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  34218. }
  34219. else {
  34220. instancesBuffer.updateDirectly(instanceStorage.instancesData, 0, instancesCount);
  34221. }
  34222. this._bind(subMesh, effect, fillMode);
  34223. this._draw(subMesh, fillMode, instancesCount);
  34224. engine.unbindInstanceAttributes();
  34225. return this;
  34226. };
  34227. /** @hidden */
  34228. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  34229. var scene = this.getScene();
  34230. var engine = scene.getEngine();
  34231. if (hardwareInstancedRendering) {
  34232. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  34233. }
  34234. else {
  34235. if (batch.renderSelf[subMesh._id]) {
  34236. // Draw
  34237. if (onBeforeDraw) {
  34238. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  34239. }
  34240. this._draw(subMesh, fillMode, this._instanceDataStorage.overridenInstanceCount);
  34241. }
  34242. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  34243. if (visibleInstancesForSubMesh) {
  34244. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  34245. var instance = visibleInstancesForSubMesh[instanceIndex];
  34246. // World
  34247. var world = instance.getWorldMatrix();
  34248. if (onBeforeDraw) {
  34249. onBeforeDraw(true, world, effectiveMaterial);
  34250. }
  34251. // Draw
  34252. this._draw(subMesh, fillMode);
  34253. }
  34254. }
  34255. }
  34256. return this;
  34257. };
  34258. /**
  34259. * 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
  34260. * @param subMesh defines the subMesh to render
  34261. * @param enableAlphaMode defines if alpha mode can be changed
  34262. * @returns the current mesh
  34263. */
  34264. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  34265. if (this._checkOcclusionQuery()) {
  34266. return this;
  34267. }
  34268. var scene = this.getScene();
  34269. // Managing instances
  34270. var batch = this._getInstancesRenderList(subMesh._id);
  34271. if (batch.mustReturn) {
  34272. return this;
  34273. }
  34274. // Checking geometry state
  34275. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  34276. return this;
  34277. }
  34278. if (this._onBeforeRenderObservable) {
  34279. this._onBeforeRenderObservable.notifyObservers(this);
  34280. }
  34281. var engine = scene.getEngine();
  34282. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  34283. // Material
  34284. var material = subMesh.getMaterial();
  34285. if (!material) {
  34286. return this;
  34287. }
  34288. this._effectiveMaterial = material;
  34289. if (this._effectiveMaterial._storeEffectOnSubMeshes) {
  34290. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  34291. return this;
  34292. }
  34293. }
  34294. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  34295. return this;
  34296. }
  34297. // Alpha mode
  34298. if (enableAlphaMode) {
  34299. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  34300. }
  34301. for (var _i = 0, _a = scene._beforeRenderingMeshStage; _i < _a.length; _i++) {
  34302. var step = _a[_i];
  34303. step.action(this, subMesh, batch);
  34304. }
  34305. var effect;
  34306. if (this._effectiveMaterial._storeEffectOnSubMeshes) {
  34307. effect = subMesh.effect;
  34308. }
  34309. else {
  34310. effect = this._effectiveMaterial.getEffect();
  34311. }
  34312. if (!effect) {
  34313. return this;
  34314. }
  34315. var effectiveMesh = (this.skeleton && this.skeleton.overrideMesh) || this;
  34316. var sideOrientation = this.overrideMaterialSideOrientation;
  34317. if (sideOrientation == null) {
  34318. sideOrientation = this._effectiveMaterial.sideOrientation;
  34319. if (effectiveMesh._getWorldMatrixDeterminant() < 0) {
  34320. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  34321. }
  34322. }
  34323. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  34324. if (this._effectiveMaterial.forceDepthWrite) {
  34325. engine.setDepthWrite(true);
  34326. }
  34327. // Bind
  34328. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  34329. if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB
  34330. this._bind(subMesh, effect, fillMode);
  34331. }
  34332. var world = effectiveMesh.getWorldMatrix();
  34333. if (this._effectiveMaterial._storeEffectOnSubMeshes) {
  34334. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  34335. }
  34336. else {
  34337. this._effectiveMaterial.bind(world, this);
  34338. }
  34339. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  34340. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  34341. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  34342. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  34343. }
  34344. // Draw
  34345. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  34346. // Unbind
  34347. this._effectiveMaterial.unbind();
  34348. for (var _b = 0, _c = scene._afterRenderingMeshStage; _b < _c.length; _b++) {
  34349. var step = _c[_b];
  34350. step.action(this, subMesh, batch);
  34351. }
  34352. if (this._onAfterRenderObservable) {
  34353. this._onAfterRenderObservable.notifyObservers(this);
  34354. }
  34355. return this;
  34356. };
  34357. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  34358. if (isInstance && effectiveMaterial) {
  34359. effectiveMaterial.bindOnlyWorldMatrix(world);
  34360. }
  34361. };
  34362. /**
  34363. * Renormalize the mesh and patch it up if there are no weights
  34364. * Similar to normalization by adding the weights compute the reciprocal and multiply all elements, this wil ensure that everything adds to 1.
  34365. * However in the case of zero weights then we set just a single influence to 1.
  34366. * We check in the function for extra's present and if so we use the normalizeSkinWeightsWithExtras rather than the FourWeights version.
  34367. */
  34368. Mesh.prototype.cleanMatrixWeights = function () {
  34369. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  34370. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  34371. this.normalizeSkinWeightsAndExtra();
  34372. }
  34373. else {
  34374. this.normalizeSkinFourWeights();
  34375. }
  34376. }
  34377. };
  34378. // faster 4 weight version.
  34379. Mesh.prototype.normalizeSkinFourWeights = function () {
  34380. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  34381. var numWeights = matricesWeights.length;
  34382. for (var a = 0; a < numWeights; a += 4) {
  34383. // accumulate weights
  34384. var t = matricesWeights[a] + matricesWeights[a + 1] + matricesWeights[a + 2] + matricesWeights[a + 3];
  34385. // check for invalid weight and just set it to 1.
  34386. if (t === 0) {
  34387. matricesWeights[a] = 1;
  34388. }
  34389. else {
  34390. // renormalize so everything adds to 1 use reciprical
  34391. var recip = 1 / t;
  34392. matricesWeights[a] *= recip;
  34393. matricesWeights[a + 1] *= recip;
  34394. matricesWeights[a + 2] *= recip;
  34395. matricesWeights[a + 3] *= recip;
  34396. }
  34397. }
  34398. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeights);
  34399. };
  34400. // handle special case of extra verts. (in theory gltf can handle 12 influences)
  34401. Mesh.prototype.normalizeSkinWeightsAndExtra = function () {
  34402. var matricesWeightsExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  34403. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  34404. var numWeights = matricesWeights.length;
  34405. for (var a = 0; a < numWeights; a += 4) {
  34406. // accumulate weights
  34407. var t = matricesWeights[a] + matricesWeights[a + 1] + matricesWeights[a + 2] + matricesWeights[a + 3];
  34408. t += matricesWeightsExtra[a] + matricesWeightsExtra[a + 1] + matricesWeightsExtra[a + 2] + matricesWeightsExtra[a + 3];
  34409. // check for invalid weight and just set it to 1.
  34410. if (t === 0) {
  34411. matricesWeights[a] = 1;
  34412. }
  34413. else {
  34414. // renormalize so everything adds to 1 use reciprical
  34415. var recip = 1 / t;
  34416. matricesWeights[a] *= recip;
  34417. matricesWeights[a + 1] *= recip;
  34418. matricesWeights[a + 2] *= recip;
  34419. matricesWeights[a + 3] *= recip;
  34420. // same goes for extras
  34421. matricesWeightsExtra[a] *= recip;
  34422. matricesWeightsExtra[a + 1] *= recip;
  34423. matricesWeightsExtra[a + 2] *= recip;
  34424. matricesWeightsExtra[a + 3] *= recip;
  34425. }
  34426. }
  34427. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeights);
  34428. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsExtra);
  34429. };
  34430. /**
  34431. * ValidateSkinning is used to determine that a mesh has valid skinning data along with skin metrics, if missing weights,
  34432. * or not normalized it is returned as invalid mesh the string can be used for console logs, or on screen messages to let
  34433. * the user know there was an issue with importing the mesh
  34434. * @returns a validation object with skinned, valid and report string
  34435. */
  34436. Mesh.prototype.validateSkinning = function () {
  34437. var matricesWeightsExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  34438. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  34439. if (matricesWeights === null || this.skeleton == null) {
  34440. return { skinned: false, valid: true, report: "not skinned" };
  34441. }
  34442. var numWeights = matricesWeights.length;
  34443. var numberNotSorted = 0;
  34444. var missingWeights = 0;
  34445. var maxUsedWeights = 0;
  34446. var numberNotNormalized = 0;
  34447. var numInfluences = matricesWeightsExtra === null ? 4 : 8;
  34448. var usedWeightCounts = new Array();
  34449. for (var a = 0; a <= numInfluences; a++) {
  34450. usedWeightCounts[a] = 0;
  34451. }
  34452. var toleranceEpsilon = 0.001;
  34453. for (var a = 0; a < numWeights; a += 4) {
  34454. var lastWeight = matricesWeights[a];
  34455. var t = lastWeight;
  34456. var usedWeights = t === 0 ? 0 : 1;
  34457. for (var b = 1; b < numInfluences; b++) {
  34458. var d = b < 4 ? matricesWeights[a + b] : matricesWeightsExtra[a + b - 4];
  34459. if (d > lastWeight) {
  34460. numberNotSorted++;
  34461. }
  34462. if (d !== 0) {
  34463. usedWeights++;
  34464. }
  34465. t += d;
  34466. lastWeight = d;
  34467. }
  34468. // count the buffer weights usage
  34469. usedWeightCounts[usedWeights]++;
  34470. // max influences
  34471. if (usedWeights > maxUsedWeights) {
  34472. maxUsedWeights = usedWeights;
  34473. }
  34474. // check for invalid weight and just set it to 1.
  34475. if (t === 0) {
  34476. missingWeights++;
  34477. }
  34478. else {
  34479. // renormalize so everything adds to 1 use reciprical
  34480. var recip = 1 / t;
  34481. var tolerance = 0;
  34482. for (b = 0; b < numInfluences; b++) {
  34483. if (b < 4) {
  34484. tolerance += Math.abs(matricesWeights[a + b] - (matricesWeights[a + b] * recip));
  34485. }
  34486. else {
  34487. tolerance += Math.abs(matricesWeightsExtra[a + b - 4] - (matricesWeightsExtra[a + b - 4] * recip));
  34488. }
  34489. }
  34490. // arbitary epsilon value for dicdating not normalized
  34491. if (tolerance > toleranceEpsilon) {
  34492. numberNotNormalized++;
  34493. }
  34494. }
  34495. }
  34496. // validate bone indices are in range of the skeleton
  34497. var numBones = this.skeleton.bones.length;
  34498. var matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  34499. var matricesIndicesExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  34500. var numBadBoneIndices = 0;
  34501. for (var a = 0; a < numWeights; a++) {
  34502. for (var b = 0; b < numInfluences; b++) {
  34503. var index = b < 4 ? matricesIndices[b] : matricesIndicesExtra[b - 4];
  34504. if (index >= numBones || index < 0) {
  34505. numBadBoneIndices++;
  34506. }
  34507. }
  34508. }
  34509. // log mesh stats
  34510. var output = "Number of Weights = " + numWeights / 4 + "\nMaximum influences = " + maxUsedWeights +
  34511. "\nMissing Weights = " + missingWeights + "\nNot Sorted = " + numberNotSorted +
  34512. "\nNot Normalized = " + numberNotNormalized + "\nWeightCounts = [" + usedWeightCounts + "]" +
  34513. "\nNumber of bones = " + numBones + "\nBad Bone Indices = " + numBadBoneIndices;
  34514. return { skinned: true, valid: missingWeights === 0 && numberNotNormalized === 0 && numBadBoneIndices === 0, report: output };
  34515. };
  34516. /** @hidden */
  34517. Mesh.prototype._checkDelayState = function () {
  34518. var scene = this.getScene();
  34519. if (this._geometry) {
  34520. this._geometry.load(scene);
  34521. }
  34522. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  34523. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  34524. this._queueLoad(scene);
  34525. }
  34526. return this;
  34527. };
  34528. Mesh.prototype._queueLoad = function (scene) {
  34529. var _this = this;
  34530. scene._addPendingData(this);
  34531. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  34532. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  34533. if (data instanceof ArrayBuffer) {
  34534. _this._delayLoadingFunction(data, _this);
  34535. }
  34536. else {
  34537. _this._delayLoadingFunction(JSON.parse(data), _this);
  34538. }
  34539. _this.instances.forEach(function (instance) {
  34540. instance._syncSubMeshes();
  34541. });
  34542. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  34543. scene._removePendingData(_this);
  34544. }, function () { }, scene.offlineProvider, getBinaryData);
  34545. return this;
  34546. };
  34547. /**
  34548. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  34549. * A mesh is in the frustum if its bounding box intersects the frustum
  34550. * @param frustumPlanes defines the frustum to test
  34551. * @returns true if the mesh is in the frustum planes
  34552. */
  34553. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  34554. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  34555. return false;
  34556. }
  34557. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  34558. return false;
  34559. }
  34560. this._checkDelayState();
  34561. return true;
  34562. };
  34563. /**
  34564. * Sets the mesh material by the material or multiMaterial `id` property
  34565. * @param id is a string identifying the material or the multiMaterial
  34566. * @returns the current mesh
  34567. */
  34568. Mesh.prototype.setMaterialByID = function (id) {
  34569. var materials = this.getScene().materials;
  34570. var index;
  34571. for (index = materials.length - 1; index > -1; index--) {
  34572. if (materials[index].id === id) {
  34573. this.material = materials[index];
  34574. return this;
  34575. }
  34576. }
  34577. // Multi
  34578. var multiMaterials = this.getScene().multiMaterials;
  34579. for (index = multiMaterials.length - 1; index > -1; index--) {
  34580. if (multiMaterials[index].id === id) {
  34581. this.material = multiMaterials[index];
  34582. return this;
  34583. }
  34584. }
  34585. return this;
  34586. };
  34587. /**
  34588. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  34589. * @returns an array of IAnimatable
  34590. */
  34591. Mesh.prototype.getAnimatables = function () {
  34592. var results = new Array();
  34593. if (this.material) {
  34594. results.push(this.material);
  34595. }
  34596. if (this.skeleton) {
  34597. results.push(this.skeleton);
  34598. }
  34599. return results;
  34600. };
  34601. /**
  34602. * Modifies the mesh geometry according to the passed transformation matrix.
  34603. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  34604. * The mesh normals are modified using the same transformation.
  34605. * Note that, under the hood, this method sets a new VertexBuffer each call.
  34606. * @param transform defines the transform matrix to use
  34607. * @see http://doc.babylonjs.com/resources/baking_transformations
  34608. * @returns the current mesh
  34609. */
  34610. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  34611. // Position
  34612. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  34613. return this;
  34614. }
  34615. var submeshes = this.subMeshes.splice(0);
  34616. this._resetPointsArrayCache();
  34617. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34618. var temp = new Array();
  34619. var index;
  34620. for (index = 0; index < data.length; index += 3) {
  34621. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  34622. }
  34623. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  34624. // Normals
  34625. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  34626. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34627. temp = [];
  34628. for (index = 0; index < data.length; index += 3) {
  34629. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  34630. }
  34631. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  34632. }
  34633. // flip faces?
  34634. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  34635. this.flipFaces();
  34636. }
  34637. // Restore submeshes
  34638. this.releaseSubMeshes();
  34639. this.subMeshes = submeshes;
  34640. return this;
  34641. };
  34642. /**
  34643. * Modifies the mesh geometry according to its own current World Matrix.
  34644. * The mesh World Matrix is then reset.
  34645. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  34646. * Note that, under the hood, this method sets a new VertexBuffer each call.
  34647. * @see http://doc.babylonjs.com/resources/baking_transformations
  34648. * @returns the current mesh
  34649. */
  34650. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  34651. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  34652. this.scaling.copyFromFloats(1, 1, 1);
  34653. this.position.copyFromFloats(0, 0, 0);
  34654. this.rotation.copyFromFloats(0, 0, 0);
  34655. //only if quaternion is already set
  34656. if (this.rotationQuaternion) {
  34657. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  34658. }
  34659. this._worldMatrix = BABYLON.Matrix.Identity();
  34660. return this;
  34661. };
  34662. Object.defineProperty(Mesh.prototype, "_positions", {
  34663. // Cache
  34664. /** @hidden */
  34665. get: function () {
  34666. if (this._geometry) {
  34667. return this._geometry._positions;
  34668. }
  34669. return null;
  34670. },
  34671. enumerable: true,
  34672. configurable: true
  34673. });
  34674. /** @hidden */
  34675. Mesh.prototype._resetPointsArrayCache = function () {
  34676. if (this._geometry) {
  34677. this._geometry._resetPointsArrayCache();
  34678. }
  34679. return this;
  34680. };
  34681. /** @hidden */
  34682. Mesh.prototype._generatePointsArray = function () {
  34683. if (this._geometry) {
  34684. return this._geometry._generatePointsArray();
  34685. }
  34686. return false;
  34687. };
  34688. /**
  34689. * Returns a new Mesh object generated from the current mesh properties.
  34690. * This method must not get confused with createInstance()
  34691. * @param name is a string, the name given to the new mesh
  34692. * @param newParent can be any Node object (default `null`)
  34693. * @param doNotCloneChildren allows/denies the recursive cloning of the original mesh children if any (default `false`)
  34694. * @param clonePhysicsImpostor allows/denies the cloning in the same time of the original mesh `body` used by the physics engine, if any (default `true`)
  34695. * @returns a new mesh
  34696. */
  34697. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  34698. if (name === void 0) { name = ""; }
  34699. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  34700. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  34701. };
  34702. /**
  34703. * Releases resources associated with this mesh.
  34704. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  34705. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  34706. */
  34707. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  34708. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  34709. this.morphTargetManager = null;
  34710. if (this._geometry) {
  34711. this._geometry.releaseForMesh(this, true);
  34712. }
  34713. if (this._onBeforeDrawObservable) {
  34714. this._onBeforeDrawObservable.clear();
  34715. }
  34716. if (this._onBeforeRenderObservable) {
  34717. this._onBeforeRenderObservable.clear();
  34718. }
  34719. if (this._onAfterRenderObservable) {
  34720. this._onAfterRenderObservable.clear();
  34721. }
  34722. // Sources
  34723. if (this._scene.useClonedMeshhMap) {
  34724. if (this.meshMap) {
  34725. for (var uniqueId in this.meshMap) {
  34726. var mesh = this.meshMap[uniqueId];
  34727. if (mesh) {
  34728. mesh._source = null;
  34729. this.meshMap[uniqueId] = undefined;
  34730. }
  34731. }
  34732. }
  34733. if (this._source && this._source.meshMap) {
  34734. this._source.meshMap[this.uniqueId] = undefined;
  34735. }
  34736. }
  34737. else {
  34738. var meshes = this.getScene().meshes;
  34739. for (var _i = 0, meshes_1 = meshes; _i < meshes_1.length; _i++) {
  34740. var abstractMesh = meshes_1[_i];
  34741. var mesh = abstractMesh;
  34742. if (mesh._source && mesh._source === this) {
  34743. mesh._source = null;
  34744. }
  34745. }
  34746. }
  34747. this._source = null;
  34748. // Instances
  34749. if (this._instanceDataStorage.instancesBuffer) {
  34750. this._instanceDataStorage.instancesBuffer.dispose();
  34751. this._instanceDataStorage.instancesBuffer = null;
  34752. }
  34753. while (this.instances.length) {
  34754. this.instances[0].dispose();
  34755. }
  34756. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  34757. };
  34758. /**
  34759. * Modifies the mesh geometry according to a displacement map.
  34760. * 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.
  34761. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  34762. * @param url is a string, the URL from the image file is to be downloaded.
  34763. * @param minHeight is the lower limit of the displacement.
  34764. * @param maxHeight is the upper limit of the displacement.
  34765. * @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.
  34766. * @param uvOffset is an optional vector2 used to offset UV.
  34767. * @param uvScale is an optional vector2 used to scale UV.
  34768. * @param forceUpdate defines whether or not to force an update of the generated buffers. This is useful to apply on a deserialized model for instance.
  34769. * @returns the Mesh.
  34770. */
  34771. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale, forceUpdate) {
  34772. var _this = this;
  34773. if (forceUpdate === void 0) { forceUpdate = false; }
  34774. var scene = this.getScene();
  34775. var onload = function (img) {
  34776. // Getting height map data
  34777. var canvas = document.createElement("canvas");
  34778. var context = canvas.getContext("2d");
  34779. var heightMapWidth = img.width;
  34780. var heightMapHeight = img.height;
  34781. canvas.width = heightMapWidth;
  34782. canvas.height = heightMapHeight;
  34783. context.drawImage(img, 0, 0);
  34784. // Create VertexData from map data
  34785. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  34786. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  34787. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale, forceUpdate);
  34788. //execute success callback, if set
  34789. if (onSuccess) {
  34790. onSuccess(_this);
  34791. }
  34792. };
  34793. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.offlineProvider);
  34794. return this;
  34795. };
  34796. /**
  34797. * Modifies the mesh geometry according to a displacementMap buffer.
  34798. * 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.
  34799. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  34800. * @param buffer is a `Uint8Array` buffer containing series of `Uint8` lower than 255, the red, green, blue and alpha values of each successive pixel.
  34801. * @param heightMapWidth is the width of the buffer image.
  34802. * @param heightMapHeight is the height of the buffer image.
  34803. * @param minHeight is the lower limit of the displacement.
  34804. * @param maxHeight is the upper limit of the displacement.
  34805. * @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.
  34806. * @param uvOffset is an optional vector2 used to offset UV.
  34807. * @param uvScale is an optional vector2 used to scale UV.
  34808. * @param forceUpdate defines whether or not to force an update of the generated buffers. This is useful to apply on a deserialized model for instance.
  34809. * @returns the Mesh.
  34810. */
  34811. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale, forceUpdate) {
  34812. if (forceUpdate === void 0) { forceUpdate = false; }
  34813. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  34814. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  34815. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  34816. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  34817. return this;
  34818. }
  34819. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, true, true);
  34820. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34821. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  34822. var position = BABYLON.Vector3.Zero();
  34823. var normal = BABYLON.Vector3.Zero();
  34824. var uv = BABYLON.Vector2.Zero();
  34825. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  34826. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  34827. for (var index = 0; index < positions.length; index += 3) {
  34828. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  34829. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  34830. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  34831. // Compute height
  34832. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  34833. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  34834. var pos = (u + v * heightMapWidth) * 4;
  34835. var r = buffer[pos] / 255.0;
  34836. var g = buffer[pos + 1] / 255.0;
  34837. var b = buffer[pos + 2] / 255.0;
  34838. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  34839. normal.normalize();
  34840. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  34841. position = position.add(normal);
  34842. position.toArray(positions, index);
  34843. }
  34844. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  34845. if (forceUpdate) {
  34846. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  34847. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  34848. }
  34849. else {
  34850. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  34851. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  34852. }
  34853. return this;
  34854. };
  34855. /**
  34856. * Modify the mesh to get a flat shading rendering.
  34857. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  34858. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  34859. * @returns current mesh
  34860. */
  34861. Mesh.prototype.convertToFlatShadedMesh = function () {
  34862. var kinds = this.getVerticesDataKinds();
  34863. var vbs = {};
  34864. var data = {};
  34865. var newdata = {};
  34866. var updatableNormals = false;
  34867. var kindIndex;
  34868. var kind;
  34869. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  34870. kind = kinds[kindIndex];
  34871. var vertexBuffer = this.getVertexBuffer(kind);
  34872. if (kind === BABYLON.VertexBuffer.NormalKind) {
  34873. updatableNormals = vertexBuffer.isUpdatable();
  34874. kinds.splice(kindIndex, 1);
  34875. kindIndex--;
  34876. continue;
  34877. }
  34878. vbs[kind] = vertexBuffer;
  34879. data[kind] = vbs[kind].getData();
  34880. newdata[kind] = [];
  34881. }
  34882. // Save previous submeshes
  34883. var previousSubmeshes = this.subMeshes.slice(0);
  34884. var indices = this.getIndices();
  34885. var totalIndices = this.getTotalIndices();
  34886. // Generating unique vertices per face
  34887. var index;
  34888. for (index = 0; index < totalIndices; index++) {
  34889. var vertexIndex = indices[index];
  34890. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  34891. kind = kinds[kindIndex];
  34892. var stride = vbs[kind].getStrideSize();
  34893. for (var offset = 0; offset < stride; offset++) {
  34894. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  34895. }
  34896. }
  34897. }
  34898. // Updating faces & normal
  34899. var normals = [];
  34900. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  34901. for (index = 0; index < totalIndices; index += 3) {
  34902. indices[index] = index;
  34903. indices[index + 1] = index + 1;
  34904. indices[index + 2] = index + 2;
  34905. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  34906. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  34907. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  34908. var p1p2 = p1.subtract(p2);
  34909. var p3p2 = p3.subtract(p2);
  34910. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  34911. // Store same normals for every vertex
  34912. for (var localIndex = 0; localIndex < 3; localIndex++) {
  34913. normals.push(normal.x);
  34914. normals.push(normal.y);
  34915. normals.push(normal.z);
  34916. }
  34917. }
  34918. this.setIndices(indices);
  34919. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  34920. // Updating vertex buffers
  34921. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  34922. kind = kinds[kindIndex];
  34923. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  34924. }
  34925. // Updating submeshes
  34926. this.releaseSubMeshes();
  34927. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  34928. var previousOne = previousSubmeshes[submeshIndex];
  34929. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  34930. }
  34931. this.synchronizeInstances();
  34932. return this;
  34933. };
  34934. /**
  34935. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  34936. * In other words, more vertices, no more indices and a single bigger VBO.
  34937. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  34938. * @returns current mesh
  34939. */
  34940. Mesh.prototype.convertToUnIndexedMesh = function () {
  34941. var kinds = this.getVerticesDataKinds();
  34942. var vbs = {};
  34943. var data = {};
  34944. var newdata = {};
  34945. var kindIndex;
  34946. var kind;
  34947. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  34948. kind = kinds[kindIndex];
  34949. var vertexBuffer = this.getVertexBuffer(kind);
  34950. vbs[kind] = vertexBuffer;
  34951. data[kind] = vbs[kind].getData();
  34952. newdata[kind] = [];
  34953. }
  34954. // Save previous submeshes
  34955. var previousSubmeshes = this.subMeshes.slice(0);
  34956. var indices = this.getIndices();
  34957. var totalIndices = this.getTotalIndices();
  34958. // Generating unique vertices per face
  34959. var index;
  34960. for (index = 0; index < totalIndices; index++) {
  34961. var vertexIndex = indices[index];
  34962. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  34963. kind = kinds[kindIndex];
  34964. var stride = vbs[kind].getStrideSize();
  34965. for (var offset = 0; offset < stride; offset++) {
  34966. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  34967. }
  34968. }
  34969. }
  34970. // Updating indices
  34971. for (index = 0; index < totalIndices; index += 3) {
  34972. indices[index] = index;
  34973. indices[index + 1] = index + 1;
  34974. indices[index + 2] = index + 2;
  34975. }
  34976. this.setIndices(indices);
  34977. // Updating vertex buffers
  34978. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  34979. kind = kinds[kindIndex];
  34980. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  34981. }
  34982. // Updating submeshes
  34983. this.releaseSubMeshes();
  34984. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  34985. var previousOne = previousSubmeshes[submeshIndex];
  34986. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  34987. }
  34988. this._unIndexed = true;
  34989. this.synchronizeInstances();
  34990. return this;
  34991. };
  34992. /**
  34993. * Inverses facet orientations.
  34994. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  34995. * @param flipNormals will also inverts the normals
  34996. * @returns current mesh
  34997. */
  34998. Mesh.prototype.flipFaces = function (flipNormals) {
  34999. if (flipNormals === void 0) { flipNormals = false; }
  35000. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  35001. var i;
  35002. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  35003. for (i = 0; i < vertex_data.normals.length; i++) {
  35004. vertex_data.normals[i] *= -1;
  35005. }
  35006. }
  35007. if (vertex_data.indices) {
  35008. var temp;
  35009. for (i = 0; i < vertex_data.indices.length; i += 3) {
  35010. // reassign indices
  35011. temp = vertex_data.indices[i + 1];
  35012. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  35013. vertex_data.indices[i + 2] = temp;
  35014. }
  35015. }
  35016. vertex_data.applyToMesh(this);
  35017. return this;
  35018. };
  35019. // Instances
  35020. /**
  35021. * Creates a new InstancedMesh object from the mesh model.
  35022. * @see http://doc.babylonjs.com/how_to/how_to_use_instances
  35023. * @param name defines the name of the new instance
  35024. * @returns a new InstancedMesh
  35025. */
  35026. Mesh.prototype.createInstance = function (name) {
  35027. return new BABYLON.InstancedMesh(name, this);
  35028. };
  35029. /**
  35030. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  35031. * After this call, all the mesh instances have the same submeshes than the current mesh.
  35032. * @returns the current mesh
  35033. */
  35034. Mesh.prototype.synchronizeInstances = function () {
  35035. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  35036. var instance = this.instances[instanceIndex];
  35037. instance._syncSubMeshes();
  35038. }
  35039. return this;
  35040. };
  35041. /**
  35042. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  35043. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  35044. * This should be used together with the simplification to avoid disappearing triangles.
  35045. * @param successCallback an optional success callback to be called after the optimization finished.
  35046. * @returns the current mesh
  35047. */
  35048. Mesh.prototype.optimizeIndices = function (successCallback) {
  35049. var _this = this;
  35050. var indices = this.getIndices();
  35051. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35052. if (!positions || !indices) {
  35053. return this;
  35054. }
  35055. var vectorPositions = new Array();
  35056. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  35057. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  35058. }
  35059. var dupes = new Array();
  35060. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  35061. var realPos = vectorPositions.length - 1 - iteration;
  35062. var testedPosition = vectorPositions[realPos];
  35063. for (var j = 0; j < realPos; ++j) {
  35064. var againstPosition = vectorPositions[j];
  35065. if (testedPosition.equals(againstPosition)) {
  35066. dupes[realPos] = j;
  35067. break;
  35068. }
  35069. }
  35070. }, function () {
  35071. for (var i = 0; i < indices.length; ++i) {
  35072. indices[i] = dupes[indices[i]] || indices[i];
  35073. }
  35074. //indices are now reordered
  35075. var originalSubMeshes = _this.subMeshes.slice(0);
  35076. _this.setIndices(indices);
  35077. _this.subMeshes = originalSubMeshes;
  35078. if (successCallback) {
  35079. successCallback(_this);
  35080. }
  35081. });
  35082. return this;
  35083. };
  35084. /**
  35085. * Serialize current mesh
  35086. * @param serializationObject defines the object which will receive the serialization data
  35087. */
  35088. Mesh.prototype.serialize = function (serializationObject) {
  35089. serializationObject.name = this.name;
  35090. serializationObject.id = this.id;
  35091. serializationObject.type = this.getClassName();
  35092. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  35093. serializationObject.tags = BABYLON.Tags.GetTags(this);
  35094. }
  35095. serializationObject.position = this.position.asArray();
  35096. if (this.rotationQuaternion) {
  35097. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  35098. }
  35099. else if (this.rotation) {
  35100. serializationObject.rotation = this.rotation.asArray();
  35101. }
  35102. serializationObject.scaling = this.scaling.asArray();
  35103. if (this._postMultiplyPivotMatrix) {
  35104. serializationObject.pivotMatrix = this.getPivotMatrix().asArray();
  35105. }
  35106. else {
  35107. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  35108. }
  35109. serializationObject.isEnabled = this.isEnabled(false);
  35110. serializationObject.isVisible = this.isVisible;
  35111. serializationObject.infiniteDistance = this.infiniteDistance;
  35112. serializationObject.pickable = this.isPickable;
  35113. serializationObject.receiveShadows = this.receiveShadows;
  35114. serializationObject.billboardMode = this.billboardMode;
  35115. serializationObject.visibility = this.visibility;
  35116. serializationObject.checkCollisions = this.checkCollisions;
  35117. serializationObject.isBlocker = this.isBlocker;
  35118. // Parent
  35119. if (this.parent) {
  35120. serializationObject.parentId = this.parent.id;
  35121. }
  35122. // Geometry
  35123. serializationObject.isUnIndexed = this.isUnIndexed;
  35124. var geometry = this._geometry;
  35125. if (geometry) {
  35126. var geometryId = geometry.id;
  35127. serializationObject.geometryId = geometryId;
  35128. // SubMeshes
  35129. serializationObject.subMeshes = [];
  35130. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  35131. var subMesh = this.subMeshes[subIndex];
  35132. serializationObject.subMeshes.push({
  35133. materialIndex: subMesh.materialIndex,
  35134. verticesStart: subMesh.verticesStart,
  35135. verticesCount: subMesh.verticesCount,
  35136. indexStart: subMesh.indexStart,
  35137. indexCount: subMesh.indexCount
  35138. });
  35139. }
  35140. }
  35141. // Material
  35142. if (this.material) {
  35143. serializationObject.materialId = this.material.id;
  35144. }
  35145. else {
  35146. this.material = null;
  35147. }
  35148. // Morph targets
  35149. if (this.morphTargetManager) {
  35150. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  35151. }
  35152. // Skeleton
  35153. if (this.skeleton) {
  35154. serializationObject.skeletonId = this.skeleton.id;
  35155. }
  35156. // Physics
  35157. //TODO implement correct serialization for physics impostors.
  35158. var impostor = this.getPhysicsImpostor();
  35159. if (impostor) {
  35160. serializationObject.physicsMass = impostor.getParam("mass");
  35161. serializationObject.physicsFriction = impostor.getParam("friction");
  35162. serializationObject.physicsRestitution = impostor.getParam("mass");
  35163. serializationObject.physicsImpostor = impostor.type;
  35164. }
  35165. // Metadata
  35166. if (this.metadata) {
  35167. serializationObject.metadata = this.metadata;
  35168. }
  35169. // Instances
  35170. serializationObject.instances = [];
  35171. for (var index = 0; index < this.instances.length; index++) {
  35172. var instance = this.instances[index];
  35173. if (instance.doNotSerialize) {
  35174. continue;
  35175. }
  35176. var serializationInstance = {
  35177. name: instance.name,
  35178. id: instance.id,
  35179. position: instance.position.asArray(),
  35180. scaling: instance.scaling.asArray()
  35181. };
  35182. if (instance.parent) {
  35183. serializationInstance.parentId = instance.parent.id;
  35184. }
  35185. if (instance.rotationQuaternion) {
  35186. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  35187. }
  35188. else if (instance.rotation) {
  35189. serializationInstance.rotation = instance.rotation.asArray();
  35190. }
  35191. serializationObject.instances.push(serializationInstance);
  35192. // Animations
  35193. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  35194. serializationInstance.ranges = instance.serializeAnimationRanges();
  35195. }
  35196. //
  35197. // Animations
  35198. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  35199. serializationObject.ranges = this.serializeAnimationRanges();
  35200. // Layer mask
  35201. serializationObject.layerMask = this.layerMask;
  35202. // Alpha
  35203. serializationObject.alphaIndex = this.alphaIndex;
  35204. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  35205. // Overlay
  35206. serializationObject.overlayAlpha = this.overlayAlpha;
  35207. serializationObject.overlayColor = this.overlayColor.asArray();
  35208. serializationObject.renderOverlay = this.renderOverlay;
  35209. // Fog
  35210. serializationObject.applyFog = this.applyFog;
  35211. // Action Manager
  35212. if (this.actionManager) {
  35213. serializationObject.actions = this.actionManager.serialize(this.name);
  35214. }
  35215. };
  35216. /** @hidden */
  35217. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  35218. if (!this.geometry) {
  35219. return;
  35220. }
  35221. this._markSubMeshesAsAttributesDirty();
  35222. var morphTargetManager = this._morphTargetManager;
  35223. if (morphTargetManager && morphTargetManager.vertexCount) {
  35224. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  35225. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  35226. this.morphTargetManager = null;
  35227. return;
  35228. }
  35229. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  35230. var morphTarget = morphTargetManager.getActiveTarget(index);
  35231. var positions = morphTarget.getPositions();
  35232. if (!positions) {
  35233. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  35234. return;
  35235. }
  35236. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  35237. var normals = morphTarget.getNormals();
  35238. if (normals) {
  35239. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  35240. }
  35241. var tangents = morphTarget.getTangents();
  35242. if (tangents) {
  35243. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  35244. }
  35245. }
  35246. }
  35247. else {
  35248. var index = 0;
  35249. // Positions
  35250. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  35251. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  35252. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  35253. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  35254. }
  35255. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  35256. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  35257. }
  35258. index++;
  35259. }
  35260. }
  35261. };
  35262. // Statics
  35263. /**
  35264. * Returns a new Mesh object parsed from the source provided.
  35265. * @param parsedMesh is the source
  35266. * @param scene defines the hosting scene
  35267. * @param rootUrl is the root URL to prefix the `delayLoadingFile` property with
  35268. * @returns a new Mesh
  35269. */
  35270. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  35271. var mesh;
  35272. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  35273. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  35274. }
  35275. else {
  35276. mesh = new Mesh(parsedMesh.name, scene);
  35277. }
  35278. mesh.id = parsedMesh.id;
  35279. if (BABYLON.Tags) {
  35280. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  35281. }
  35282. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  35283. if (parsedMesh.metadata !== undefined) {
  35284. mesh.metadata = parsedMesh.metadata;
  35285. }
  35286. if (parsedMesh.rotationQuaternion) {
  35287. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  35288. }
  35289. else if (parsedMesh.rotation) {
  35290. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  35291. }
  35292. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  35293. if (parsedMesh.localMatrix) {
  35294. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  35295. }
  35296. else if (parsedMesh.pivotMatrix) {
  35297. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  35298. }
  35299. mesh.setEnabled(parsedMesh.isEnabled);
  35300. mesh.isVisible = parsedMesh.isVisible;
  35301. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  35302. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  35303. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  35304. if (parsedMesh.applyFog !== undefined) {
  35305. mesh.applyFog = parsedMesh.applyFog;
  35306. }
  35307. if (parsedMesh.pickable !== undefined) {
  35308. mesh.isPickable = parsedMesh.pickable;
  35309. }
  35310. if (parsedMesh.alphaIndex !== undefined) {
  35311. mesh.alphaIndex = parsedMesh.alphaIndex;
  35312. }
  35313. mesh.receiveShadows = parsedMesh.receiveShadows;
  35314. mesh.billboardMode = parsedMesh.billboardMode;
  35315. if (parsedMesh.visibility !== undefined) {
  35316. mesh.visibility = parsedMesh.visibility;
  35317. }
  35318. mesh.checkCollisions = parsedMesh.checkCollisions;
  35319. if (parsedMesh.isBlocker !== undefined) {
  35320. mesh.isBlocker = parsedMesh.isBlocker;
  35321. }
  35322. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  35323. // freezeWorldMatrix
  35324. if (parsedMesh.freezeWorldMatrix) {
  35325. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  35326. }
  35327. // Parent
  35328. if (parsedMesh.parentId) {
  35329. mesh._waitingParentId = parsedMesh.parentId;
  35330. }
  35331. // Actions
  35332. if (parsedMesh.actions !== undefined) {
  35333. mesh._waitingActions = parsedMesh.actions;
  35334. }
  35335. // Overlay
  35336. if (parsedMesh.overlayAlpha !== undefined) {
  35337. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  35338. }
  35339. if (parsedMesh.overlayColor !== undefined) {
  35340. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  35341. }
  35342. if (parsedMesh.renderOverlay !== undefined) {
  35343. mesh.renderOverlay = parsedMesh.renderOverlay;
  35344. }
  35345. // Geometry
  35346. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  35347. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  35348. if (parsedMesh.delayLoadingFile) {
  35349. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  35350. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  35351. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  35352. if (parsedMesh._binaryInfo) {
  35353. mesh._binaryInfo = parsedMesh._binaryInfo;
  35354. }
  35355. mesh._delayInfo = [];
  35356. if (parsedMesh.hasUVs) {
  35357. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  35358. }
  35359. if (parsedMesh.hasUVs2) {
  35360. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  35361. }
  35362. if (parsedMesh.hasUVs3) {
  35363. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  35364. }
  35365. if (parsedMesh.hasUVs4) {
  35366. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  35367. }
  35368. if (parsedMesh.hasUVs5) {
  35369. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  35370. }
  35371. if (parsedMesh.hasUVs6) {
  35372. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  35373. }
  35374. if (parsedMesh.hasColors) {
  35375. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  35376. }
  35377. if (parsedMesh.hasMatricesIndices) {
  35378. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  35379. }
  35380. if (parsedMesh.hasMatricesWeights) {
  35381. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  35382. }
  35383. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  35384. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  35385. mesh._checkDelayState();
  35386. }
  35387. }
  35388. else {
  35389. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  35390. }
  35391. // Material
  35392. if (parsedMesh.materialId) {
  35393. mesh.setMaterialByID(parsedMesh.materialId);
  35394. }
  35395. else {
  35396. mesh.material = null;
  35397. }
  35398. // Morph targets
  35399. if (parsedMesh.morphTargetManagerId > -1) {
  35400. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  35401. }
  35402. // Skeleton
  35403. if (parsedMesh.skeletonId > -1) {
  35404. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  35405. if (parsedMesh.numBoneInfluencers) {
  35406. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  35407. }
  35408. }
  35409. // Animations
  35410. if (parsedMesh.animations) {
  35411. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  35412. var parsedAnimation = parsedMesh.animations[animationIndex];
  35413. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  35414. }
  35415. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  35416. }
  35417. if (parsedMesh.autoAnimate) {
  35418. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  35419. }
  35420. // Layer Mask
  35421. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  35422. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  35423. }
  35424. else {
  35425. mesh.layerMask = 0x0FFFFFFF;
  35426. }
  35427. // Physics
  35428. if (parsedMesh.physicsImpostor) {
  35429. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  35430. mass: parsedMesh.physicsMass,
  35431. friction: parsedMesh.physicsFriction,
  35432. restitution: parsedMesh.physicsRestitution
  35433. }, scene);
  35434. }
  35435. // Instances
  35436. if (parsedMesh.instances) {
  35437. for (var index = 0; index < parsedMesh.instances.length; index++) {
  35438. var parsedInstance = parsedMesh.instances[index];
  35439. var instance = mesh.createInstance(parsedInstance.name);
  35440. if (parsedInstance.id) {
  35441. instance.id = parsedInstance.id;
  35442. }
  35443. if (BABYLON.Tags) {
  35444. if (parsedInstance.tags) {
  35445. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  35446. }
  35447. else {
  35448. BABYLON.Tags.AddTagsTo(instance, parsedMesh.tags);
  35449. }
  35450. }
  35451. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  35452. if (parsedInstance.parentId) {
  35453. instance._waitingParentId = parsedInstance.parentId;
  35454. }
  35455. if (parsedInstance.rotationQuaternion) {
  35456. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  35457. }
  35458. else if (parsedInstance.rotation) {
  35459. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  35460. }
  35461. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  35462. if (parsedInstance.checkCollisions != undefined && parsedInstance.checkCollisions != null) {
  35463. instance.checkCollisions = parsedInstance.checkCollisions;
  35464. }
  35465. if (parsedInstance.pickable != undefined && parsedInstance.pickable != null) {
  35466. instance.isPickable = parsedInstance.pickable;
  35467. }
  35468. if (parsedInstance.showBoundingBox != undefined && parsedInstance.showBoundingBox != null) {
  35469. instance.showBoundingBox = parsedInstance.showBoundingBox;
  35470. }
  35471. if (parsedInstance.showSubMeshesBoundingBox != undefined && parsedInstance.showSubMeshesBoundingBox != null) {
  35472. instance.showSubMeshesBoundingBox = parsedInstance.showSubMeshesBoundingBox;
  35473. }
  35474. if (parsedInstance.alphaIndex != undefined && parsedInstance.showSubMeshesBoundingBox != null) {
  35475. instance.alphaIndex = parsedInstance.alphaIndex;
  35476. }
  35477. // Physics
  35478. if (parsedInstance.physicsImpostor) {
  35479. instance.physicsImpostor = new BABYLON.PhysicsImpostor(instance, parsedInstance.physicsImpostor, {
  35480. mass: parsedInstance.physicsMass,
  35481. friction: parsedInstance.physicsFriction,
  35482. restitution: parsedInstance.physicsRestitution
  35483. }, scene);
  35484. }
  35485. // Animation
  35486. if (parsedInstance.animations) {
  35487. for (animationIndex = 0; animationIndex < parsedInstance.animations.length; animationIndex++) {
  35488. parsedAnimation = parsedInstance.animations[animationIndex];
  35489. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  35490. }
  35491. BABYLON.Node.ParseAnimationRanges(instance, parsedInstance, scene);
  35492. if (parsedInstance.autoAnimate) {
  35493. scene.beginAnimation(instance, parsedInstance.autoAnimateFrom, parsedInstance.autoAnimateTo, parsedInstance.autoAnimateLoop, parsedInstance.autoAnimateSpeed || 1.0);
  35494. }
  35495. }
  35496. }
  35497. }
  35498. return mesh;
  35499. };
  35500. /**
  35501. * Creates a ribbon mesh. Please consider using the same method from the MeshBuilder class instead
  35502. * @see http://doc.babylonjs.com/how_to/parametric_shapes
  35503. * @param name defines the name of the mesh to create
  35504. * @param pathArray is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  35505. * @param closeArray creates a seam between the first and the last paths of the path array (default is false)
  35506. * @param closePath creates a seam between the first and the last points of each path of the path array
  35507. * @param offset is taken in account only if the `pathArray` is containing a single path
  35508. * @param scene defines the hosting scene
  35509. * @param updatable defines if the mesh must be flagged as updatable
  35510. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  35511. * @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)
  35512. * @returns a new Mesh
  35513. */
  35514. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  35515. if (closeArray === void 0) { closeArray = false; }
  35516. if (updatable === void 0) { updatable = false; }
  35517. return BABYLON.MeshBuilder.CreateRibbon(name, {
  35518. pathArray: pathArray,
  35519. closeArray: closeArray,
  35520. closePath: closePath,
  35521. offset: offset,
  35522. updatable: updatable,
  35523. sideOrientation: sideOrientation,
  35524. instance: instance
  35525. }, scene);
  35526. };
  35527. /**
  35528. * Creates a plane polygonal mesh. By default, this is a disc. Please consider using the same method from the MeshBuilder class instead
  35529. * @param name defines the name of the mesh to create
  35530. * @param radius sets the radius size (float) of the polygon (default 0.5)
  35531. * @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
  35532. * @param scene defines the hosting scene
  35533. * @param updatable defines if the mesh must be flagged as updatable
  35534. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  35535. * @returns a new Mesh
  35536. */
  35537. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  35538. if (scene === void 0) { scene = null; }
  35539. var options = {
  35540. radius: radius,
  35541. tessellation: tessellation,
  35542. sideOrientation: sideOrientation,
  35543. updatable: updatable
  35544. };
  35545. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  35546. };
  35547. /**
  35548. * Creates a box mesh. Please consider using the same method from the MeshBuilder class instead
  35549. * @param name defines the name of the mesh to create
  35550. * @param size sets the size (float) of each box side (default 1)
  35551. * @param scene defines the hosting scene
  35552. * @param updatable defines if the mesh must be flagged as updatable
  35553. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  35554. * @returns a new Mesh
  35555. */
  35556. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  35557. if (scene === void 0) { scene = null; }
  35558. var options = {
  35559. size: size,
  35560. sideOrientation: sideOrientation,
  35561. updatable: updatable
  35562. };
  35563. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  35564. };
  35565. /**
  35566. * Creates a sphere mesh. Please consider using the same method from the MeshBuilder class instead
  35567. * @param name defines the name of the mesh to create
  35568. * @param segments sets the sphere number of horizontal stripes (positive integer, default 32)
  35569. * @param diameter sets the diameter size (float) of the sphere (default 1)
  35570. * @param scene defines the hosting scene
  35571. * @param updatable defines if the mesh must be flagged as updatable
  35572. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  35573. * @returns a new Mesh
  35574. */
  35575. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  35576. var options = {
  35577. segments: segments,
  35578. diameterX: diameter,
  35579. diameterY: diameter,
  35580. diameterZ: diameter,
  35581. sideOrientation: sideOrientation,
  35582. updatable: updatable
  35583. };
  35584. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  35585. };
  35586. /**
  35587. * Creates a cylinder or a cone mesh. Please consider using the same method from the MeshBuilder class instead
  35588. * @param name defines the name of the mesh to create
  35589. * @param height sets the height size (float) of the cylinder/cone (float, default 2)
  35590. * @param diameterTop set the top cap diameter (floats, default 1)
  35591. * @param diameterBottom set the bottom cap diameter (floats, default 1). This value can't be zero
  35592. * @param tessellation sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance
  35593. * @param subdivisions sets the number of rings along the cylinder height (positive integer, default 1)
  35594. * @param scene defines the hosting scene
  35595. * @param updatable defines if the mesh must be flagged as updatable
  35596. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  35597. * @returns a new Mesh
  35598. */
  35599. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  35600. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  35601. if (scene !== undefined) {
  35602. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  35603. updatable = scene;
  35604. }
  35605. scene = subdivisions;
  35606. subdivisions = 1;
  35607. }
  35608. var options = {
  35609. height: height,
  35610. diameterTop: diameterTop,
  35611. diameterBottom: diameterBottom,
  35612. tessellation: tessellation,
  35613. subdivisions: subdivisions,
  35614. sideOrientation: sideOrientation,
  35615. updatable: updatable
  35616. };
  35617. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  35618. };
  35619. // Torus (Code from SharpDX.org)
  35620. /**
  35621. * Creates a torus mesh. Please consider using the same method from the MeshBuilder class instead
  35622. * @param name defines the name of the mesh to create
  35623. * @param diameter sets the diameter size (float) of the torus (default 1)
  35624. * @param thickness sets the diameter size of the tube of the torus (float, default 0.5)
  35625. * @param tessellation sets the number of torus sides (postive integer, default 16)
  35626. * @param scene defines the hosting scene
  35627. * @param updatable defines if the mesh must be flagged as updatable
  35628. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  35629. * @returns a new Mesh
  35630. */
  35631. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  35632. var options = {
  35633. diameter: diameter,
  35634. thickness: thickness,
  35635. tessellation: tessellation,
  35636. sideOrientation: sideOrientation,
  35637. updatable: updatable
  35638. };
  35639. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  35640. };
  35641. /**
  35642. * Creates a torus knot mesh. Please consider using the same method from the MeshBuilder class instead
  35643. * @param name defines the name of the mesh to create
  35644. * @param radius sets the global radius size (float) of the torus knot (default 2)
  35645. * @param tube sets the diameter size of the tube of the torus (float, default 0.5)
  35646. * @param radialSegments sets the number of sides on each tube segments (positive integer, default 32)
  35647. * @param tubularSegments sets the number of tubes to decompose the knot into (positive integer, default 32)
  35648. * @param p the number of windings on X axis (positive integers, default 2)
  35649. * @param q the number of windings on Y axis (positive integers, default 3)
  35650. * @param scene defines the hosting scene
  35651. * @param updatable defines if the mesh must be flagged as updatable
  35652. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  35653. * @returns a new Mesh
  35654. */
  35655. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  35656. var options = {
  35657. radius: radius,
  35658. tube: tube,
  35659. radialSegments: radialSegments,
  35660. tubularSegments: tubularSegments,
  35661. p: p,
  35662. q: q,
  35663. sideOrientation: sideOrientation,
  35664. updatable: updatable
  35665. };
  35666. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  35667. };
  35668. /**
  35669. * Creates a line mesh. Please consider using the same method from the MeshBuilder class instead.
  35670. * @param name defines the name of the mesh to create
  35671. * @param points is an array successive Vector3
  35672. * @param scene defines the hosting scene
  35673. * @param updatable defines if the mesh must be flagged as updatable
  35674. * @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).
  35675. * @returns a new Mesh
  35676. */
  35677. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  35678. if (scene === void 0) { scene = null; }
  35679. if (updatable === void 0) { updatable = false; }
  35680. if (instance === void 0) { instance = null; }
  35681. var options = {
  35682. points: points,
  35683. updatable: updatable,
  35684. instance: instance
  35685. };
  35686. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  35687. };
  35688. /**
  35689. * Creates a dashed line mesh. Please consider using the same method from the MeshBuilder class instead
  35690. * @param name defines the name of the mesh to create
  35691. * @param points is an array successive Vector3
  35692. * @param dashSize is the size of the dashes relatively the dash number (positive float, default 3)
  35693. * @param gapSize is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  35694. * @param dashNb is the intended total number of dashes (positive integer, default 200)
  35695. * @param scene defines the hosting scene
  35696. * @param updatable defines if the mesh must be flagged as updatable
  35697. * @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)
  35698. * @returns a new Mesh
  35699. */
  35700. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  35701. if (scene === void 0) { scene = null; }
  35702. var options = {
  35703. points: points,
  35704. dashSize: dashSize,
  35705. gapSize: gapSize,
  35706. dashNb: dashNb,
  35707. updatable: updatable,
  35708. instance: instance
  35709. };
  35710. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  35711. };
  35712. /**
  35713. * Creates a polygon mesh.
  35714. * Please consider using the same method from the MeshBuilder class instead.
  35715. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  35716. * 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.
  35717. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  35718. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  35719. * Remember you can only change the shape positions, not their number when updating a polygon.
  35720. */
  35721. /**
  35722. * Creates a polygon mesh.Please consider using the same method from the MeshBuilder class instead
  35723. * @see http://doc.babylonjs.com/how_to/parametric_shapes#non-regular-polygon
  35724. * @param name defines the name of the mesh to create
  35725. * @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
  35726. * @param scene defines the hosting scene
  35727. * @param holes is a required array of arrays of successive Vector3 used to defines holes in the polygon
  35728. * @param updatable defines if the mesh must be flagged as updatable
  35729. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  35730. * @returns a new Mesh
  35731. */
  35732. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  35733. var options = {
  35734. shape: shape,
  35735. holes: holes,
  35736. updatable: updatable,
  35737. sideOrientation: sideOrientation
  35738. };
  35739. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  35740. };
  35741. /**
  35742. * Creates an extruded polygon mesh, with depth in the Y direction. Please consider using the same method from the MeshBuilder class instead.
  35743. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-non-regular-polygon
  35744. * @param name defines the name of the mesh to create
  35745. * @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
  35746. * @param depth defines the height of extrusion
  35747. * @param scene defines the hosting scene
  35748. * @param holes is a required array of arrays of successive Vector3 used to defines holes in the polygon
  35749. * @param updatable defines if the mesh must be flagged as updatable
  35750. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  35751. * @returns a new Mesh
  35752. */
  35753. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  35754. var options = {
  35755. shape: shape,
  35756. holes: holes,
  35757. depth: depth,
  35758. updatable: updatable,
  35759. sideOrientation: sideOrientation
  35760. };
  35761. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  35762. };
  35763. /**
  35764. * Creates an extruded shape mesh.
  35765. * 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
  35766. * @see http://doc.babylonjs.com/how_to/parametric_shapes
  35767. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  35768. * @param name defines the name of the mesh to create
  35769. * @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
  35770. * @param path is a required array of successive Vector3. This is the axis curve the shape is extruded along
  35771. * @param scale is the value to scale the shape
  35772. * @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
  35773. * @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
  35774. * @param scene defines the hosting scene
  35775. * @param updatable defines if the mesh must be flagged as updatable
  35776. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  35777. * @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)
  35778. * @returns a new Mesh
  35779. */
  35780. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  35781. if (scene === void 0) { scene = null; }
  35782. var options = {
  35783. shape: shape,
  35784. path: path,
  35785. scale: scale,
  35786. rotation: rotation,
  35787. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  35788. sideOrientation: sideOrientation,
  35789. instance: instance,
  35790. updatable: updatable
  35791. };
  35792. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  35793. };
  35794. /**
  35795. * Creates an custom extruded shape mesh.
  35796. * The custom extrusion is a parametric shape.
  35797. * It has no predefined shape. Its final shape will depend on the input parameters.
  35798. * Please consider using the same method from the MeshBuilder class instead
  35799. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  35800. * @param name defines the name of the mesh to create
  35801. * @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
  35802. * @param path is a required array of successive Vector3. This is the axis curve the shape is extruded along
  35803. * @param scaleFunction is a custom Javascript function called on each path point
  35804. * @param rotationFunction is a custom Javascript function called on each path point
  35805. * @param ribbonCloseArray forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  35806. * @param ribbonClosePath forces the extrusion underlying ribbon to close its `pathArray`
  35807. * @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
  35808. * @param scene defines the hosting scene
  35809. * @param updatable defines if the mesh must be flagged as updatable
  35810. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  35811. * @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)
  35812. * @returns a new Mesh
  35813. */
  35814. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  35815. var options = {
  35816. shape: shape,
  35817. path: path,
  35818. scaleFunction: scaleFunction,
  35819. rotationFunction: rotationFunction,
  35820. ribbonCloseArray: ribbonCloseArray,
  35821. ribbonClosePath: ribbonClosePath,
  35822. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  35823. sideOrientation: sideOrientation,
  35824. instance: instance,
  35825. updatable: updatable
  35826. };
  35827. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  35828. };
  35829. /**
  35830. * Creates lathe mesh.
  35831. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  35832. * Please consider using the same method from the MeshBuilder class instead
  35833. * @param name defines the name of the mesh to create
  35834. * @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
  35835. * @param radius is the radius value of the lathe
  35836. * @param tessellation is the side number of the lathe.
  35837. * @param scene defines the hosting scene
  35838. * @param updatable defines if the mesh must be flagged as updatable
  35839. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  35840. * @returns a new Mesh
  35841. */
  35842. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  35843. var options = {
  35844. shape: shape,
  35845. radius: radius,
  35846. tessellation: tessellation,
  35847. sideOrientation: sideOrientation,
  35848. updatable: updatable
  35849. };
  35850. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  35851. };
  35852. /**
  35853. * Creates a plane mesh. Please consider using the same method from the MeshBuilder class instead
  35854. * @param name defines the name of the mesh to create
  35855. * @param size sets the size (float) of both sides of the plane at once (default 1)
  35856. * @param scene defines the hosting scene
  35857. * @param updatable defines if the mesh must be flagged as updatable
  35858. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  35859. * @returns a new Mesh
  35860. */
  35861. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  35862. var options = {
  35863. size: size,
  35864. width: size,
  35865. height: size,
  35866. sideOrientation: sideOrientation,
  35867. updatable: updatable
  35868. };
  35869. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  35870. };
  35871. /**
  35872. * Creates a ground mesh.
  35873. * Please consider using the same method from the MeshBuilder class instead
  35874. * @param name defines the name of the mesh to create
  35875. * @param width set the width of the ground
  35876. * @param height set the height of the ground
  35877. * @param subdivisions sets the number of subdivisions per side
  35878. * @param scene defines the hosting scene
  35879. * @param updatable defines if the mesh must be flagged as updatable
  35880. * @returns a new Mesh
  35881. */
  35882. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  35883. var options = {
  35884. width: width,
  35885. height: height,
  35886. subdivisions: subdivisions,
  35887. updatable: updatable
  35888. };
  35889. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  35890. };
  35891. /**
  35892. * Creates a tiled ground mesh.
  35893. * Please consider using the same method from the MeshBuilder class instead
  35894. * @param name defines the name of the mesh to create
  35895. * @param xmin set the ground minimum X coordinate
  35896. * @param zmin set the ground minimum Y coordinate
  35897. * @param xmax set the ground maximum X coordinate
  35898. * @param zmax set the ground maximum Z coordinate
  35899. * @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
  35900. * @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
  35901. * @param scene defines the hosting scene
  35902. * @param updatable defines if the mesh must be flagged as updatable
  35903. * @returns a new Mesh
  35904. */
  35905. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  35906. var options = {
  35907. xmin: xmin,
  35908. zmin: zmin,
  35909. xmax: xmax,
  35910. zmax: zmax,
  35911. subdivisions: subdivisions,
  35912. precision: precision,
  35913. updatable: updatable
  35914. };
  35915. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  35916. };
  35917. /**
  35918. * Creates a ground mesh from a height map.
  35919. * Please consider using the same method from the MeshBuilder class instead
  35920. * @see http://doc.babylonjs.com/babylon101/height_map
  35921. * @param name defines the name of the mesh to create
  35922. * @param url sets the URL of the height map image resource
  35923. * @param width set the ground width size
  35924. * @param height set the ground height size
  35925. * @param subdivisions sets the number of subdivision per side
  35926. * @param minHeight is the minimum altitude on the ground
  35927. * @param maxHeight is the maximum altitude on the ground
  35928. * @param scene defines the hosting scene
  35929. * @param updatable defines if the mesh must be flagged as updatable
  35930. * @param onReady is a callback function that will be called once the mesh is built (the height map download can last some time)
  35931. * @param alphaFilter will filter any data where the alpha channel is below this value, defaults 0 (all data visible)
  35932. * @returns a new Mesh
  35933. */
  35934. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady, alphaFilter) {
  35935. var options = {
  35936. width: width,
  35937. height: height,
  35938. subdivisions: subdivisions,
  35939. minHeight: minHeight,
  35940. maxHeight: maxHeight,
  35941. updatable: updatable,
  35942. onReady: onReady,
  35943. alphaFilter: alphaFilter
  35944. };
  35945. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  35946. };
  35947. /**
  35948. * Creates a tube mesh.
  35949. * The tube is a parametric shape.
  35950. * It has no predefined shape. Its final shape will depend on the input parameters.
  35951. * Please consider using the same method from the MeshBuilder class instead
  35952. * @see http://doc.babylonjs.com/how_to/parametric_shapes
  35953. * @param name defines the name of the mesh to create
  35954. * @param path is a required array of successive Vector3. It is the curve used as the axis of the tube
  35955. * @param radius sets the tube radius size
  35956. * @param tessellation is the number of sides on the tubular surface
  35957. * @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
  35958. * @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
  35959. * @param scene defines the hosting scene
  35960. * @param updatable defines if the mesh must be flagged as updatable
  35961. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  35962. * @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)
  35963. * @returns a new Mesh
  35964. */
  35965. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  35966. var options = {
  35967. path: path,
  35968. radius: radius,
  35969. tessellation: tessellation,
  35970. radiusFunction: radiusFunction,
  35971. arc: 1,
  35972. cap: cap,
  35973. updatable: updatable,
  35974. sideOrientation: sideOrientation,
  35975. instance: instance
  35976. };
  35977. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  35978. };
  35979. /**
  35980. * Creates a polyhedron mesh.
  35981. * Please consider using the same method from the MeshBuilder class instead.
  35982. * * 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
  35983. * * The parameter `size` (positive float, default 1) sets the polygon size
  35984. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  35985. * * 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`
  35986. * * 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
  35987. * * 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)`)
  35988. * * 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 : https://doc.babylonjs.com/how_to/createbox_per_face_textures_and_colors
  35989. * * 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
  35990. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  35991. * * 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
  35992. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  35993. * @param name defines the name of the mesh to create
  35994. * @param options defines the options used to create the mesh
  35995. * @param scene defines the hosting scene
  35996. * @returns a new Mesh
  35997. */
  35998. Mesh.CreatePolyhedron = function (name, options, scene) {
  35999. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  36000. };
  36001. /**
  36002. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  36003. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  36004. * * 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`)
  36005. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  36006. * * 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
  36007. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36008. * * 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
  36009. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  36010. * @param name defines the name of the mesh
  36011. * @param options defines the options used to create the mesh
  36012. * @param scene defines the hosting scene
  36013. * @returns a new Mesh
  36014. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  36015. */
  36016. Mesh.CreateIcoSphere = function (name, options, scene) {
  36017. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  36018. };
  36019. /**
  36020. * Creates a decal mesh.
  36021. * Please consider using the same method from the MeshBuilder class instead.
  36022. * A decal is a mesh usually applied as a model onto the surface of another mesh
  36023. * @param name defines the name of the mesh
  36024. * @param sourceMesh defines the mesh receiving the decal
  36025. * @param position sets the position of the decal in world coordinates
  36026. * @param normal sets the normal of the mesh where the decal is applied onto in world coordinates
  36027. * @param size sets the decal scaling
  36028. * @param angle sets the angle to rotate the decal
  36029. * @returns a new Mesh
  36030. */
  36031. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  36032. var options = {
  36033. position: position,
  36034. normal: normal,
  36035. size: size,
  36036. angle: angle
  36037. };
  36038. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  36039. };
  36040. // Skeletons
  36041. /**
  36042. * Prepare internal position array for software CPU skinning
  36043. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh
  36044. */
  36045. Mesh.prototype.setPositionsForCPUSkinning = function () {
  36046. if (!this._sourcePositions) {
  36047. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  36048. if (!source) {
  36049. return this._sourcePositions;
  36050. }
  36051. this._sourcePositions = new Float32Array(source);
  36052. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  36053. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  36054. }
  36055. }
  36056. return this._sourcePositions;
  36057. };
  36058. /**
  36059. * Prepare internal normal array for software CPU skinning
  36060. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  36061. */
  36062. Mesh.prototype.setNormalsForCPUSkinning = function () {
  36063. if (!this._sourceNormals) {
  36064. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  36065. if (!source) {
  36066. return this._sourceNormals;
  36067. }
  36068. this._sourceNormals = new Float32Array(source);
  36069. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  36070. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  36071. }
  36072. }
  36073. return this._sourceNormals;
  36074. };
  36075. /**
  36076. * Updates the vertex buffer by applying transformation from the bones
  36077. * @param skeleton defines the skeleton to apply to current mesh
  36078. * @returns the current mesh
  36079. */
  36080. Mesh.prototype.applySkeleton = function (skeleton) {
  36081. if (!this.geometry) {
  36082. return this;
  36083. }
  36084. if (this.geometry._softwareSkinningFrameId == this.getScene().getFrameId()) {
  36085. return this;
  36086. }
  36087. this.geometry._softwareSkinningFrameId = this.getScene().getFrameId();
  36088. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  36089. return this;
  36090. }
  36091. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  36092. return this;
  36093. }
  36094. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  36095. return this;
  36096. }
  36097. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  36098. return this;
  36099. }
  36100. if (!this._sourcePositions) {
  36101. var submeshes = this.subMeshes.slice();
  36102. this.setPositionsForCPUSkinning();
  36103. this.subMeshes = submeshes;
  36104. }
  36105. if (!this._sourceNormals) {
  36106. this.setNormalsForCPUSkinning();
  36107. }
  36108. // positionsData checks for not being Float32Array will only pass at most once
  36109. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  36110. if (!positionsData) {
  36111. return this;
  36112. }
  36113. if (!(positionsData instanceof Float32Array)) {
  36114. positionsData = new Float32Array(positionsData);
  36115. }
  36116. // normalsData checks for not being Float32Array will only pass at most once
  36117. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  36118. if (!normalsData) {
  36119. return this;
  36120. }
  36121. if (!(normalsData instanceof Float32Array)) {
  36122. normalsData = new Float32Array(normalsData);
  36123. }
  36124. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  36125. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  36126. if (!matricesWeightsData || !matricesIndicesData) {
  36127. return this;
  36128. }
  36129. var needExtras = this.numBoneInfluencers > 4;
  36130. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  36131. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  36132. var skeletonMatrices = skeleton.getTransformMatrices(this);
  36133. var tempVector3 = BABYLON.Vector3.Zero();
  36134. var finalMatrix = new BABYLON.Matrix();
  36135. var tempMatrix = new BABYLON.Matrix();
  36136. var matWeightIdx = 0;
  36137. var inf;
  36138. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  36139. var weight;
  36140. for (inf = 0; inf < 4; inf++) {
  36141. weight = matricesWeightsData[matWeightIdx + inf];
  36142. if (weight > 0) {
  36143. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  36144. finalMatrix.addToSelf(tempMatrix);
  36145. }
  36146. }
  36147. if (needExtras) {
  36148. for (inf = 0; inf < 4; inf++) {
  36149. weight = matricesWeightsExtraData[matWeightIdx + inf];
  36150. if (weight > 0) {
  36151. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  36152. finalMatrix.addToSelf(tempMatrix);
  36153. }
  36154. }
  36155. }
  36156. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  36157. tempVector3.toArray(positionsData, index);
  36158. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  36159. tempVector3.toArray(normalsData, index);
  36160. finalMatrix.reset();
  36161. }
  36162. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  36163. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  36164. return this;
  36165. };
  36166. // Tools
  36167. /**
  36168. * 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
  36169. * @param meshes defines the list of meshes to scan
  36170. * @returns an object `{min:` Vector3`, max:` Vector3`}`
  36171. */
  36172. Mesh.MinMax = function (meshes) {
  36173. var minVector = null;
  36174. var maxVector = null;
  36175. meshes.forEach(function (mesh, index, array) {
  36176. var boundingInfo = mesh.getBoundingInfo();
  36177. var boundingBox = boundingInfo.boundingBox;
  36178. if (!minVector || !maxVector) {
  36179. minVector = boundingBox.minimumWorld;
  36180. maxVector = boundingBox.maximumWorld;
  36181. }
  36182. else {
  36183. minVector.minimizeInPlace(boundingBox.minimumWorld);
  36184. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  36185. }
  36186. });
  36187. if (!minVector || !maxVector) {
  36188. return {
  36189. min: BABYLON.Vector3.Zero(),
  36190. max: BABYLON.Vector3.Zero()
  36191. };
  36192. }
  36193. return {
  36194. min: minVector,
  36195. max: maxVector
  36196. };
  36197. };
  36198. /**
  36199. * Returns the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array
  36200. * @param meshesOrMinMaxVector could be an array of meshes or a `{min:` Vector3`, max:` Vector3`}` object
  36201. * @returns a vector3
  36202. */
  36203. Mesh.Center = function (meshesOrMinMaxVector) {
  36204. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  36205. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  36206. };
  36207. /**
  36208. * Merge the array of meshes into a single mesh for performance reasons.
  36209. * @param meshes defines he vertices source. They should all be of the same material. Entries can empty
  36210. * @param disposeSource when true (default), dispose of the vertices from the source meshes
  36211. * @param allow32BitsIndices when the sum of the vertices > 64k, this must be set to true
  36212. * @param meshSubclass when set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  36213. * @param subdivideWithSubMeshes when true (false default), subdivide mesh to his subMesh array with meshes source.
  36214. * @returns a new mesh
  36215. */
  36216. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  36217. if (disposeSource === void 0) { disposeSource = true; }
  36218. var index;
  36219. if (!allow32BitsIndices) {
  36220. var totalVertices = 0;
  36221. // Counting vertices
  36222. for (index = 0; index < meshes.length; index++) {
  36223. if (meshes[index]) {
  36224. totalVertices += meshes[index].getTotalVertices();
  36225. if (totalVertices > 65536) {
  36226. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  36227. return null;
  36228. }
  36229. }
  36230. }
  36231. }
  36232. // Merge
  36233. var vertexData = null;
  36234. var otherVertexData;
  36235. var indiceArray = new Array();
  36236. var source = null;
  36237. for (index = 0; index < meshes.length; index++) {
  36238. if (meshes[index]) {
  36239. var wm = meshes[index].computeWorldMatrix(true);
  36240. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true, true);
  36241. otherVertexData.transform(wm);
  36242. if (vertexData) {
  36243. vertexData.merge(otherVertexData, allow32BitsIndices);
  36244. }
  36245. else {
  36246. vertexData = otherVertexData;
  36247. source = meshes[index];
  36248. }
  36249. if (subdivideWithSubMeshes) {
  36250. indiceArray.push(meshes[index].getTotalIndices());
  36251. }
  36252. }
  36253. }
  36254. source = source;
  36255. if (!meshSubclass) {
  36256. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  36257. }
  36258. vertexData.applyToMesh(meshSubclass);
  36259. // Setting properties
  36260. meshSubclass.material = source.material;
  36261. meshSubclass.checkCollisions = source.checkCollisions;
  36262. // Cleaning
  36263. if (disposeSource) {
  36264. for (index = 0; index < meshes.length; index++) {
  36265. if (meshes[index]) {
  36266. meshes[index].dispose();
  36267. }
  36268. }
  36269. }
  36270. // Subdivide
  36271. if (subdivideWithSubMeshes) {
  36272. //-- removal of global submesh
  36273. meshSubclass.releaseSubMeshes();
  36274. index = 0;
  36275. var offset = 0;
  36276. //-- apply subdivision according to index table
  36277. while (index < indiceArray.length) {
  36278. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  36279. offset += indiceArray[index];
  36280. index++;
  36281. }
  36282. }
  36283. return meshSubclass;
  36284. };
  36285. /** @hidden */
  36286. Mesh.prototype.addInstance = function (instance) {
  36287. instance._indexInSourceMeshInstanceArray = this.instances.length;
  36288. this.instances.push(instance);
  36289. };
  36290. /** @hidden */
  36291. Mesh.prototype.removeInstance = function (instance) {
  36292. // Remove from mesh
  36293. var index = instance._indexInSourceMeshInstanceArray;
  36294. if (index != -1) {
  36295. if (index !== this.instances.length - 1) {
  36296. var last = this.instances[this.instances.length - 1];
  36297. this.instances[index] = last;
  36298. last._indexInSourceMeshInstanceArray = index;
  36299. }
  36300. instance._indexInSourceMeshInstanceArray = -1;
  36301. this.instances.pop();
  36302. }
  36303. };
  36304. // Consts
  36305. /**
  36306. * Mesh side orientation : usually the external or front surface
  36307. */
  36308. Mesh.FRONTSIDE = 0;
  36309. /**
  36310. * Mesh side orientation : usually the internal or back surface
  36311. */
  36312. Mesh.BACKSIDE = 1;
  36313. /**
  36314. * Mesh side orientation : both internal and external or front and back surfaces
  36315. */
  36316. Mesh.DOUBLESIDE = 2;
  36317. /**
  36318. * Mesh side orientation : by default, `FRONTSIDE`
  36319. */
  36320. Mesh.DEFAULTSIDE = 0;
  36321. /**
  36322. * Mesh cap setting : no cap
  36323. */
  36324. Mesh.NO_CAP = 0;
  36325. /**
  36326. * Mesh cap setting : one cap at the beginning of the mesh
  36327. */
  36328. Mesh.CAP_START = 1;
  36329. /**
  36330. * Mesh cap setting : one cap at the end of the mesh
  36331. */
  36332. Mesh.CAP_END = 2;
  36333. /**
  36334. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  36335. */
  36336. Mesh.CAP_ALL = 3;
  36337. return Mesh;
  36338. }(BABYLON.AbstractMesh));
  36339. BABYLON.Mesh = Mesh;
  36340. })(BABYLON || (BABYLON = {}));
  36341. //# sourceMappingURL=babylon.mesh.js.map
  36342. var BABYLON;
  36343. (function (BABYLON) {
  36344. /**
  36345. * Base class for submeshes
  36346. */
  36347. var BaseSubMesh = /** @class */ (function () {
  36348. function BaseSubMesh() {
  36349. }
  36350. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  36351. /**
  36352. * Gets associated effect
  36353. */
  36354. get: function () {
  36355. return this._materialEffect;
  36356. },
  36357. enumerable: true,
  36358. configurable: true
  36359. });
  36360. /**
  36361. * Sets associated effect (effect used to render this submesh)
  36362. * @param effect defines the effect to associate with
  36363. * @param defines defines the set of defines used to compile this effect
  36364. */
  36365. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  36366. if (defines === void 0) { defines = null; }
  36367. if (this._materialEffect === effect) {
  36368. if (!effect) {
  36369. this._materialDefines = null;
  36370. }
  36371. return;
  36372. }
  36373. this._materialDefines = defines;
  36374. this._materialEffect = effect;
  36375. };
  36376. return BaseSubMesh;
  36377. }());
  36378. BABYLON.BaseSubMesh = BaseSubMesh;
  36379. /**
  36380. * Defines a subdivision inside a mesh
  36381. */
  36382. var SubMesh = /** @class */ (function (_super) {
  36383. __extends(SubMesh, _super);
  36384. /**
  36385. * Creates a new submesh
  36386. * @param materialIndex defines the material index to use
  36387. * @param verticesStart defines vertex index start
  36388. * @param verticesCount defines vertices count
  36389. * @param indexStart defines index start
  36390. * @param indexCount defines indices count
  36391. * @param mesh defines the parent mesh
  36392. * @param renderingMesh defines an optional rendering mesh
  36393. * @param createBoundingBox defines if bounding box should be created for this submesh
  36394. */
  36395. function SubMesh(
  36396. /** the material index to use */
  36397. materialIndex,
  36398. /** vertex index start */
  36399. verticesStart,
  36400. /** vertices count */
  36401. verticesCount,
  36402. /** index start */
  36403. indexStart,
  36404. /** indices count */
  36405. indexCount, mesh, renderingMesh, createBoundingBox) {
  36406. if (createBoundingBox === void 0) { createBoundingBox = true; }
  36407. var _this = _super.call(this) || this;
  36408. _this.materialIndex = materialIndex;
  36409. _this.verticesStart = verticesStart;
  36410. _this.verticesCount = verticesCount;
  36411. _this.indexStart = indexStart;
  36412. _this.indexCount = indexCount;
  36413. /** @hidden */
  36414. _this._renderId = 0;
  36415. _this._mesh = mesh;
  36416. _this._renderingMesh = renderingMesh || mesh;
  36417. mesh.subMeshes.push(_this);
  36418. _this._trianglePlanes = [];
  36419. _this._id = mesh.subMeshes.length - 1;
  36420. if (createBoundingBox) {
  36421. _this.refreshBoundingInfo();
  36422. mesh.computeWorldMatrix(true);
  36423. }
  36424. return _this;
  36425. }
  36426. /**
  36427. * Add a new submesh to a mesh
  36428. * @param materialIndex defines the material index to use
  36429. * @param verticesStart defines vertex index start
  36430. * @param verticesCount defines vertices count
  36431. * @param indexStart defines index start
  36432. * @param indexCount defines indices count
  36433. * @param mesh defines the parent mesh
  36434. * @param renderingMesh defines an optional rendering mesh
  36435. * @param createBoundingBox defines if bounding box should be created for this submesh
  36436. * @returns the new submesh
  36437. */
  36438. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  36439. if (createBoundingBox === void 0) { createBoundingBox = true; }
  36440. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  36441. };
  36442. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  36443. /**
  36444. * Returns true if this submesh covers the entire parent mesh
  36445. * @ignorenaming
  36446. */
  36447. get: function () {
  36448. return (this.verticesStart === 0 && this.verticesCount === this._mesh.getTotalVertices());
  36449. },
  36450. enumerable: true,
  36451. configurable: true
  36452. });
  36453. /**
  36454. * Returns the submesh BoudingInfo object
  36455. * @returns current bounding info (or mesh's one if the submesh is global)
  36456. */
  36457. SubMesh.prototype.getBoundingInfo = function () {
  36458. if (this.IsGlobal) {
  36459. return this._mesh.getBoundingInfo();
  36460. }
  36461. return this._boundingInfo;
  36462. };
  36463. /**
  36464. * Sets the submesh BoundingInfo
  36465. * @param boundingInfo defines the new bounding info to use
  36466. * @returns the SubMesh
  36467. */
  36468. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  36469. this._boundingInfo = boundingInfo;
  36470. return this;
  36471. };
  36472. /**
  36473. * Returns the mesh of the current submesh
  36474. * @return the parent mesh
  36475. */
  36476. SubMesh.prototype.getMesh = function () {
  36477. return this._mesh;
  36478. };
  36479. /**
  36480. * Returns the rendering mesh of the submesh
  36481. * @returns the rendering mesh (could be different from parent mesh)
  36482. */
  36483. SubMesh.prototype.getRenderingMesh = function () {
  36484. return this._renderingMesh;
  36485. };
  36486. /**
  36487. * Returns the submesh material
  36488. * @returns null or the current material
  36489. */
  36490. SubMesh.prototype.getMaterial = function () {
  36491. var rootMaterial = this._renderingMesh.material;
  36492. if (rootMaterial === null || rootMaterial === undefined) {
  36493. return this._mesh.getScene().defaultMaterial;
  36494. }
  36495. else if (rootMaterial.getSubMaterial) {
  36496. var multiMaterial = rootMaterial;
  36497. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  36498. if (this._currentMaterial !== effectiveMaterial) {
  36499. this._currentMaterial = effectiveMaterial;
  36500. this._materialDefines = null;
  36501. }
  36502. return effectiveMaterial;
  36503. }
  36504. return rootMaterial;
  36505. };
  36506. // Methods
  36507. /**
  36508. * Sets a new updated BoundingInfo object to the submesh
  36509. * @returns the SubMesh
  36510. */
  36511. SubMesh.prototype.refreshBoundingInfo = function () {
  36512. this._lastColliderWorldVertices = null;
  36513. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  36514. return this;
  36515. }
  36516. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  36517. if (!data) {
  36518. this._boundingInfo = this._mesh.getBoundingInfo();
  36519. return this;
  36520. }
  36521. var indices = this._renderingMesh.getIndices();
  36522. var extend;
  36523. //is this the only submesh?
  36524. if (this.indexStart === 0 && this.indexCount === indices.length) {
  36525. var boundingInfo = this._renderingMesh.getBoundingInfo();
  36526. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  36527. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  36528. }
  36529. else {
  36530. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  36531. }
  36532. if (this._boundingInfo) {
  36533. this._boundingInfo.reConstruct(extend.minimum, extend.maximum);
  36534. }
  36535. else {
  36536. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  36537. }
  36538. return this;
  36539. };
  36540. /** @hidden */
  36541. SubMesh.prototype._checkCollision = function (collider) {
  36542. var boundingInfo = this.getBoundingInfo();
  36543. return boundingInfo._checkCollision(collider);
  36544. };
  36545. /**
  36546. * Updates the submesh BoundingInfo
  36547. * @param world defines the world matrix to use to update the bounding info
  36548. * @returns the submesh
  36549. */
  36550. SubMesh.prototype.updateBoundingInfo = function (world) {
  36551. var boundingInfo = this.getBoundingInfo();
  36552. if (!boundingInfo) {
  36553. this.refreshBoundingInfo();
  36554. boundingInfo = this.getBoundingInfo();
  36555. }
  36556. boundingInfo.update(world);
  36557. return this;
  36558. };
  36559. /**
  36560. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  36561. * @param frustumPlanes defines the frustum planes
  36562. * @returns true if the submesh is intersecting with the frustum
  36563. */
  36564. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  36565. var boundingInfo = this.getBoundingInfo();
  36566. if (!boundingInfo) {
  36567. return false;
  36568. }
  36569. return boundingInfo.isInFrustum(frustumPlanes, this._mesh.cullingStrategy);
  36570. };
  36571. /**
  36572. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes
  36573. * @param frustumPlanes defines the frustum planes
  36574. * @returns true if the submesh is inside the frustum
  36575. */
  36576. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  36577. var boundingInfo = this.getBoundingInfo();
  36578. if (!boundingInfo) {
  36579. return false;
  36580. }
  36581. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  36582. };
  36583. /**
  36584. * Renders the submesh
  36585. * @param enableAlphaMode defines if alpha needs to be used
  36586. * @returns the submesh
  36587. */
  36588. SubMesh.prototype.render = function (enableAlphaMode) {
  36589. this._renderingMesh.render(this, enableAlphaMode);
  36590. return this;
  36591. };
  36592. /**
  36593. * @hidden
  36594. */
  36595. SubMesh.prototype._getLinesIndexBuffer = function (indices, engine) {
  36596. if (!this._linesIndexBuffer) {
  36597. var linesIndices = [];
  36598. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  36599. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  36600. }
  36601. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  36602. this._linesIndexCount = linesIndices.length;
  36603. }
  36604. return this._linesIndexBuffer;
  36605. };
  36606. /**
  36607. * Checks if the submesh intersects with a ray
  36608. * @param ray defines the ray to test
  36609. * @returns true is the passed ray intersects the submesh bounding box
  36610. */
  36611. SubMesh.prototype.canIntersects = function (ray) {
  36612. var boundingInfo = this.getBoundingInfo();
  36613. if (!boundingInfo) {
  36614. return false;
  36615. }
  36616. return ray.intersectsBox(boundingInfo.boundingBox);
  36617. };
  36618. /**
  36619. * Intersects current submesh with a ray
  36620. * @param ray defines the ray to test
  36621. * @param positions defines mesh's positions array
  36622. * @param indices defines mesh's indices array
  36623. * @param fastCheck defines if only bounding info should be used
  36624. * @returns intersection info or null if no intersection
  36625. */
  36626. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  36627. var material = this.getMaterial();
  36628. if (!material) {
  36629. return null;
  36630. }
  36631. switch (material.fillMode) {
  36632. case BABYLON.Material.PointListDrawMode:
  36633. case BABYLON.Material.LineListDrawMode:
  36634. case BABYLON.Material.LineLoopDrawMode:
  36635. case BABYLON.Material.LineStripDrawMode:
  36636. case BABYLON.Material.TriangleFanDrawMode:
  36637. case BABYLON.Material.TriangleStripDrawMode:
  36638. return null;
  36639. }
  36640. // LineMesh first as it's also a Mesh...
  36641. if (BABYLON.LinesMesh) {
  36642. if (this._mesh.getClassName() === "InstancedLinesMesh" || this._mesh.getClassName() === "LinesMesh") {
  36643. return this._intersectLines(ray, positions, indices, this._mesh.intersectionThreshold, fastCheck);
  36644. }
  36645. }
  36646. return this._intersectTriangles(ray, positions, indices, fastCheck);
  36647. };
  36648. /** @hidden */
  36649. SubMesh.prototype._intersectLines = function (ray, positions, indices, intersectionThreshold, fastCheck) {
  36650. var intersectInfo = null;
  36651. // Line test
  36652. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  36653. var p0 = positions[indices[index]];
  36654. var p1 = positions[indices[index + 1]];
  36655. var length = ray.intersectionSegment(p0, p1, intersectionThreshold);
  36656. if (length < 0) {
  36657. continue;
  36658. }
  36659. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  36660. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  36661. intersectInfo.faceId = index / 2;
  36662. if (fastCheck) {
  36663. break;
  36664. }
  36665. }
  36666. }
  36667. return intersectInfo;
  36668. };
  36669. /** @hidden */
  36670. SubMesh.prototype._intersectTriangles = function (ray, positions, indices, fastCheck) {
  36671. var intersectInfo = null;
  36672. // Triangles test
  36673. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  36674. var p0 = positions[indices[index]];
  36675. var p1 = positions[indices[index + 1]];
  36676. var p2 = positions[indices[index + 2]];
  36677. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  36678. if (currentIntersectInfo) {
  36679. if (currentIntersectInfo.distance < 0) {
  36680. continue;
  36681. }
  36682. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  36683. intersectInfo = currentIntersectInfo;
  36684. intersectInfo.faceId = index / 3;
  36685. if (fastCheck) {
  36686. break;
  36687. }
  36688. }
  36689. }
  36690. }
  36691. return intersectInfo;
  36692. };
  36693. /** @hidden */
  36694. SubMesh.prototype._rebuild = function () {
  36695. if (this._linesIndexBuffer) {
  36696. this._linesIndexBuffer = null;
  36697. }
  36698. };
  36699. // Clone
  36700. /**
  36701. * Creates a new submesh from the passed mesh
  36702. * @param newMesh defines the new hosting mesh
  36703. * @param newRenderingMesh defines an optional rendering mesh
  36704. * @returns the new submesh
  36705. */
  36706. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  36707. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  36708. if (!this.IsGlobal) {
  36709. var boundingInfo = this.getBoundingInfo();
  36710. if (!boundingInfo) {
  36711. return result;
  36712. }
  36713. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  36714. }
  36715. return result;
  36716. };
  36717. // Dispose
  36718. /**
  36719. * Release associated resources
  36720. */
  36721. SubMesh.prototype.dispose = function () {
  36722. if (this._linesIndexBuffer) {
  36723. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  36724. this._linesIndexBuffer = null;
  36725. }
  36726. // Remove from mesh
  36727. var index = this._mesh.subMeshes.indexOf(this);
  36728. this._mesh.subMeshes.splice(index, 1);
  36729. };
  36730. // Statics
  36731. /**
  36732. * Creates a new submesh from indices data
  36733. * @param materialIndex the index of the main mesh material
  36734. * @param startIndex the index where to start the copy in the mesh indices array
  36735. * @param indexCount the number of indices to copy then from the startIndex
  36736. * @param mesh the main mesh to create the submesh from
  36737. * @param renderingMesh the optional rendering mesh
  36738. * @returns a new submesh
  36739. */
  36740. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  36741. var minVertexIndex = Number.MAX_VALUE;
  36742. var maxVertexIndex = -Number.MAX_VALUE;
  36743. renderingMesh = (renderingMesh || mesh);
  36744. var indices = renderingMesh.getIndices();
  36745. for (var index = startIndex; index < startIndex + indexCount; index++) {
  36746. var vertexIndex = indices[index];
  36747. if (vertexIndex < minVertexIndex) {
  36748. minVertexIndex = vertexIndex;
  36749. }
  36750. if (vertexIndex > maxVertexIndex) {
  36751. maxVertexIndex = vertexIndex;
  36752. }
  36753. }
  36754. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  36755. };
  36756. return SubMesh;
  36757. }(BaseSubMesh));
  36758. BABYLON.SubMesh = SubMesh;
  36759. })(BABYLON || (BABYLON = {}));
  36760. //# sourceMappingURL=babylon.subMesh.js.map
  36761. var __assign = (this && this.__assign) || function () {
  36762. __assign = Object.assign || function(t) {
  36763. for (var s, i = 1, n = arguments.length; i < n; i++) {
  36764. s = arguments[i];
  36765. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  36766. t[p] = s[p];
  36767. }
  36768. return t;
  36769. };
  36770. return __assign.apply(this, arguments);
  36771. };
  36772. var BABYLON;
  36773. (function (BABYLON) {
  36774. /**
  36775. * Manages the defines for the Material
  36776. */
  36777. var MaterialDefines = /** @class */ (function () {
  36778. function MaterialDefines() {
  36779. this._isDirty = true;
  36780. /** @hidden */
  36781. this._areLightsDirty = true;
  36782. /** @hidden */
  36783. this._areAttributesDirty = true;
  36784. /** @hidden */
  36785. this._areTexturesDirty = true;
  36786. /** @hidden */
  36787. this._areFresnelDirty = true;
  36788. /** @hidden */
  36789. this._areMiscDirty = true;
  36790. /** @hidden */
  36791. this._areImageProcessingDirty = true;
  36792. /** @hidden */
  36793. this._normals = false;
  36794. /** @hidden */
  36795. this._uvs = false;
  36796. /** @hidden */
  36797. this._needNormals = false;
  36798. /** @hidden */
  36799. this._needUVs = false;
  36800. }
  36801. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  36802. /**
  36803. * Specifies if the material needs to be re-calculated
  36804. */
  36805. get: function () {
  36806. return this._isDirty;
  36807. },
  36808. enumerable: true,
  36809. configurable: true
  36810. });
  36811. /**
  36812. * Marks the material to indicate that it has been re-calculated
  36813. */
  36814. MaterialDefines.prototype.markAsProcessed = function () {
  36815. this._isDirty = false;
  36816. this._areAttributesDirty = false;
  36817. this._areTexturesDirty = false;
  36818. this._areFresnelDirty = false;
  36819. this._areLightsDirty = false;
  36820. this._areMiscDirty = false;
  36821. this._areImageProcessingDirty = false;
  36822. };
  36823. /**
  36824. * Marks the material to indicate that it needs to be re-calculated
  36825. */
  36826. MaterialDefines.prototype.markAsUnprocessed = function () {
  36827. this._isDirty = true;
  36828. };
  36829. /**
  36830. * Marks the material to indicate all of its defines need to be re-calculated
  36831. */
  36832. MaterialDefines.prototype.markAllAsDirty = function () {
  36833. this._areTexturesDirty = true;
  36834. this._areAttributesDirty = true;
  36835. this._areLightsDirty = true;
  36836. this._areFresnelDirty = true;
  36837. this._areMiscDirty = true;
  36838. this._areImageProcessingDirty = true;
  36839. this._isDirty = true;
  36840. };
  36841. /**
  36842. * Marks the material to indicate that image processing needs to be re-calculated
  36843. */
  36844. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  36845. this._areImageProcessingDirty = true;
  36846. this._isDirty = true;
  36847. };
  36848. /**
  36849. * Marks the material to indicate the lights need to be re-calculated
  36850. */
  36851. MaterialDefines.prototype.markAsLightDirty = function () {
  36852. this._areLightsDirty = true;
  36853. this._isDirty = true;
  36854. };
  36855. /**
  36856. * Marks the attribute state as changed
  36857. */
  36858. MaterialDefines.prototype.markAsAttributesDirty = function () {
  36859. this._areAttributesDirty = true;
  36860. this._isDirty = true;
  36861. };
  36862. /**
  36863. * Marks the texture state as changed
  36864. */
  36865. MaterialDefines.prototype.markAsTexturesDirty = function () {
  36866. this._areTexturesDirty = true;
  36867. this._isDirty = true;
  36868. };
  36869. /**
  36870. * Marks the fresnel state as changed
  36871. */
  36872. MaterialDefines.prototype.markAsFresnelDirty = function () {
  36873. this._areFresnelDirty = true;
  36874. this._isDirty = true;
  36875. };
  36876. /**
  36877. * Marks the misc state as changed
  36878. */
  36879. MaterialDefines.prototype.markAsMiscDirty = function () {
  36880. this._areMiscDirty = true;
  36881. this._isDirty = true;
  36882. };
  36883. /**
  36884. * Rebuilds the material defines
  36885. */
  36886. MaterialDefines.prototype.rebuild = function () {
  36887. if (this._keys) {
  36888. delete this._keys;
  36889. }
  36890. this._keys = [];
  36891. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  36892. var key = _a[_i];
  36893. if (key[0] === "_") {
  36894. continue;
  36895. }
  36896. this._keys.push(key);
  36897. }
  36898. };
  36899. /**
  36900. * Specifies if two material defines are equal
  36901. * @param other - A material define instance to compare to
  36902. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  36903. */
  36904. MaterialDefines.prototype.isEqual = function (other) {
  36905. if (this._keys.length !== other._keys.length) {
  36906. return false;
  36907. }
  36908. for (var index = 0; index < this._keys.length; index++) {
  36909. var prop = this._keys[index];
  36910. if (this[prop] !== other[prop]) {
  36911. return false;
  36912. }
  36913. }
  36914. return true;
  36915. };
  36916. /**
  36917. * Clones this instance's defines to another instance
  36918. * @param other - material defines to clone values to
  36919. */
  36920. MaterialDefines.prototype.cloneTo = function (other) {
  36921. if (this._keys.length !== other._keys.length) {
  36922. other._keys = this._keys.slice(0);
  36923. }
  36924. for (var index = 0; index < this._keys.length; index++) {
  36925. var prop = this._keys[index];
  36926. other[prop] = this[prop];
  36927. }
  36928. };
  36929. /**
  36930. * Resets the material define values
  36931. */
  36932. MaterialDefines.prototype.reset = function () {
  36933. for (var index = 0; index < this._keys.length; index++) {
  36934. var prop = this._keys[index];
  36935. var type = typeof this[prop];
  36936. switch (type) {
  36937. case "number":
  36938. this[prop] = 0;
  36939. break;
  36940. case "string":
  36941. this[prop] = "";
  36942. break;
  36943. default:
  36944. this[prop] = false;
  36945. break;
  36946. }
  36947. }
  36948. };
  36949. /**
  36950. * Converts the material define values to a string
  36951. * @returns - String of material define information
  36952. */
  36953. MaterialDefines.prototype.toString = function () {
  36954. var result = "";
  36955. for (var index = 0; index < this._keys.length; index++) {
  36956. var prop = this._keys[index];
  36957. var value = this[prop];
  36958. var type = typeof value;
  36959. switch (type) {
  36960. case "number":
  36961. case "string":
  36962. result += "#define " + prop + " " + value + "\n";
  36963. break;
  36964. default:
  36965. if (value) {
  36966. result += "#define " + prop + "\n";
  36967. }
  36968. break;
  36969. }
  36970. }
  36971. return result;
  36972. };
  36973. return MaterialDefines;
  36974. }());
  36975. BABYLON.MaterialDefines = MaterialDefines;
  36976. /**
  36977. * Base class for the main features of a material in Babylon.js
  36978. */
  36979. var Material = /** @class */ (function () {
  36980. /**
  36981. * Creates a material instance
  36982. * @param name defines the name of the material
  36983. * @param scene defines the scene to reference
  36984. * @param doNotAdd specifies if the material should be added to the scene
  36985. */
  36986. function Material(name, scene, doNotAdd) {
  36987. /**
  36988. * Gets or sets user defined metadata
  36989. */
  36990. this.metadata = null;
  36991. /**
  36992. * For internal use only. Please do not use.
  36993. */
  36994. this.reservedDataStore = null;
  36995. /**
  36996. * Specifies if the ready state should be checked on each call
  36997. */
  36998. this.checkReadyOnEveryCall = false;
  36999. /**
  37000. * Specifies if the ready state should be checked once
  37001. */
  37002. this.checkReadyOnlyOnce = false;
  37003. /**
  37004. * The state of the material
  37005. */
  37006. this.state = "";
  37007. /**
  37008. * The alpha value of the material
  37009. */
  37010. this._alpha = 1.0;
  37011. /**
  37012. * Specifies if back face culling is enabled
  37013. */
  37014. this._backFaceCulling = true;
  37015. /**
  37016. * Specifies if the material should be serialized
  37017. */
  37018. this.doNotSerialize = false;
  37019. /**
  37020. * @hidden
  37021. */
  37022. this._storeEffectOnSubMeshes = false;
  37023. /**
  37024. * An event triggered when the material is disposed
  37025. */
  37026. this.onDisposeObservable = new BABYLON.Observable();
  37027. /**
  37028. * Stores the value of the alpha mode
  37029. */
  37030. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  37031. /**
  37032. * Stores the state of the need depth pre-pass value
  37033. */
  37034. this._needDepthPrePass = false;
  37035. /**
  37036. * Specifies if depth writing should be disabled
  37037. */
  37038. this.disableDepthWrite = false;
  37039. /**
  37040. * Specifies if depth writing should be forced
  37041. */
  37042. this.forceDepthWrite = false;
  37043. /**
  37044. * Specifies if there should be a separate pass for culling
  37045. */
  37046. this.separateCullingPass = false;
  37047. /**
  37048. * Stores the state specifing if fog should be enabled
  37049. */
  37050. this._fogEnabled = true;
  37051. /**
  37052. * Stores the size of points
  37053. */
  37054. this.pointSize = 1.0;
  37055. /**
  37056. * Stores the z offset value
  37057. */
  37058. this.zOffset = 0;
  37059. /**
  37060. * @hidden
  37061. * Specifies if the material was previously ready
  37062. */
  37063. this._wasPreviouslyReady = false;
  37064. /**
  37065. * Stores the fill mode state
  37066. */
  37067. this._fillMode = Material.TriangleFillMode;
  37068. /** @hidden */
  37069. this._indexInSceneMaterialArray = -1;
  37070. this.name = name;
  37071. this.id = name || BABYLON.Tools.RandomId();
  37072. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  37073. this.uniqueId = this._scene.getUniqueId();
  37074. if (this._scene.useRightHandedSystem) {
  37075. this.sideOrientation = Material.ClockWiseSideOrientation;
  37076. }
  37077. else {
  37078. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  37079. }
  37080. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  37081. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  37082. if (!doNotAdd) {
  37083. this._scene.addMaterial(this);
  37084. }
  37085. if (this._scene.useMaterialMeshMap) {
  37086. this.meshMap = {};
  37087. }
  37088. }
  37089. Object.defineProperty(Material, "TriangleFillMode", {
  37090. /**
  37091. * Returns the triangle fill mode
  37092. */
  37093. get: function () {
  37094. return Material._TriangleFillMode;
  37095. },
  37096. enumerable: true,
  37097. configurable: true
  37098. });
  37099. Object.defineProperty(Material, "WireFrameFillMode", {
  37100. /**
  37101. * Returns the wireframe mode
  37102. */
  37103. get: function () {
  37104. return Material._WireFrameFillMode;
  37105. },
  37106. enumerable: true,
  37107. configurable: true
  37108. });
  37109. Object.defineProperty(Material, "PointFillMode", {
  37110. /**
  37111. * Returns the point fill mode
  37112. */
  37113. get: function () {
  37114. return Material._PointFillMode;
  37115. },
  37116. enumerable: true,
  37117. configurable: true
  37118. });
  37119. Object.defineProperty(Material, "PointListDrawMode", {
  37120. /**
  37121. * Returns the point list draw mode
  37122. */
  37123. get: function () {
  37124. return Material._PointListDrawMode;
  37125. },
  37126. enumerable: true,
  37127. configurable: true
  37128. });
  37129. Object.defineProperty(Material, "LineListDrawMode", {
  37130. /**
  37131. * Returns the line list draw mode
  37132. */
  37133. get: function () {
  37134. return Material._LineListDrawMode;
  37135. },
  37136. enumerable: true,
  37137. configurable: true
  37138. });
  37139. Object.defineProperty(Material, "LineLoopDrawMode", {
  37140. /**
  37141. * Returns the line loop draw mode
  37142. */
  37143. get: function () {
  37144. return Material._LineLoopDrawMode;
  37145. },
  37146. enumerable: true,
  37147. configurable: true
  37148. });
  37149. Object.defineProperty(Material, "LineStripDrawMode", {
  37150. /**
  37151. * Returns the line strip draw mode
  37152. */
  37153. get: function () {
  37154. return Material._LineStripDrawMode;
  37155. },
  37156. enumerable: true,
  37157. configurable: true
  37158. });
  37159. Object.defineProperty(Material, "TriangleStripDrawMode", {
  37160. /**
  37161. * Returns the triangle strip draw mode
  37162. */
  37163. get: function () {
  37164. return Material._TriangleStripDrawMode;
  37165. },
  37166. enumerable: true,
  37167. configurable: true
  37168. });
  37169. Object.defineProperty(Material, "TriangleFanDrawMode", {
  37170. /**
  37171. * Returns the triangle fan draw mode
  37172. */
  37173. get: function () {
  37174. return Material._TriangleFanDrawMode;
  37175. },
  37176. enumerable: true,
  37177. configurable: true
  37178. });
  37179. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  37180. /**
  37181. * Returns the clock-wise side orientation
  37182. */
  37183. get: function () {
  37184. return Material._ClockWiseSideOrientation;
  37185. },
  37186. enumerable: true,
  37187. configurable: true
  37188. });
  37189. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  37190. /**
  37191. * Returns the counter clock-wise side orientation
  37192. */
  37193. get: function () {
  37194. return Material._CounterClockWiseSideOrientation;
  37195. },
  37196. enumerable: true,
  37197. configurable: true
  37198. });
  37199. Object.defineProperty(Material.prototype, "alpha", {
  37200. /**
  37201. * Gets the alpha value of the material
  37202. */
  37203. get: function () {
  37204. return this._alpha;
  37205. },
  37206. /**
  37207. * Sets the alpha value of the material
  37208. */
  37209. set: function (value) {
  37210. if (this._alpha === value) {
  37211. return;
  37212. }
  37213. this._alpha = value;
  37214. this.markAsDirty(Material.MiscDirtyFlag);
  37215. },
  37216. enumerable: true,
  37217. configurable: true
  37218. });
  37219. Object.defineProperty(Material.prototype, "backFaceCulling", {
  37220. /**
  37221. * Gets the back-face culling state
  37222. */
  37223. get: function () {
  37224. return this._backFaceCulling;
  37225. },
  37226. /**
  37227. * Sets the back-face culling state
  37228. */
  37229. set: function (value) {
  37230. if (this._backFaceCulling === value) {
  37231. return;
  37232. }
  37233. this._backFaceCulling = value;
  37234. this.markAsDirty(Material.TextureDirtyFlag);
  37235. },
  37236. enumerable: true,
  37237. configurable: true
  37238. });
  37239. Object.defineProperty(Material.prototype, "hasRenderTargetTextures", {
  37240. /**
  37241. * Gets a boolean indicating that current material needs to register RTT
  37242. */
  37243. get: function () {
  37244. return false;
  37245. },
  37246. enumerable: true,
  37247. configurable: true
  37248. });
  37249. Object.defineProperty(Material.prototype, "onDispose", {
  37250. /**
  37251. * Called during a dispose event
  37252. */
  37253. set: function (callback) {
  37254. if (this._onDisposeObserver) {
  37255. this.onDisposeObservable.remove(this._onDisposeObserver);
  37256. }
  37257. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  37258. },
  37259. enumerable: true,
  37260. configurable: true
  37261. });
  37262. Object.defineProperty(Material.prototype, "onBindObservable", {
  37263. /**
  37264. * An event triggered when the material is bound
  37265. */
  37266. get: function () {
  37267. if (!this._onBindObservable) {
  37268. this._onBindObservable = new BABYLON.Observable();
  37269. }
  37270. return this._onBindObservable;
  37271. },
  37272. enumerable: true,
  37273. configurable: true
  37274. });
  37275. Object.defineProperty(Material.prototype, "onBind", {
  37276. /**
  37277. * Called during a bind event
  37278. */
  37279. set: function (callback) {
  37280. if (this._onBindObserver) {
  37281. this.onBindObservable.remove(this._onBindObserver);
  37282. }
  37283. this._onBindObserver = this.onBindObservable.add(callback);
  37284. },
  37285. enumerable: true,
  37286. configurable: true
  37287. });
  37288. Object.defineProperty(Material.prototype, "onUnBindObservable", {
  37289. /**
  37290. * An event triggered when the material is unbound
  37291. */
  37292. get: function () {
  37293. if (!this._onUnBindObservable) {
  37294. this._onUnBindObservable = new BABYLON.Observable();
  37295. }
  37296. return this._onUnBindObservable;
  37297. },
  37298. enumerable: true,
  37299. configurable: true
  37300. });
  37301. Object.defineProperty(Material.prototype, "alphaMode", {
  37302. /**
  37303. * Gets the value of the alpha mode
  37304. */
  37305. get: function () {
  37306. return this._alphaMode;
  37307. },
  37308. /**
  37309. * Sets the value of the alpha mode.
  37310. *
  37311. * | Value | Type | Description |
  37312. * | --- | --- | --- |
  37313. * | 0 | ALPHA_DISABLE | |
  37314. * | 1 | ALPHA_ADD | |
  37315. * | 2 | ALPHA_COMBINE | |
  37316. * | 3 | ALPHA_SUBTRACT | |
  37317. * | 4 | ALPHA_MULTIPLY | |
  37318. * | 5 | ALPHA_MAXIMIZED | |
  37319. * | 6 | ALPHA_ONEONE | |
  37320. * | 7 | ALPHA_PREMULTIPLIED | |
  37321. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  37322. * | 9 | ALPHA_INTERPOLATE | |
  37323. * | 10 | ALPHA_SCREENMODE | |
  37324. *
  37325. */
  37326. set: function (value) {
  37327. if (this._alphaMode === value) {
  37328. return;
  37329. }
  37330. this._alphaMode = value;
  37331. this.markAsDirty(Material.TextureDirtyFlag);
  37332. },
  37333. enumerable: true,
  37334. configurable: true
  37335. });
  37336. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  37337. /**
  37338. * Gets the depth pre-pass value
  37339. */
  37340. get: function () {
  37341. return this._needDepthPrePass;
  37342. },
  37343. /**
  37344. * Sets the need depth pre-pass value
  37345. */
  37346. set: function (value) {
  37347. if (this._needDepthPrePass === value) {
  37348. return;
  37349. }
  37350. this._needDepthPrePass = value;
  37351. if (this._needDepthPrePass) {
  37352. this.checkReadyOnEveryCall = true;
  37353. }
  37354. },
  37355. enumerable: true,
  37356. configurable: true
  37357. });
  37358. Object.defineProperty(Material.prototype, "fogEnabled", {
  37359. /**
  37360. * Gets the value of the fog enabled state
  37361. */
  37362. get: function () {
  37363. return this._fogEnabled;
  37364. },
  37365. /**
  37366. * Sets the state for enabling fog
  37367. */
  37368. set: function (value) {
  37369. if (this._fogEnabled === value) {
  37370. return;
  37371. }
  37372. this._fogEnabled = value;
  37373. this.markAsDirty(Material.MiscDirtyFlag);
  37374. },
  37375. enumerable: true,
  37376. configurable: true
  37377. });
  37378. Object.defineProperty(Material.prototype, "wireframe", {
  37379. /**
  37380. * Gets a value specifying if wireframe mode is enabled
  37381. */
  37382. get: function () {
  37383. switch (this._fillMode) {
  37384. case Material.WireFrameFillMode:
  37385. case Material.LineListDrawMode:
  37386. case Material.LineLoopDrawMode:
  37387. case Material.LineStripDrawMode:
  37388. return true;
  37389. }
  37390. return this._scene.forceWireframe;
  37391. },
  37392. /**
  37393. * Sets the state of wireframe mode
  37394. */
  37395. set: function (value) {
  37396. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  37397. },
  37398. enumerable: true,
  37399. configurable: true
  37400. });
  37401. Object.defineProperty(Material.prototype, "pointsCloud", {
  37402. /**
  37403. * Gets the value specifying if point clouds are enabled
  37404. */
  37405. get: function () {
  37406. switch (this._fillMode) {
  37407. case Material.PointFillMode:
  37408. case Material.PointListDrawMode:
  37409. return true;
  37410. }
  37411. return this._scene.forcePointsCloud;
  37412. },
  37413. /**
  37414. * Sets the state of point cloud mode
  37415. */
  37416. set: function (value) {
  37417. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  37418. },
  37419. enumerable: true,
  37420. configurable: true
  37421. });
  37422. Object.defineProperty(Material.prototype, "fillMode", {
  37423. /**
  37424. * Gets the material fill mode
  37425. */
  37426. get: function () {
  37427. return this._fillMode;
  37428. },
  37429. /**
  37430. * Sets the material fill mode
  37431. */
  37432. set: function (value) {
  37433. if (this._fillMode === value) {
  37434. return;
  37435. }
  37436. this._fillMode = value;
  37437. this.markAsDirty(Material.MiscDirtyFlag);
  37438. },
  37439. enumerable: true,
  37440. configurable: true
  37441. });
  37442. /**
  37443. * Returns a string representation of the current material
  37444. * @param fullDetails defines a boolean indicating which levels of logging is desired
  37445. * @returns a string with material information
  37446. */
  37447. Material.prototype.toString = function (fullDetails) {
  37448. var ret = "Name: " + this.name;
  37449. if (fullDetails) {
  37450. }
  37451. return ret;
  37452. };
  37453. /**
  37454. * Gets the class name of the material
  37455. * @returns a string with the class name of the material
  37456. */
  37457. Material.prototype.getClassName = function () {
  37458. return "Material";
  37459. };
  37460. Object.defineProperty(Material.prototype, "isFrozen", {
  37461. /**
  37462. * Specifies if updates for the material been locked
  37463. */
  37464. get: function () {
  37465. return this.checkReadyOnlyOnce;
  37466. },
  37467. enumerable: true,
  37468. configurable: true
  37469. });
  37470. /**
  37471. * Locks updates for the material
  37472. */
  37473. Material.prototype.freeze = function () {
  37474. this.checkReadyOnlyOnce = true;
  37475. };
  37476. /**
  37477. * Unlocks updates for the material
  37478. */
  37479. Material.prototype.unfreeze = function () {
  37480. this.checkReadyOnlyOnce = false;
  37481. };
  37482. /**
  37483. * Specifies if the material is ready to be used
  37484. * @param mesh defines the mesh to check
  37485. * @param useInstances specifies if instances should be used
  37486. * @returns a boolean indicating if the material is ready to be used
  37487. */
  37488. Material.prototype.isReady = function (mesh, useInstances) {
  37489. return true;
  37490. };
  37491. /**
  37492. * Specifies that the submesh is ready to be used
  37493. * @param mesh defines the mesh to check
  37494. * @param subMesh defines which submesh to check
  37495. * @param useInstances specifies that instances should be used
  37496. * @returns a boolean indicating that the submesh is ready or not
  37497. */
  37498. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  37499. return false;
  37500. };
  37501. /**
  37502. * Returns the material effect
  37503. * @returns the effect associated with the material
  37504. */
  37505. Material.prototype.getEffect = function () {
  37506. return this._effect;
  37507. };
  37508. /**
  37509. * Returns the current scene
  37510. * @returns a Scene
  37511. */
  37512. Material.prototype.getScene = function () {
  37513. return this._scene;
  37514. };
  37515. /**
  37516. * Specifies if the material will require alpha blending
  37517. * @returns a boolean specifying if alpha blending is needed
  37518. */
  37519. Material.prototype.needAlphaBlending = function () {
  37520. return (this.alpha < 1.0);
  37521. };
  37522. /**
  37523. * Specifies if the mesh will require alpha blending
  37524. * @param mesh defines the mesh to check
  37525. * @returns a boolean specifying if alpha blending is needed for the mesh
  37526. */
  37527. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  37528. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  37529. };
  37530. /**
  37531. * Specifies if this material should be rendered in alpha test mode
  37532. * @returns a boolean specifying if an alpha test is needed.
  37533. */
  37534. Material.prototype.needAlphaTesting = function () {
  37535. return false;
  37536. };
  37537. /**
  37538. * Gets the texture used for the alpha test
  37539. * @returns the texture to use for alpha testing
  37540. */
  37541. Material.prototype.getAlphaTestTexture = function () {
  37542. return null;
  37543. };
  37544. /**
  37545. * Marks the material to indicate that it needs to be re-calculated
  37546. */
  37547. Material.prototype.markDirty = function () {
  37548. this._wasPreviouslyReady = false;
  37549. };
  37550. /** @hidden */
  37551. Material.prototype._preBind = function (effect, overrideOrientation) {
  37552. if (overrideOrientation === void 0) { overrideOrientation = null; }
  37553. var engine = this._scene.getEngine();
  37554. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  37555. var reverse = orientation === Material.ClockWiseSideOrientation;
  37556. engine.enableEffect(effect ? effect : this._effect);
  37557. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  37558. return reverse;
  37559. };
  37560. /**
  37561. * Binds the material to the mesh
  37562. * @param world defines the world transformation matrix
  37563. * @param mesh defines the mesh to bind the material to
  37564. */
  37565. Material.prototype.bind = function (world, mesh) {
  37566. };
  37567. /**
  37568. * Binds the submesh to the material
  37569. * @param world defines the world transformation matrix
  37570. * @param mesh defines the mesh containing the submesh
  37571. * @param subMesh defines the submesh to bind the material to
  37572. */
  37573. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  37574. };
  37575. /**
  37576. * Binds the world matrix to the material
  37577. * @param world defines the world transformation matrix
  37578. */
  37579. Material.prototype.bindOnlyWorldMatrix = function (world) {
  37580. };
  37581. /**
  37582. * Binds the scene's uniform buffer to the effect.
  37583. * @param effect defines the effect to bind to the scene uniform buffer
  37584. * @param sceneUbo defines the uniform buffer storing scene data
  37585. */
  37586. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  37587. sceneUbo.bindToEffect(effect, "Scene");
  37588. };
  37589. /**
  37590. * Binds the view matrix to the effect
  37591. * @param effect defines the effect to bind the view matrix to
  37592. */
  37593. Material.prototype.bindView = function (effect) {
  37594. if (!this._useUBO) {
  37595. effect.setMatrix("view", this.getScene().getViewMatrix());
  37596. }
  37597. else {
  37598. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  37599. }
  37600. };
  37601. /**
  37602. * Binds the view projection matrix to the effect
  37603. * @param effect defines the effect to bind the view projection matrix to
  37604. */
  37605. Material.prototype.bindViewProjection = function (effect) {
  37606. if (!this._useUBO) {
  37607. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  37608. }
  37609. else {
  37610. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  37611. }
  37612. };
  37613. /**
  37614. * Specifies if material alpha testing should be turned on for the mesh
  37615. * @param mesh defines the mesh to check
  37616. */
  37617. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  37618. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  37619. };
  37620. /**
  37621. * Processes to execute after binding the material to a mesh
  37622. * @param mesh defines the rendered mesh
  37623. */
  37624. Material.prototype._afterBind = function (mesh) {
  37625. this._scene._cachedMaterial = this;
  37626. if (mesh) {
  37627. this._scene._cachedVisibility = mesh.visibility;
  37628. }
  37629. else {
  37630. this._scene._cachedVisibility = 1;
  37631. }
  37632. if (this._onBindObservable && mesh) {
  37633. this._onBindObservable.notifyObservers(mesh);
  37634. }
  37635. if (this.disableDepthWrite) {
  37636. var engine = this._scene.getEngine();
  37637. this._cachedDepthWriteState = engine.getDepthWrite();
  37638. engine.setDepthWrite(false);
  37639. }
  37640. };
  37641. /**
  37642. * Unbinds the material from the mesh
  37643. */
  37644. Material.prototype.unbind = function () {
  37645. if (this._onUnBindObservable) {
  37646. this._onUnBindObservable.notifyObservers(this);
  37647. }
  37648. if (this.disableDepthWrite) {
  37649. var engine = this._scene.getEngine();
  37650. engine.setDepthWrite(this._cachedDepthWriteState);
  37651. }
  37652. };
  37653. /**
  37654. * Gets the active textures from the material
  37655. * @returns an array of textures
  37656. */
  37657. Material.prototype.getActiveTextures = function () {
  37658. return [];
  37659. };
  37660. /**
  37661. * Specifies if the material uses a texture
  37662. * @param texture defines the texture to check against the material
  37663. * @returns a boolean specifying if the material uses the texture
  37664. */
  37665. Material.prototype.hasTexture = function (texture) {
  37666. return false;
  37667. };
  37668. /**
  37669. * Makes a duplicate of the material, and gives it a new name
  37670. * @param name defines the new name for the duplicated material
  37671. * @returns the cloned material
  37672. */
  37673. Material.prototype.clone = function (name) {
  37674. return null;
  37675. };
  37676. /**
  37677. * Gets the meshes bound to the material
  37678. * @returns an array of meshes bound to the material
  37679. */
  37680. Material.prototype.getBindedMeshes = function () {
  37681. var _this = this;
  37682. if (this.meshMap) {
  37683. var result = new Array();
  37684. for (var meshId in this.meshMap) {
  37685. var mesh = this.meshMap[meshId];
  37686. if (mesh) {
  37687. result.push(mesh);
  37688. }
  37689. }
  37690. return result;
  37691. }
  37692. else {
  37693. var meshes = this._scene.meshes;
  37694. return meshes.filter(function (mesh) { return mesh.material === _this; });
  37695. }
  37696. };
  37697. /**
  37698. * Force shader compilation
  37699. * @param mesh defines the mesh associated with this material
  37700. * @param onCompiled defines a function to execute once the material is compiled
  37701. * @param options defines the options to configure the compilation
  37702. */
  37703. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  37704. var _this = this;
  37705. var localOptions = __assign({ clipPlane: false }, options);
  37706. var subMesh = new BABYLON.BaseSubMesh();
  37707. var scene = this.getScene();
  37708. var checkReady = function () {
  37709. if (!_this._scene || !_this._scene.getEngine()) {
  37710. return;
  37711. }
  37712. if (subMesh._materialDefines) {
  37713. subMesh._materialDefines._renderId = -1;
  37714. }
  37715. var clipPlaneState = scene.clipPlane;
  37716. if (localOptions.clipPlane) {
  37717. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  37718. }
  37719. if (_this._storeEffectOnSubMeshes) {
  37720. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  37721. if (onCompiled) {
  37722. onCompiled(_this);
  37723. }
  37724. }
  37725. else {
  37726. setTimeout(checkReady, 16);
  37727. }
  37728. }
  37729. else {
  37730. if (_this.isReady(mesh)) {
  37731. if (onCompiled) {
  37732. onCompiled(_this);
  37733. }
  37734. }
  37735. else {
  37736. setTimeout(checkReady, 16);
  37737. }
  37738. }
  37739. if (localOptions.clipPlane) {
  37740. scene.clipPlane = clipPlaneState;
  37741. }
  37742. };
  37743. checkReady();
  37744. };
  37745. /**
  37746. * Force shader compilation
  37747. * @param mesh defines the mesh that will use this material
  37748. * @param options defines additional options for compiling the shaders
  37749. * @returns a promise that resolves when the compilation completes
  37750. */
  37751. Material.prototype.forceCompilationAsync = function (mesh, options) {
  37752. var _this = this;
  37753. return new Promise(function (resolve) {
  37754. _this.forceCompilation(mesh, function () {
  37755. resolve();
  37756. }, options);
  37757. });
  37758. };
  37759. /**
  37760. * Marks a define in the material to indicate that it needs to be re-computed
  37761. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  37762. */
  37763. Material.prototype.markAsDirty = function (flag) {
  37764. if (this.getScene().blockMaterialDirtyMechanism) {
  37765. return;
  37766. }
  37767. Material._DirtyCallbackArray.length = 0;
  37768. if (flag & Material.TextureDirtyFlag) {
  37769. Material._DirtyCallbackArray.push(Material._TextureDirtyCallBack);
  37770. }
  37771. if (flag & Material.LightDirtyFlag) {
  37772. Material._DirtyCallbackArray.push(Material._LightsDirtyCallBack);
  37773. }
  37774. if (flag & Material.FresnelDirtyFlag) {
  37775. Material._DirtyCallbackArray.push(Material._FresnelDirtyCallBack);
  37776. }
  37777. if (flag & Material.AttributesDirtyFlag) {
  37778. Material._DirtyCallbackArray.push(Material._AttributeDirtyCallBack);
  37779. }
  37780. if (flag & Material.MiscDirtyFlag) {
  37781. Material._DirtyCallbackArray.push(Material._MiscDirtyCallBack);
  37782. }
  37783. if (Material._DirtyCallbackArray.length) {
  37784. this._markAllSubMeshesAsDirty(Material._RunDirtyCallBacks);
  37785. }
  37786. this.getScene().resetCachedMaterial();
  37787. };
  37788. /**
  37789. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  37790. * @param func defines a function which checks material defines against the submeshes
  37791. */
  37792. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  37793. if (this.getScene().blockMaterialDirtyMechanism) {
  37794. return;
  37795. }
  37796. var meshes = this.getScene().meshes;
  37797. for (var _i = 0, meshes_1 = meshes; _i < meshes_1.length; _i++) {
  37798. var mesh = meshes_1[_i];
  37799. if (!mesh.subMeshes) {
  37800. continue;
  37801. }
  37802. for (var _a = 0, _b = mesh.subMeshes; _a < _b.length; _a++) {
  37803. var subMesh = _b[_a];
  37804. if (subMesh.getMaterial() !== this) {
  37805. continue;
  37806. }
  37807. if (!subMesh._materialDefines) {
  37808. continue;
  37809. }
  37810. func(subMesh._materialDefines);
  37811. }
  37812. }
  37813. };
  37814. /**
  37815. * Indicates that image processing needs to be re-calculated for all submeshes
  37816. */
  37817. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  37818. this._markAllSubMeshesAsDirty(Material._ImageProcessingDirtyCallBack);
  37819. };
  37820. /**
  37821. * Indicates that textures need to be re-calculated for all submeshes
  37822. */
  37823. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  37824. this._markAllSubMeshesAsDirty(Material._TextureDirtyCallBack);
  37825. };
  37826. /**
  37827. * Indicates that fresnel needs to be re-calculated for all submeshes
  37828. */
  37829. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  37830. this._markAllSubMeshesAsDirty(Material._FresnelDirtyCallBack);
  37831. };
  37832. /**
  37833. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  37834. */
  37835. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  37836. this._markAllSubMeshesAsDirty(Material._FresnelAndMiscDirtyCallBack);
  37837. };
  37838. /**
  37839. * Indicates that lights need to be re-calculated for all submeshes
  37840. */
  37841. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  37842. this._markAllSubMeshesAsDirty(Material._LightsDirtyCallBack);
  37843. };
  37844. /**
  37845. * Indicates that attributes need to be re-calculated for all submeshes
  37846. */
  37847. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  37848. this._markAllSubMeshesAsDirty(Material._AttributeDirtyCallBack);
  37849. };
  37850. /**
  37851. * Indicates that misc needs to be re-calculated for all submeshes
  37852. */
  37853. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  37854. this._markAllSubMeshesAsDirty(Material._MiscDirtyCallBack);
  37855. };
  37856. /**
  37857. * Indicates that textures and misc need to be re-calculated for all submeshes
  37858. */
  37859. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  37860. this._markAllSubMeshesAsDirty(Material._TextureAndMiscDirtyCallBack);
  37861. };
  37862. /**
  37863. * Disposes the material
  37864. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  37865. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  37866. * @param notBoundToMesh specifies if the material that is being disposed is known to be not bound to any mesh
  37867. */
  37868. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures, notBoundToMesh) {
  37869. var scene = this.getScene();
  37870. // Animations
  37871. scene.stopAnimation(this);
  37872. scene.freeProcessedMaterials();
  37873. // Remove from scene
  37874. scene.removeMaterial(this);
  37875. if (notBoundToMesh !== true) {
  37876. // Remove from meshes
  37877. if (this.meshMap) {
  37878. for (var meshId in this.meshMap) {
  37879. var mesh = this.meshMap[meshId];
  37880. if (mesh) {
  37881. mesh.material = null; // will set the entry in the map to undefined
  37882. this.releaseVertexArrayObject(mesh, forceDisposeEffect);
  37883. }
  37884. }
  37885. }
  37886. else {
  37887. var meshes = scene.meshes;
  37888. for (var _i = 0, meshes_2 = meshes; _i < meshes_2.length; _i++) {
  37889. var mesh = meshes_2[_i];
  37890. if (mesh.material === this) {
  37891. mesh.material = null;
  37892. this.releaseVertexArrayObject(mesh, forceDisposeEffect);
  37893. }
  37894. }
  37895. }
  37896. }
  37897. this._uniformBuffer.dispose();
  37898. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  37899. if (forceDisposeEffect && this._effect) {
  37900. if (!this._storeEffectOnSubMeshes) {
  37901. scene.getEngine()._releaseEffect(this._effect);
  37902. }
  37903. this._effect = null;
  37904. }
  37905. // Callback
  37906. this.onDisposeObservable.notifyObservers(this);
  37907. this.onDisposeObservable.clear();
  37908. if (this._onBindObservable) {
  37909. this._onBindObservable.clear();
  37910. }
  37911. if (this._onUnBindObservable) {
  37912. this._onUnBindObservable.clear();
  37913. }
  37914. };
  37915. /** @hidden */
  37916. Material.prototype.releaseVertexArrayObject = function (mesh, forceDisposeEffect) {
  37917. if (mesh.geometry) {
  37918. var geometry = (mesh.geometry);
  37919. var scene = this.getScene();
  37920. if (this._storeEffectOnSubMeshes) {
  37921. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  37922. var subMesh = _a[_i];
  37923. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  37924. if (forceDisposeEffect && subMesh._materialEffect) {
  37925. scene.getEngine()._releaseEffect(subMesh._materialEffect);
  37926. }
  37927. }
  37928. }
  37929. else {
  37930. geometry._releaseVertexArrayObject(this._effect);
  37931. }
  37932. }
  37933. };
  37934. /**
  37935. * Serializes this material
  37936. * @returns the serialized material object
  37937. */
  37938. Material.prototype.serialize = function () {
  37939. return BABYLON.SerializationHelper.Serialize(this);
  37940. };
  37941. /**
  37942. * Creates a MultiMaterial from parsed MultiMaterial data.
  37943. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  37944. * @param scene defines the hosting scene
  37945. * @returns a new MultiMaterial
  37946. */
  37947. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  37948. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  37949. multiMaterial.id = parsedMultiMaterial.id;
  37950. if (BABYLON.Tags) {
  37951. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  37952. }
  37953. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  37954. var subMatId = parsedMultiMaterial.materials[matIndex];
  37955. if (subMatId) {
  37956. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  37957. }
  37958. else {
  37959. multiMaterial.subMaterials.push(null);
  37960. }
  37961. }
  37962. return multiMaterial;
  37963. };
  37964. /**
  37965. * Creates a material from parsed material data
  37966. * @param parsedMaterial defines parsed material data
  37967. * @param scene defines the hosting scene
  37968. * @param rootUrl defines the root URL to use to load textures
  37969. * @returns a new material
  37970. */
  37971. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  37972. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  37973. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  37974. }
  37975. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  37976. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  37977. if (!BABYLON.LegacyPBRMaterial) {
  37978. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  37979. return;
  37980. }
  37981. }
  37982. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  37983. return materialType.Parse(parsedMaterial, scene, rootUrl);
  37984. };
  37985. // Triangle views
  37986. Material._TriangleFillMode = 0;
  37987. Material._WireFrameFillMode = 1;
  37988. Material._PointFillMode = 2;
  37989. // Draw modes
  37990. Material._PointListDrawMode = 3;
  37991. Material._LineListDrawMode = 4;
  37992. Material._LineLoopDrawMode = 5;
  37993. Material._LineStripDrawMode = 6;
  37994. Material._TriangleStripDrawMode = 7;
  37995. Material._TriangleFanDrawMode = 8;
  37996. /**
  37997. * Stores the clock-wise side orientation
  37998. */
  37999. Material._ClockWiseSideOrientation = 0;
  38000. /**
  38001. * Stores the counter clock-wise side orientation
  38002. */
  38003. Material._CounterClockWiseSideOrientation = 1;
  38004. /**
  38005. * The dirty texture flag value
  38006. */
  38007. Material.TextureDirtyFlag = 1;
  38008. /**
  38009. * The dirty light flag value
  38010. */
  38011. Material.LightDirtyFlag = 2;
  38012. /**
  38013. * The dirty fresnel flag value
  38014. */
  38015. Material.FresnelDirtyFlag = 4;
  38016. /**
  38017. * The dirty attribute flag value
  38018. */
  38019. Material.AttributesDirtyFlag = 8;
  38020. /**
  38021. * The dirty misc flag value
  38022. */
  38023. Material.MiscDirtyFlag = 16;
  38024. /**
  38025. * The all dirty flag value
  38026. */
  38027. Material.AllDirtyFlag = 31;
  38028. Material._ImageProcessingDirtyCallBack = function (defines) { return defines.markAsImageProcessingDirty(); };
  38029. Material._TextureDirtyCallBack = function (defines) { return defines.markAsTexturesDirty(); };
  38030. Material._FresnelDirtyCallBack = function (defines) { return defines.markAsFresnelDirty(); };
  38031. Material._MiscDirtyCallBack = function (defines) { return defines.markAsMiscDirty(); };
  38032. Material._LightsDirtyCallBack = function (defines) { return defines.markAsLightDirty(); };
  38033. Material._AttributeDirtyCallBack = function (defines) { return defines.markAsAttributesDirty(); };
  38034. Material._FresnelAndMiscDirtyCallBack = function (defines) {
  38035. Material._FresnelDirtyCallBack(defines);
  38036. Material._MiscDirtyCallBack(defines);
  38037. };
  38038. Material._TextureAndMiscDirtyCallBack = function (defines) {
  38039. Material._TextureDirtyCallBack(defines);
  38040. Material._MiscDirtyCallBack(defines);
  38041. };
  38042. Material._DirtyCallbackArray = [];
  38043. Material._RunDirtyCallBacks = function (defines) {
  38044. for (var _i = 0, _a = Material._DirtyCallbackArray; _i < _a.length; _i++) {
  38045. var cb = _a[_i];
  38046. cb(defines);
  38047. }
  38048. };
  38049. __decorate([
  38050. BABYLON.serialize()
  38051. ], Material.prototype, "id", void 0);
  38052. __decorate([
  38053. BABYLON.serialize()
  38054. ], Material.prototype, "uniqueId", void 0);
  38055. __decorate([
  38056. BABYLON.serialize()
  38057. ], Material.prototype, "name", void 0);
  38058. __decorate([
  38059. BABYLON.serialize()
  38060. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  38061. __decorate([
  38062. BABYLON.serialize()
  38063. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  38064. __decorate([
  38065. BABYLON.serialize()
  38066. ], Material.prototype, "state", void 0);
  38067. __decorate([
  38068. BABYLON.serialize("alpha")
  38069. ], Material.prototype, "_alpha", void 0);
  38070. __decorate([
  38071. BABYLON.serialize("backFaceCulling")
  38072. ], Material.prototype, "_backFaceCulling", void 0);
  38073. __decorate([
  38074. BABYLON.serialize()
  38075. ], Material.prototype, "sideOrientation", void 0);
  38076. __decorate([
  38077. BABYLON.serialize("alphaMode")
  38078. ], Material.prototype, "_alphaMode", void 0);
  38079. __decorate([
  38080. BABYLON.serialize()
  38081. ], Material.prototype, "_needDepthPrePass", void 0);
  38082. __decorate([
  38083. BABYLON.serialize()
  38084. ], Material.prototype, "disableDepthWrite", void 0);
  38085. __decorate([
  38086. BABYLON.serialize()
  38087. ], Material.prototype, "forceDepthWrite", void 0);
  38088. __decorate([
  38089. BABYLON.serialize()
  38090. ], Material.prototype, "separateCullingPass", void 0);
  38091. __decorate([
  38092. BABYLON.serialize("fogEnabled")
  38093. ], Material.prototype, "_fogEnabled", void 0);
  38094. __decorate([
  38095. BABYLON.serialize()
  38096. ], Material.prototype, "pointSize", void 0);
  38097. __decorate([
  38098. BABYLON.serialize()
  38099. ], Material.prototype, "zOffset", void 0);
  38100. __decorate([
  38101. BABYLON.serialize()
  38102. ], Material.prototype, "wireframe", null);
  38103. __decorate([
  38104. BABYLON.serialize()
  38105. ], Material.prototype, "pointsCloud", null);
  38106. __decorate([
  38107. BABYLON.serialize()
  38108. ], Material.prototype, "fillMode", null);
  38109. return Material;
  38110. }());
  38111. BABYLON.Material = Material;
  38112. })(BABYLON || (BABYLON = {}));
  38113. //# sourceMappingURL=babylon.material.js.map
  38114. var BABYLON;
  38115. (function (BABYLON) {
  38116. /**
  38117. * Uniform buffer objects.
  38118. *
  38119. * Handles blocks of uniform on the GPU.
  38120. *
  38121. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  38122. *
  38123. * For more information, please refer to :
  38124. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  38125. */
  38126. var UniformBuffer = /** @class */ (function () {
  38127. /**
  38128. * Instantiates a new Uniform buffer objects.
  38129. *
  38130. * Handles blocks of uniform on the GPU.
  38131. *
  38132. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  38133. *
  38134. * For more information, please refer to :
  38135. * @see https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  38136. * @param engine Define the engine the buffer is associated with
  38137. * @param data Define the data contained in the buffer
  38138. * @param dynamic Define if the buffer is updatable
  38139. */
  38140. function UniformBuffer(engine, data, dynamic) {
  38141. this._engine = engine;
  38142. this._noUBO = !engine.supportsUniformBuffers;
  38143. this._dynamic = dynamic;
  38144. this._data = data || [];
  38145. this._uniformLocations = {};
  38146. this._uniformSizes = {};
  38147. this._uniformLocationPointer = 0;
  38148. this._needSync = false;
  38149. if (this._noUBO) {
  38150. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  38151. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  38152. this.updateFloat = this._updateFloatForEffect;
  38153. this.updateFloat2 = this._updateFloat2ForEffect;
  38154. this.updateFloat3 = this._updateFloat3ForEffect;
  38155. this.updateFloat4 = this._updateFloat4ForEffect;
  38156. this.updateMatrix = this._updateMatrixForEffect;
  38157. this.updateVector3 = this._updateVector3ForEffect;
  38158. this.updateVector4 = this._updateVector4ForEffect;
  38159. this.updateColor3 = this._updateColor3ForEffect;
  38160. this.updateColor4 = this._updateColor4ForEffect;
  38161. }
  38162. else {
  38163. this._engine._uniformBuffers.push(this);
  38164. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  38165. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  38166. this.updateFloat = this._updateFloatForUniform;
  38167. this.updateFloat2 = this._updateFloat2ForUniform;
  38168. this.updateFloat3 = this._updateFloat3ForUniform;
  38169. this.updateFloat4 = this._updateFloat4ForUniform;
  38170. this.updateMatrix = this._updateMatrixForUniform;
  38171. this.updateVector3 = this._updateVector3ForUniform;
  38172. this.updateVector4 = this._updateVector4ForUniform;
  38173. this.updateColor3 = this._updateColor3ForUniform;
  38174. this.updateColor4 = this._updateColor4ForUniform;
  38175. }
  38176. }
  38177. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  38178. /**
  38179. * Indicates if the buffer is using the WebGL2 UBO implementation,
  38180. * or just falling back on setUniformXXX calls.
  38181. */
  38182. get: function () {
  38183. return !this._noUBO;
  38184. },
  38185. enumerable: true,
  38186. configurable: true
  38187. });
  38188. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  38189. /**
  38190. * Indicates if the WebGL underlying uniform buffer is in sync
  38191. * with the javascript cache data.
  38192. */
  38193. get: function () {
  38194. return !this._needSync;
  38195. },
  38196. enumerable: true,
  38197. configurable: true
  38198. });
  38199. /**
  38200. * Indicates if the WebGL underlying uniform buffer is dynamic.
  38201. * Also, a dynamic UniformBuffer will disable cache verification and always
  38202. * update the underlying WebGL uniform buffer to the GPU.
  38203. * @returns if Dynamic, otherwise false
  38204. */
  38205. UniformBuffer.prototype.isDynamic = function () {
  38206. return this._dynamic !== undefined;
  38207. };
  38208. /**
  38209. * The data cache on JS side.
  38210. * @returns the underlying data as a float array
  38211. */
  38212. UniformBuffer.prototype.getData = function () {
  38213. return this._bufferData;
  38214. };
  38215. /**
  38216. * The underlying WebGL Uniform buffer.
  38217. * @returns the webgl buffer
  38218. */
  38219. UniformBuffer.prototype.getBuffer = function () {
  38220. return this._buffer;
  38221. };
  38222. /**
  38223. * std140 layout specifies how to align data within an UBO structure.
  38224. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  38225. * for specs.
  38226. */
  38227. UniformBuffer.prototype._fillAlignment = function (size) {
  38228. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  38229. // and 4x4 matrices
  38230. // TODO : change if other types are used
  38231. var alignment;
  38232. if (size <= 2) {
  38233. alignment = size;
  38234. }
  38235. else {
  38236. alignment = 4;
  38237. }
  38238. if ((this._uniformLocationPointer % alignment) !== 0) {
  38239. var oldPointer = this._uniformLocationPointer;
  38240. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  38241. var diff = this._uniformLocationPointer - oldPointer;
  38242. for (var i = 0; i < diff; i++) {
  38243. this._data.push(0);
  38244. }
  38245. }
  38246. };
  38247. /**
  38248. * Adds an uniform in the buffer.
  38249. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  38250. * for the layout to be correct !
  38251. * @param name Name of the uniform, as used in the uniform block in the shader.
  38252. * @param size Data size, or data directly.
  38253. */
  38254. UniformBuffer.prototype.addUniform = function (name, size) {
  38255. if (this._noUBO) {
  38256. return;
  38257. }
  38258. if (this._uniformLocations[name] !== undefined) {
  38259. // Already existing uniform
  38260. return;
  38261. }
  38262. // This function must be called in the order of the shader layout !
  38263. // size can be the size of the uniform, or data directly
  38264. var data;
  38265. if (size instanceof Array) {
  38266. data = size;
  38267. size = data.length;
  38268. }
  38269. else {
  38270. size = size;
  38271. data = [];
  38272. // Fill with zeros
  38273. for (var i = 0; i < size; i++) {
  38274. data.push(0);
  38275. }
  38276. }
  38277. this._fillAlignment(size);
  38278. this._uniformSizes[name] = size;
  38279. this._uniformLocations[name] = this._uniformLocationPointer;
  38280. this._uniformLocationPointer += size;
  38281. for (var i = 0; i < size; i++) {
  38282. this._data.push(data[i]);
  38283. }
  38284. this._needSync = true;
  38285. };
  38286. /**
  38287. * Adds a Matrix 4x4 to the uniform buffer.
  38288. * @param name Name of the uniform, as used in the uniform block in the shader.
  38289. * @param mat A 4x4 matrix.
  38290. */
  38291. UniformBuffer.prototype.addMatrix = function (name, mat) {
  38292. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  38293. };
  38294. /**
  38295. * Adds a vec2 to the uniform buffer.
  38296. * @param name Name of the uniform, as used in the uniform block in the shader.
  38297. * @param x Define the x component value of the vec2
  38298. * @param y Define the y component value of the vec2
  38299. */
  38300. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  38301. var temp = [x, y];
  38302. this.addUniform(name, temp);
  38303. };
  38304. /**
  38305. * Adds a vec3 to the uniform buffer.
  38306. * @param name Name of the uniform, as used in the uniform block in the shader.
  38307. * @param x Define the x component value of the vec3
  38308. * @param y Define the y component value of the vec3
  38309. * @param z Define the z component value of the vec3
  38310. */
  38311. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  38312. var temp = [x, y, z];
  38313. this.addUniform(name, temp);
  38314. };
  38315. /**
  38316. * Adds a vec3 to the uniform buffer.
  38317. * @param name Name of the uniform, as used in the uniform block in the shader.
  38318. * @param color Define the vec3 from a Color
  38319. */
  38320. UniformBuffer.prototype.addColor3 = function (name, color) {
  38321. var temp = new Array();
  38322. color.toArray(temp);
  38323. this.addUniform(name, temp);
  38324. };
  38325. /**
  38326. * Adds a vec4 to the uniform buffer.
  38327. * @param name Name of the uniform, as used in the uniform block in the shader.
  38328. * @param color Define the rgb components from a Color
  38329. * @param alpha Define the a component of the vec4
  38330. */
  38331. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  38332. var temp = new Array();
  38333. color.toArray(temp);
  38334. temp.push(alpha);
  38335. this.addUniform(name, temp);
  38336. };
  38337. /**
  38338. * Adds a vec3 to the uniform buffer.
  38339. * @param name Name of the uniform, as used in the uniform block in the shader.
  38340. * @param vector Define the vec3 components from a Vector
  38341. */
  38342. UniformBuffer.prototype.addVector3 = function (name, vector) {
  38343. var temp = new Array();
  38344. vector.toArray(temp);
  38345. this.addUniform(name, temp);
  38346. };
  38347. /**
  38348. * Adds a Matrix 3x3 to the uniform buffer.
  38349. * @param name Name of the uniform, as used in the uniform block in the shader.
  38350. */
  38351. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  38352. this.addUniform(name, 12);
  38353. };
  38354. /**
  38355. * Adds a Matrix 2x2 to the uniform buffer.
  38356. * @param name Name of the uniform, as used in the uniform block in the shader.
  38357. */
  38358. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  38359. this.addUniform(name, 8);
  38360. };
  38361. /**
  38362. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  38363. */
  38364. UniformBuffer.prototype.create = function () {
  38365. if (this._noUBO) {
  38366. return;
  38367. }
  38368. if (this._buffer) {
  38369. return; // nothing to do
  38370. }
  38371. // See spec, alignment must be filled as a vec4
  38372. this._fillAlignment(4);
  38373. this._bufferData = new Float32Array(this._data);
  38374. this._rebuild();
  38375. this._needSync = true;
  38376. };
  38377. /** @hidden */
  38378. UniformBuffer.prototype._rebuild = function () {
  38379. if (this._noUBO) {
  38380. return;
  38381. }
  38382. if (this._dynamic) {
  38383. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  38384. }
  38385. else {
  38386. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  38387. }
  38388. };
  38389. /**
  38390. * Updates the WebGL Uniform Buffer on the GPU.
  38391. * If the `dynamic` flag is set to true, no cache comparison is done.
  38392. * Otherwise, the buffer will be updated only if the cache differs.
  38393. */
  38394. UniformBuffer.prototype.update = function () {
  38395. if (!this._buffer) {
  38396. this.create();
  38397. return;
  38398. }
  38399. if (!this._dynamic && !this._needSync) {
  38400. return;
  38401. }
  38402. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  38403. this._needSync = false;
  38404. };
  38405. /**
  38406. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  38407. * @param uniformName Define the name of the uniform, as used in the uniform block in the shader.
  38408. * @param data Define the flattened data
  38409. * @param size Define the size of the data.
  38410. */
  38411. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  38412. var location = this._uniformLocations[uniformName];
  38413. if (location === undefined) {
  38414. if (this._buffer) {
  38415. // Cannot add an uniform if the buffer is already created
  38416. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  38417. return;
  38418. }
  38419. this.addUniform(uniformName, size);
  38420. location = this._uniformLocations[uniformName];
  38421. }
  38422. if (!this._buffer) {
  38423. this.create();
  38424. }
  38425. if (!this._dynamic) {
  38426. // Cache for static uniform buffers
  38427. var changed = false;
  38428. for (var i = 0; i < size; i++) {
  38429. if (this._bufferData[location + i] !== data[i]) {
  38430. changed = true;
  38431. this._bufferData[location + i] = data[i];
  38432. }
  38433. }
  38434. this._needSync = this._needSync || changed;
  38435. }
  38436. else {
  38437. // No cache for dynamic
  38438. for (var i = 0; i < size; i++) {
  38439. this._bufferData[location + i] = data[i];
  38440. }
  38441. }
  38442. };
  38443. // Update methods
  38444. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  38445. // To match std140, matrix must be realigned
  38446. for (var i = 0; i < 3; i++) {
  38447. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  38448. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  38449. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  38450. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  38451. }
  38452. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  38453. };
  38454. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  38455. this._currentEffect.setMatrix3x3(name, matrix);
  38456. };
  38457. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  38458. this._currentEffect.setMatrix2x2(name, matrix);
  38459. };
  38460. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  38461. // To match std140, matrix must be realigned
  38462. for (var i = 0; i < 2; i++) {
  38463. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  38464. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  38465. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  38466. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  38467. }
  38468. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  38469. };
  38470. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  38471. this._currentEffect.setFloat(name, x);
  38472. };
  38473. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  38474. UniformBuffer._tempBuffer[0] = x;
  38475. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  38476. };
  38477. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  38478. if (suffix === void 0) { suffix = ""; }
  38479. this._currentEffect.setFloat2(name + suffix, x, y);
  38480. };
  38481. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  38482. if (suffix === void 0) { suffix = ""; }
  38483. UniformBuffer._tempBuffer[0] = x;
  38484. UniformBuffer._tempBuffer[1] = y;
  38485. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  38486. };
  38487. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  38488. if (suffix === void 0) { suffix = ""; }
  38489. this._currentEffect.setFloat3(name + suffix, x, y, z);
  38490. };
  38491. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  38492. if (suffix === void 0) { suffix = ""; }
  38493. UniformBuffer._tempBuffer[0] = x;
  38494. UniformBuffer._tempBuffer[1] = y;
  38495. UniformBuffer._tempBuffer[2] = z;
  38496. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  38497. };
  38498. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  38499. if (suffix === void 0) { suffix = ""; }
  38500. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  38501. };
  38502. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  38503. if (suffix === void 0) { suffix = ""; }
  38504. UniformBuffer._tempBuffer[0] = x;
  38505. UniformBuffer._tempBuffer[1] = y;
  38506. UniformBuffer._tempBuffer[2] = z;
  38507. UniformBuffer._tempBuffer[3] = w;
  38508. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  38509. };
  38510. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  38511. this._currentEffect.setMatrix(name, mat);
  38512. };
  38513. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  38514. this.updateUniform(name, mat.toArray(), 16);
  38515. };
  38516. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  38517. this._currentEffect.setVector3(name, vector);
  38518. };
  38519. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  38520. vector.toArray(UniformBuffer._tempBuffer);
  38521. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  38522. };
  38523. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  38524. this._currentEffect.setVector4(name, vector);
  38525. };
  38526. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  38527. vector.toArray(UniformBuffer._tempBuffer);
  38528. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  38529. };
  38530. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  38531. if (suffix === void 0) { suffix = ""; }
  38532. this._currentEffect.setColor3(name + suffix, color);
  38533. };
  38534. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  38535. if (suffix === void 0) { suffix = ""; }
  38536. color.toArray(UniformBuffer._tempBuffer);
  38537. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  38538. };
  38539. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  38540. if (suffix === void 0) { suffix = ""; }
  38541. this._currentEffect.setColor4(name + suffix, color, alpha);
  38542. };
  38543. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  38544. if (suffix === void 0) { suffix = ""; }
  38545. color.toArray(UniformBuffer._tempBuffer);
  38546. UniformBuffer._tempBuffer[3] = alpha;
  38547. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  38548. };
  38549. /**
  38550. * Sets a sampler uniform on the effect.
  38551. * @param name Define the name of the sampler.
  38552. * @param texture Define the texture to set in the sampler
  38553. */
  38554. UniformBuffer.prototype.setTexture = function (name, texture) {
  38555. this._currentEffect.setTexture(name, texture);
  38556. };
  38557. /**
  38558. * Directly updates the value of the uniform in the cache AND on the GPU.
  38559. * @param uniformName Define the name of the uniform, as used in the uniform block in the shader.
  38560. * @param data Define the flattened data
  38561. */
  38562. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  38563. this.updateUniform(uniformName, data, data.length);
  38564. this.update();
  38565. };
  38566. /**
  38567. * Binds this uniform buffer to an effect.
  38568. * @param effect Define the effect to bind the buffer to
  38569. * @param name Name of the uniform block in the shader.
  38570. */
  38571. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  38572. this._currentEffect = effect;
  38573. if (this._noUBO || !this._buffer) {
  38574. return;
  38575. }
  38576. effect.bindUniformBuffer(this._buffer, name);
  38577. };
  38578. /**
  38579. * Disposes the uniform buffer.
  38580. */
  38581. UniformBuffer.prototype.dispose = function () {
  38582. if (this._noUBO) {
  38583. return;
  38584. }
  38585. var uniformBuffers = this._engine._uniformBuffers;
  38586. var index = uniformBuffers.indexOf(this);
  38587. if (index !== -1) {
  38588. uniformBuffers[index] = uniformBuffers[uniformBuffers.length - 1];
  38589. uniformBuffers.pop();
  38590. }
  38591. if (!this._buffer) {
  38592. return;
  38593. }
  38594. if (this._engine._releaseBuffer(this._buffer)) {
  38595. this._buffer = null;
  38596. }
  38597. };
  38598. // Pool for avoiding memory leaks
  38599. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  38600. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  38601. return UniformBuffer;
  38602. }());
  38603. BABYLON.UniformBuffer = UniformBuffer;
  38604. })(BABYLON || (BABYLON = {}));
  38605. //# sourceMappingURL=babylon.uniformBuffer.js.map
  38606. var BABYLON;
  38607. (function (BABYLON) {
  38608. /**
  38609. * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance
  38610. */
  38611. var VertexData = /** @class */ (function () {
  38612. function VertexData() {
  38613. }
  38614. /**
  38615. * Uses the passed data array to set the set the values for the specified kind of data
  38616. * @param data a linear array of floating numbers
  38617. * @param kind the type of data that is being set, eg positions, colors etc
  38618. */
  38619. VertexData.prototype.set = function (data, kind) {
  38620. switch (kind) {
  38621. case BABYLON.VertexBuffer.PositionKind:
  38622. this.positions = data;
  38623. break;
  38624. case BABYLON.VertexBuffer.NormalKind:
  38625. this.normals = data;
  38626. break;
  38627. case BABYLON.VertexBuffer.TangentKind:
  38628. this.tangents = data;
  38629. break;
  38630. case BABYLON.VertexBuffer.UVKind:
  38631. this.uvs = data;
  38632. break;
  38633. case BABYLON.VertexBuffer.UV2Kind:
  38634. this.uvs2 = data;
  38635. break;
  38636. case BABYLON.VertexBuffer.UV3Kind:
  38637. this.uvs3 = data;
  38638. break;
  38639. case BABYLON.VertexBuffer.UV4Kind:
  38640. this.uvs4 = data;
  38641. break;
  38642. case BABYLON.VertexBuffer.UV5Kind:
  38643. this.uvs5 = data;
  38644. break;
  38645. case BABYLON.VertexBuffer.UV6Kind:
  38646. this.uvs6 = data;
  38647. break;
  38648. case BABYLON.VertexBuffer.ColorKind:
  38649. this.colors = data;
  38650. break;
  38651. case BABYLON.VertexBuffer.MatricesIndicesKind:
  38652. this.matricesIndices = data;
  38653. break;
  38654. case BABYLON.VertexBuffer.MatricesWeightsKind:
  38655. this.matricesWeights = data;
  38656. break;
  38657. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  38658. this.matricesIndicesExtra = data;
  38659. break;
  38660. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  38661. this.matricesWeightsExtra = data;
  38662. break;
  38663. }
  38664. };
  38665. /**
  38666. * Associates the vertexData to the passed Mesh.
  38667. * Sets it as updatable or not (default `false`)
  38668. * @param mesh the mesh the vertexData is applied to
  38669. * @param updatable when used and having the value true allows new data to update the vertexData
  38670. * @returns the VertexData
  38671. */
  38672. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  38673. this._applyTo(mesh, updatable);
  38674. return this;
  38675. };
  38676. /**
  38677. * Associates the vertexData to the passed Geometry.
  38678. * Sets it as updatable or not (default `false`)
  38679. * @param geometry the geometry the vertexData is applied to
  38680. * @param updatable when used and having the value true allows new data to update the vertexData
  38681. * @returns VertexData
  38682. */
  38683. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  38684. this._applyTo(geometry, updatable);
  38685. return this;
  38686. };
  38687. /**
  38688. * Updates the associated mesh
  38689. * @param mesh the mesh to be updated
  38690. * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false
  38691. * @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
  38692. * @returns VertexData
  38693. */
  38694. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  38695. this._update(mesh);
  38696. return this;
  38697. };
  38698. /**
  38699. * Updates the associated geometry
  38700. * @param geometry the geometry to be updated
  38701. * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false
  38702. * @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
  38703. * @returns VertexData.
  38704. */
  38705. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  38706. this._update(geometry);
  38707. return this;
  38708. };
  38709. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  38710. if (updatable === void 0) { updatable = false; }
  38711. if (this.positions) {
  38712. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  38713. }
  38714. if (this.normals) {
  38715. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  38716. }
  38717. if (this.tangents) {
  38718. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  38719. }
  38720. if (this.uvs) {
  38721. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  38722. }
  38723. if (this.uvs2) {
  38724. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  38725. }
  38726. if (this.uvs3) {
  38727. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  38728. }
  38729. if (this.uvs4) {
  38730. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  38731. }
  38732. if (this.uvs5) {
  38733. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  38734. }
  38735. if (this.uvs6) {
  38736. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  38737. }
  38738. if (this.colors) {
  38739. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  38740. }
  38741. if (this.matricesIndices) {
  38742. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  38743. }
  38744. if (this.matricesWeights) {
  38745. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  38746. }
  38747. if (this.matricesIndicesExtra) {
  38748. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  38749. }
  38750. if (this.matricesWeightsExtra) {
  38751. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  38752. }
  38753. if (this.indices) {
  38754. meshOrGeometry.setIndices(this.indices, null, updatable);
  38755. }
  38756. else {
  38757. meshOrGeometry.setIndices([], null);
  38758. }
  38759. return this;
  38760. };
  38761. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  38762. if (this.positions) {
  38763. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  38764. }
  38765. if (this.normals) {
  38766. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  38767. }
  38768. if (this.tangents) {
  38769. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  38770. }
  38771. if (this.uvs) {
  38772. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  38773. }
  38774. if (this.uvs2) {
  38775. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  38776. }
  38777. if (this.uvs3) {
  38778. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  38779. }
  38780. if (this.uvs4) {
  38781. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  38782. }
  38783. if (this.uvs5) {
  38784. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  38785. }
  38786. if (this.uvs6) {
  38787. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  38788. }
  38789. if (this.colors) {
  38790. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  38791. }
  38792. if (this.matricesIndices) {
  38793. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  38794. }
  38795. if (this.matricesWeights) {
  38796. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  38797. }
  38798. if (this.matricesIndicesExtra) {
  38799. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  38800. }
  38801. if (this.matricesWeightsExtra) {
  38802. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  38803. }
  38804. if (this.indices) {
  38805. meshOrGeometry.setIndices(this.indices, null);
  38806. }
  38807. return this;
  38808. };
  38809. /**
  38810. * Transforms each position and each normal of the vertexData according to the passed Matrix
  38811. * @param matrix the transforming matrix
  38812. * @returns the VertexData
  38813. */
  38814. VertexData.prototype.transform = function (matrix) {
  38815. var flip = matrix.m[0] * matrix.m[5] * matrix.m[10] < 0;
  38816. var transformed = BABYLON.Vector3.Zero();
  38817. var index;
  38818. if (this.positions) {
  38819. var position = BABYLON.Vector3.Zero();
  38820. for (index = 0; index < this.positions.length; index += 3) {
  38821. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  38822. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  38823. this.positions[index] = transformed.x;
  38824. this.positions[index + 1] = transformed.y;
  38825. this.positions[index + 2] = transformed.z;
  38826. }
  38827. }
  38828. if (this.normals) {
  38829. var normal = BABYLON.Vector3.Zero();
  38830. for (index = 0; index < this.normals.length; index += 3) {
  38831. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  38832. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  38833. this.normals[index] = transformed.x;
  38834. this.normals[index + 1] = transformed.y;
  38835. this.normals[index + 2] = transformed.z;
  38836. }
  38837. }
  38838. if (this.tangents) {
  38839. var tangent = BABYLON.Vector4.Zero();
  38840. var tangentTransformed = BABYLON.Vector4.Zero();
  38841. for (index = 0; index < this.tangents.length; index += 4) {
  38842. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  38843. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  38844. this.tangents[index] = tangentTransformed.x;
  38845. this.tangents[index + 1] = tangentTransformed.y;
  38846. this.tangents[index + 2] = tangentTransformed.z;
  38847. this.tangents[index + 3] = tangentTransformed.w;
  38848. }
  38849. }
  38850. if (flip && this.indices) {
  38851. for (index = 0; index < this.indices.length; index += 3) {
  38852. var tmp = this.indices[index + 1];
  38853. this.indices[index + 1] = this.indices[index + 2];
  38854. this.indices[index + 2] = tmp;
  38855. }
  38856. }
  38857. return this;
  38858. };
  38859. /**
  38860. * Merges the passed VertexData into the current one
  38861. * @param other the VertexData to be merged into the current one
  38862. * @param use32BitsIndices defines a boolean indicating if indices must be store in a 32 bits array
  38863. * @returns the modified VertexData
  38864. */
  38865. VertexData.prototype.merge = function (other, use32BitsIndices) {
  38866. if (use32BitsIndices === void 0) { use32BitsIndices = false; }
  38867. this._validate();
  38868. other._validate();
  38869. if (!this.normals !== !other.normals ||
  38870. !this.tangents !== !other.tangents ||
  38871. !this.uvs !== !other.uvs ||
  38872. !this.uvs2 !== !other.uvs2 ||
  38873. !this.uvs3 !== !other.uvs3 ||
  38874. !this.uvs4 !== !other.uvs4 ||
  38875. !this.uvs5 !== !other.uvs5 ||
  38876. !this.uvs6 !== !other.uvs6 ||
  38877. !this.colors !== !other.colors ||
  38878. !this.matricesIndices !== !other.matricesIndices ||
  38879. !this.matricesWeights !== !other.matricesWeights ||
  38880. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  38881. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  38882. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  38883. }
  38884. if (other.indices) {
  38885. if (!this.indices) {
  38886. this.indices = [];
  38887. }
  38888. var offset = this.positions ? this.positions.length / 3 : 0;
  38889. var isSrcTypedArray = this.indices.BYTES_PER_ELEMENT !== undefined;
  38890. if (isSrcTypedArray) {
  38891. var len = this.indices.length + other.indices.length;
  38892. var temp = use32BitsIndices || this.indices instanceof Uint32Array ? new Uint32Array(len) : new Uint16Array(len);
  38893. temp.set(this.indices);
  38894. var decal = this.indices.length;
  38895. for (var index = 0; index < other.indices.length; index++) {
  38896. temp[decal + index] = other.indices[index] + offset;
  38897. }
  38898. this.indices = temp;
  38899. }
  38900. else {
  38901. for (var index = 0; index < other.indices.length; index++) {
  38902. this.indices.push(other.indices[index] + offset);
  38903. }
  38904. }
  38905. }
  38906. this.positions = this._mergeElement(this.positions, other.positions);
  38907. this.normals = this._mergeElement(this.normals, other.normals);
  38908. this.tangents = this._mergeElement(this.tangents, other.tangents);
  38909. this.uvs = this._mergeElement(this.uvs, other.uvs);
  38910. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  38911. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  38912. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  38913. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  38914. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  38915. this.colors = this._mergeElement(this.colors, other.colors);
  38916. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  38917. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  38918. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  38919. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  38920. return this;
  38921. };
  38922. VertexData.prototype._mergeElement = function (source, other) {
  38923. if (!source) {
  38924. return other;
  38925. }
  38926. if (!other) {
  38927. return source;
  38928. }
  38929. var len = other.length + source.length;
  38930. var isSrcTypedArray = source instanceof Float32Array;
  38931. var isOthTypedArray = other instanceof Float32Array;
  38932. // use non-loop method when the source is Float32Array
  38933. if (isSrcTypedArray) {
  38934. var ret32 = new Float32Array(len);
  38935. ret32.set(source);
  38936. ret32.set(other, source.length);
  38937. return ret32;
  38938. // source is number[], when other is also use concat
  38939. }
  38940. else if (!isOthTypedArray) {
  38941. return source.concat(other);
  38942. // source is a number[], but other is a Float32Array, loop required
  38943. }
  38944. else {
  38945. var ret = source.slice(0); // copy source to a separate array
  38946. for (var i = 0, len = other.length; i < len; i++) {
  38947. ret.push(other[i]);
  38948. }
  38949. return ret;
  38950. }
  38951. };
  38952. VertexData.prototype._validate = function () {
  38953. if (!this.positions) {
  38954. throw new Error("Positions are required");
  38955. }
  38956. var getElementCount = function (kind, values) {
  38957. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  38958. if ((values.length % stride) !== 0) {
  38959. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  38960. }
  38961. return values.length / stride;
  38962. };
  38963. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  38964. var validateElementCount = function (kind, values) {
  38965. var elementCount = getElementCount(kind, values);
  38966. if (elementCount !== positionsElementCount) {
  38967. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  38968. }
  38969. };
  38970. if (this.normals) {
  38971. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  38972. }
  38973. if (this.tangents) {
  38974. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  38975. }
  38976. if (this.uvs) {
  38977. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  38978. }
  38979. if (this.uvs2) {
  38980. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  38981. }
  38982. if (this.uvs3) {
  38983. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  38984. }
  38985. if (this.uvs4) {
  38986. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  38987. }
  38988. if (this.uvs5) {
  38989. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  38990. }
  38991. if (this.uvs6) {
  38992. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  38993. }
  38994. if (this.colors) {
  38995. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  38996. }
  38997. if (this.matricesIndices) {
  38998. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  38999. }
  39000. if (this.matricesWeights) {
  39001. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  39002. }
  39003. if (this.matricesIndicesExtra) {
  39004. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  39005. }
  39006. if (this.matricesWeightsExtra) {
  39007. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  39008. }
  39009. };
  39010. /**
  39011. * Serializes the VertexData
  39012. * @returns a serialized object
  39013. */
  39014. VertexData.prototype.serialize = function () {
  39015. var serializationObject = this.serialize();
  39016. if (this.positions) {
  39017. serializationObject.positions = this.positions;
  39018. }
  39019. if (this.normals) {
  39020. serializationObject.normals = this.normals;
  39021. }
  39022. if (this.tangents) {
  39023. serializationObject.tangents = this.tangents;
  39024. }
  39025. if (this.uvs) {
  39026. serializationObject.uvs = this.uvs;
  39027. }
  39028. if (this.uvs2) {
  39029. serializationObject.uvs2 = this.uvs2;
  39030. }
  39031. if (this.uvs3) {
  39032. serializationObject.uvs3 = this.uvs3;
  39033. }
  39034. if (this.uvs4) {
  39035. serializationObject.uvs4 = this.uvs4;
  39036. }
  39037. if (this.uvs5) {
  39038. serializationObject.uvs5 = this.uvs5;
  39039. }
  39040. if (this.uvs6) {
  39041. serializationObject.uvs6 = this.uvs6;
  39042. }
  39043. if (this.colors) {
  39044. serializationObject.colors = this.colors;
  39045. }
  39046. if (this.matricesIndices) {
  39047. serializationObject.matricesIndices = this.matricesIndices;
  39048. serializationObject.matricesIndices._isExpanded = true;
  39049. }
  39050. if (this.matricesWeights) {
  39051. serializationObject.matricesWeights = this.matricesWeights;
  39052. }
  39053. if (this.matricesIndicesExtra) {
  39054. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  39055. serializationObject.matricesIndicesExtra._isExpanded = true;
  39056. }
  39057. if (this.matricesWeightsExtra) {
  39058. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  39059. }
  39060. serializationObject.indices = this.indices;
  39061. return serializationObject;
  39062. };
  39063. // Statics
  39064. /**
  39065. * Extracts the vertexData from a mesh
  39066. * @param mesh the mesh from which to extract the VertexData
  39067. * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false
  39068. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  39069. * @returns the object VertexData associated to the passed mesh
  39070. */
  39071. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  39072. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  39073. };
  39074. /**
  39075. * Extracts the vertexData from the geometry
  39076. * @param geometry the geometry from which to extract the VertexData
  39077. * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false
  39078. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  39079. * @returns the object VertexData associated to the passed mesh
  39080. */
  39081. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  39082. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  39083. };
  39084. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  39085. var result = new VertexData();
  39086. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  39087. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  39088. }
  39089. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  39090. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  39091. }
  39092. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  39093. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  39094. }
  39095. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  39096. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  39097. }
  39098. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  39099. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  39100. }
  39101. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  39102. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  39103. }
  39104. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  39105. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  39106. }
  39107. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  39108. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  39109. }
  39110. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  39111. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  39112. }
  39113. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  39114. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  39115. }
  39116. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39117. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  39118. }
  39119. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39120. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  39121. }
  39122. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  39123. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  39124. }
  39125. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  39126. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  39127. }
  39128. result.indices = meshOrGeometry.getIndices(copyWhenShared, forceCopy);
  39129. return result;
  39130. };
  39131. /**
  39132. * Creates the VertexData for a Ribbon
  39133. * @param options an object used to set the following optional parameters for the ribbon, required but can be empty
  39134. * * pathArray array of paths, each of which an array of successive Vector3
  39135. * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false
  39136. * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false
  39137. * * 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
  39138. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39139. * * 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)
  39140. * * 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)
  39141. * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false
  39142. * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional
  39143. * * colors a linear array, of length 4 * number of vertices, of custom color values, optional
  39144. * @returns the VertexData of the ribbon
  39145. */
  39146. VertexData.CreateRibbon = function (options) {
  39147. var pathArray = options.pathArray;
  39148. var closeArray = options.closeArray || false;
  39149. var closePath = options.closePath || false;
  39150. var invertUV = options.invertUV || false;
  39151. var defaultOffset = Math.floor(pathArray[0].length / 2);
  39152. var offset = options.offset || defaultOffset;
  39153. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  39154. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  39155. var customUV = options.uvs;
  39156. var customColors = options.colors;
  39157. var positions = [];
  39158. var indices = [];
  39159. var normals = [];
  39160. var uvs = [];
  39161. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  39162. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  39163. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  39164. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  39165. var minlg; // minimal length among all paths from pathArray
  39166. var lg = []; // array of path lengths : nb of vertex per path
  39167. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  39168. var p; // path iterator
  39169. var i; // point iterator
  39170. var j; // point iterator
  39171. // if single path in pathArray
  39172. if (pathArray.length < 2) {
  39173. var ar1 = [];
  39174. var ar2 = [];
  39175. for (i = 0; i < pathArray[0].length - offset; i++) {
  39176. ar1.push(pathArray[0][i]);
  39177. ar2.push(pathArray[0][i + offset]);
  39178. }
  39179. pathArray = [ar1, ar2];
  39180. }
  39181. // positions and horizontal distances (u)
  39182. var idc = 0;
  39183. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  39184. var path;
  39185. var l;
  39186. minlg = pathArray[0].length;
  39187. var vectlg;
  39188. var dist;
  39189. for (p = 0; p < pathArray.length; p++) {
  39190. uTotalDistance[p] = 0;
  39191. us[p] = [0];
  39192. path = pathArray[p];
  39193. l = path.length;
  39194. minlg = (minlg < l) ? minlg : l;
  39195. j = 0;
  39196. while (j < l) {
  39197. positions.push(path[j].x, path[j].y, path[j].z);
  39198. if (j > 0) {
  39199. vectlg = path[j].subtract(path[j - 1]).length();
  39200. dist = vectlg + uTotalDistance[p];
  39201. us[p].push(dist);
  39202. uTotalDistance[p] = dist;
  39203. }
  39204. j++;
  39205. }
  39206. if (closePath) { // an extra hidden vertex is added in the "positions" array
  39207. j--;
  39208. positions.push(path[0].x, path[0].y, path[0].z);
  39209. vectlg = path[j].subtract(path[0]).length();
  39210. dist = vectlg + uTotalDistance[p];
  39211. us[p].push(dist);
  39212. uTotalDistance[p] = dist;
  39213. }
  39214. lg[p] = l + closePathCorr;
  39215. idx[p] = idc;
  39216. idc += (l + closePathCorr);
  39217. }
  39218. // vertical distances (v)
  39219. var path1;
  39220. var path2;
  39221. var vertex1 = null;
  39222. var vertex2 = null;
  39223. for (i = 0; i < minlg + closePathCorr; i++) {
  39224. vTotalDistance[i] = 0;
  39225. vs[i] = [0];
  39226. for (p = 0; p < pathArray.length - 1; p++) {
  39227. path1 = pathArray[p];
  39228. path2 = pathArray[p + 1];
  39229. if (i === minlg) { // closePath
  39230. vertex1 = path1[0];
  39231. vertex2 = path2[0];
  39232. }
  39233. else {
  39234. vertex1 = path1[i];
  39235. vertex2 = path2[i];
  39236. }
  39237. vectlg = vertex2.subtract(vertex1).length();
  39238. dist = vectlg + vTotalDistance[i];
  39239. vs[i].push(dist);
  39240. vTotalDistance[i] = dist;
  39241. }
  39242. if (closeArray && vertex2 && vertex1) {
  39243. path1 = pathArray[p];
  39244. path2 = pathArray[0];
  39245. if (i === minlg) { // closePath
  39246. vertex2 = path2[0];
  39247. }
  39248. vectlg = vertex2.subtract(vertex1).length();
  39249. dist = vectlg + vTotalDistance[i];
  39250. vTotalDistance[i] = dist;
  39251. }
  39252. }
  39253. // uvs
  39254. var u;
  39255. var v;
  39256. if (customUV) {
  39257. for (p = 0; p < customUV.length; p++) {
  39258. uvs.push(customUV[p].x, customUV[p].y);
  39259. }
  39260. }
  39261. else {
  39262. for (p = 0; p < pathArray.length; p++) {
  39263. for (i = 0; i < minlg + closePathCorr; i++) {
  39264. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  39265. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  39266. if (invertUV) {
  39267. uvs.push(v, u);
  39268. }
  39269. else {
  39270. uvs.push(u, v);
  39271. }
  39272. }
  39273. }
  39274. }
  39275. // indices
  39276. p = 0; // path index
  39277. var pi = 0; // positions array index
  39278. var l1 = lg[p] - 1; // path1 length
  39279. var l2 = lg[p + 1] - 1; // path2 length
  39280. var min = (l1 < l2) ? l1 : l2; // current path stop index
  39281. var shft = idx[1] - idx[0]; // shift
  39282. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  39283. while (pi <= min && p < path1nb) { // stay under min and don't go over next to last path
  39284. // 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
  39285. indices.push(pi, pi + shft, pi + 1);
  39286. indices.push(pi + shft + 1, pi + 1, pi + shft);
  39287. pi += 1;
  39288. if (pi === min) { // if end of one of two consecutive paths reached, go to next existing path
  39289. p++;
  39290. if (p === lg.length - 1) { // last path of pathArray reached <=> closeArray == true
  39291. shft = idx[0] - idx[p];
  39292. l1 = lg[p] - 1;
  39293. l2 = lg[0] - 1;
  39294. }
  39295. else {
  39296. shft = idx[p + 1] - idx[p];
  39297. l1 = lg[p] - 1;
  39298. l2 = lg[p + 1] - 1;
  39299. }
  39300. pi = idx[p];
  39301. min = (l1 < l2) ? l1 + pi : l2 + pi;
  39302. }
  39303. }
  39304. // normals
  39305. VertexData.ComputeNormals(positions, indices, normals);
  39306. if (closePath) { // update both the first and last vertex normals to their average value
  39307. var indexFirst = 0;
  39308. var indexLast = 0;
  39309. for (p = 0; p < pathArray.length; p++) {
  39310. indexFirst = idx[p] * 3;
  39311. if (p + 1 < pathArray.length) {
  39312. indexLast = (idx[p + 1] - 1) * 3;
  39313. }
  39314. else {
  39315. indexLast = normals.length - 3;
  39316. }
  39317. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  39318. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  39319. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  39320. normals[indexLast] = normals[indexFirst];
  39321. normals[indexLast + 1] = normals[indexFirst + 1];
  39322. normals[indexLast + 2] = normals[indexFirst + 2];
  39323. }
  39324. }
  39325. // sides
  39326. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  39327. // Colors
  39328. var colors = null;
  39329. if (customColors) {
  39330. colors = new Float32Array(customColors.length * 4);
  39331. for (var c = 0; c < customColors.length; c++) {
  39332. colors[c * 4] = customColors[c].r;
  39333. colors[c * 4 + 1] = customColors[c].g;
  39334. colors[c * 4 + 2] = customColors[c].b;
  39335. colors[c * 4 + 3] = customColors[c].a;
  39336. }
  39337. }
  39338. // Result
  39339. var vertexData = new VertexData();
  39340. var positions32 = new Float32Array(positions);
  39341. var normals32 = new Float32Array(normals);
  39342. var uvs32 = new Float32Array(uvs);
  39343. vertexData.indices = indices;
  39344. vertexData.positions = positions32;
  39345. vertexData.normals = normals32;
  39346. vertexData.uvs = uvs32;
  39347. if (colors) {
  39348. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  39349. }
  39350. if (closePath) {
  39351. vertexData._idx = idx;
  39352. }
  39353. return vertexData;
  39354. };
  39355. /**
  39356. * Creates the VertexData for a box
  39357. * @param options an object used to set the following optional parameters for the box, required but can be empty
  39358. * * size sets the width, height and depth of the box to the value of size, optional default 1
  39359. * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size
  39360. * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size
  39361. * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size
  39362. * * faceUV an array of 6 Vector4 elements used to set different images to each box side
  39363. * * faceColors an array of 6 Color3 elements used to set different colors to each box side
  39364. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39365. * * 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)
  39366. * * 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)
  39367. * @returns the VertexData of the box
  39368. */
  39369. VertexData.CreateBox = function (options) {
  39370. var normalsSource = [
  39371. new BABYLON.Vector3(0, 0, 1),
  39372. new BABYLON.Vector3(0, 0, -1),
  39373. new BABYLON.Vector3(1, 0, 0),
  39374. new BABYLON.Vector3(-1, 0, 0),
  39375. new BABYLON.Vector3(0, 1, 0),
  39376. new BABYLON.Vector3(0, -1, 0)
  39377. ];
  39378. var indices = [];
  39379. var positions = [];
  39380. var normals = [];
  39381. var uvs = [];
  39382. var width = options.width || options.size || 1;
  39383. var height = options.height || options.size || 1;
  39384. var depth = options.depth || options.size || 1;
  39385. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  39386. var faceUV = options.faceUV || new Array(6);
  39387. var faceColors = options.faceColors;
  39388. var colors = [];
  39389. // default face colors and UV if undefined
  39390. for (var f = 0; f < 6; f++) {
  39391. if (faceUV[f] === undefined) {
  39392. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  39393. }
  39394. if (faceColors && faceColors[f] === undefined) {
  39395. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  39396. }
  39397. }
  39398. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  39399. // Create each face in turn.
  39400. for (var index = 0; index < normalsSource.length; index++) {
  39401. var normal = normalsSource[index];
  39402. // Get two vectors perpendicular to the face normal and to each other.
  39403. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  39404. var side2 = BABYLON.Vector3.Cross(normal, side1);
  39405. // Six indices (two triangles) per face.
  39406. var verticesLength = positions.length / 3;
  39407. indices.push(verticesLength);
  39408. indices.push(verticesLength + 1);
  39409. indices.push(verticesLength + 2);
  39410. indices.push(verticesLength);
  39411. indices.push(verticesLength + 2);
  39412. indices.push(verticesLength + 3);
  39413. // Four vertices per face.
  39414. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  39415. positions.push(vertex.x, vertex.y, vertex.z);
  39416. normals.push(normal.x, normal.y, normal.z);
  39417. uvs.push(faceUV[index].z, faceUV[index].w);
  39418. if (faceColors) {
  39419. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  39420. }
  39421. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  39422. positions.push(vertex.x, vertex.y, vertex.z);
  39423. normals.push(normal.x, normal.y, normal.z);
  39424. uvs.push(faceUV[index].x, faceUV[index].w);
  39425. if (faceColors) {
  39426. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  39427. }
  39428. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  39429. positions.push(vertex.x, vertex.y, vertex.z);
  39430. normals.push(normal.x, normal.y, normal.z);
  39431. uvs.push(faceUV[index].x, faceUV[index].y);
  39432. if (faceColors) {
  39433. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  39434. }
  39435. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  39436. positions.push(vertex.x, vertex.y, vertex.z);
  39437. normals.push(normal.x, normal.y, normal.z);
  39438. uvs.push(faceUV[index].z, faceUV[index].y);
  39439. if (faceColors) {
  39440. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  39441. }
  39442. }
  39443. // sides
  39444. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  39445. // Result
  39446. var vertexData = new VertexData();
  39447. vertexData.indices = indices;
  39448. vertexData.positions = positions;
  39449. vertexData.normals = normals;
  39450. vertexData.uvs = uvs;
  39451. if (faceColors) {
  39452. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  39453. vertexData.colors = totalColors;
  39454. }
  39455. return vertexData;
  39456. };
  39457. /**
  39458. * Creates the VertexData for an ellipsoid, defaults to a sphere
  39459. * @param options an object used to set the following optional parameters for the box, required but can be empty
  39460. * * segments sets the number of horizontal strips optional, default 32
  39461. * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1
  39462. * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter
  39463. * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter
  39464. * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter
  39465. * * 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
  39466. * * 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
  39467. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39468. * * 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)
  39469. * * 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)
  39470. * @returns the VertexData of the ellipsoid
  39471. */
  39472. VertexData.CreateSphere = function (options) {
  39473. var segments = options.segments || 32;
  39474. var diameterX = options.diameterX || options.diameter || 1;
  39475. var diameterY = options.diameterY || options.diameter || 1;
  39476. var diameterZ = options.diameterZ || options.diameter || 1;
  39477. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  39478. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  39479. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  39480. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  39481. var totalZRotationSteps = 2 + segments;
  39482. var totalYRotationSteps = 2 * totalZRotationSteps;
  39483. var indices = [];
  39484. var positions = [];
  39485. var normals = [];
  39486. var uvs = [];
  39487. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  39488. var normalizedZ = zRotationStep / totalZRotationSteps;
  39489. var angleZ = normalizedZ * Math.PI * slice;
  39490. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  39491. var normalizedY = yRotationStep / totalYRotationSteps;
  39492. var angleY = normalizedY * Math.PI * 2 * arc;
  39493. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  39494. var rotationY = BABYLON.Matrix.RotationY(angleY);
  39495. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  39496. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  39497. var vertex = complete.multiply(radius);
  39498. var normal = complete.divide(radius).normalize();
  39499. positions.push(vertex.x, vertex.y, vertex.z);
  39500. normals.push(normal.x, normal.y, normal.z);
  39501. uvs.push(normalizedY, normalizedZ);
  39502. }
  39503. if (zRotationStep > 0) {
  39504. var verticesCount = positions.length / 3;
  39505. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  39506. indices.push((firstIndex));
  39507. indices.push((firstIndex + 1));
  39508. indices.push(firstIndex + totalYRotationSteps + 1);
  39509. indices.push((firstIndex + totalYRotationSteps + 1));
  39510. indices.push((firstIndex + 1));
  39511. indices.push((firstIndex + totalYRotationSteps + 2));
  39512. }
  39513. }
  39514. }
  39515. // Sides
  39516. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  39517. // Result
  39518. var vertexData = new VertexData();
  39519. vertexData.indices = indices;
  39520. vertexData.positions = positions;
  39521. vertexData.normals = normals;
  39522. vertexData.uvs = uvs;
  39523. return vertexData;
  39524. };
  39525. /**
  39526. * Creates the VertexData for a cylinder, cone or prism
  39527. * @param options an object used to set the following optional parameters for the box, required but can be empty
  39528. * * height sets the height (y direction) of the cylinder, optional, default 2
  39529. * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter
  39530. * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter
  39531. * * diameter sets the diameter of the top and bottom of the cone, optional default 1
  39532. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  39533. * * subdivisions` the number of rings along the cylinder height, optional, default 1
  39534. * * 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
  39535. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  39536. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  39537. * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false
  39538. * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake
  39539. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39540. * * 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)
  39541. * * 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)
  39542. * @returns the VertexData of the cylinder, cone or prism
  39543. */
  39544. VertexData.CreateCylinder = function (options) {
  39545. var height = options.height || 2;
  39546. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  39547. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  39548. var tessellation = options.tessellation || 24;
  39549. var subdivisions = options.subdivisions || 1;
  39550. var hasRings = options.hasRings ? true : false;
  39551. var enclose = options.enclose ? true : false;
  39552. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  39553. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  39554. var faceUV = options.faceUV || new Array(3);
  39555. var faceColors = options.faceColors;
  39556. // default face colors and UV if undefined
  39557. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  39558. var ringNb = (hasRings) ? subdivisions : 1;
  39559. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  39560. var f;
  39561. for (f = 0; f < surfaceNb; f++) {
  39562. if (faceColors && faceColors[f] === undefined) {
  39563. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  39564. }
  39565. }
  39566. for (f = 0; f < surfaceNb; f++) {
  39567. if (faceUV && faceUV[f] === undefined) {
  39568. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  39569. }
  39570. }
  39571. var indices = new Array();
  39572. var positions = new Array();
  39573. var normals = new Array();
  39574. var uvs = new Array();
  39575. var colors = new Array();
  39576. var angle_step = Math.PI * 2 * arc / tessellation;
  39577. var angle;
  39578. var h;
  39579. var radius;
  39580. var tan = (diameterBottom - diameterTop) / 2 / height;
  39581. var ringVertex = BABYLON.Vector3.Zero();
  39582. var ringNormal = BABYLON.Vector3.Zero();
  39583. var ringFirstVertex = BABYLON.Vector3.Zero();
  39584. var ringFirstNormal = BABYLON.Vector3.Zero();
  39585. var quadNormal = BABYLON.Vector3.Zero();
  39586. var Y = BABYLON.Axis.Y;
  39587. // positions, normals, uvs
  39588. var i;
  39589. var j;
  39590. var r;
  39591. var ringIdx = 1;
  39592. var s = 1; // surface index
  39593. var cs = 0;
  39594. var v = 0;
  39595. for (i = 0; i <= subdivisions; i++) {
  39596. h = i / subdivisions;
  39597. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  39598. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  39599. for (r = 0; r < ringIdx; r++) {
  39600. if (hasRings) {
  39601. s += r;
  39602. }
  39603. if (enclose) {
  39604. s += 2 * r;
  39605. }
  39606. for (j = 0; j <= tessellation; j++) {
  39607. angle = j * angle_step;
  39608. // position
  39609. ringVertex.x = Math.cos(-angle) * radius;
  39610. ringVertex.y = -height / 2 + h * height;
  39611. ringVertex.z = Math.sin(-angle) * radius;
  39612. // normal
  39613. if (diameterTop === 0 && i === subdivisions) {
  39614. // if no top cap, reuse former normals
  39615. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  39616. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  39617. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  39618. }
  39619. else {
  39620. ringNormal.x = ringVertex.x;
  39621. ringNormal.z = ringVertex.z;
  39622. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  39623. ringNormal.normalize();
  39624. }
  39625. // keep first ring vertex values for enclose
  39626. if (j === 0) {
  39627. ringFirstVertex.copyFrom(ringVertex);
  39628. ringFirstNormal.copyFrom(ringNormal);
  39629. }
  39630. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  39631. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  39632. if (hasRings) {
  39633. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  39634. }
  39635. else {
  39636. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  39637. }
  39638. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  39639. if (faceColors) {
  39640. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  39641. }
  39642. }
  39643. // if enclose, add four vertices and their dedicated normals
  39644. if (arc !== 1 && enclose) {
  39645. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  39646. positions.push(0, ringVertex.y, 0);
  39647. positions.push(0, ringVertex.y, 0);
  39648. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  39649. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  39650. quadNormal.normalize();
  39651. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  39652. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  39653. quadNormal.normalize();
  39654. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  39655. if (hasRings) {
  39656. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  39657. }
  39658. else {
  39659. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  39660. }
  39661. uvs.push(faceUV[s + 1].x, v);
  39662. uvs.push(faceUV[s + 1].z, v);
  39663. if (hasRings) {
  39664. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  39665. }
  39666. else {
  39667. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  39668. }
  39669. uvs.push(faceUV[s + 2].x, v);
  39670. uvs.push(faceUV[s + 2].z, v);
  39671. if (faceColors) {
  39672. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  39673. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  39674. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  39675. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  39676. }
  39677. }
  39678. if (cs !== s) {
  39679. cs = s;
  39680. }
  39681. }
  39682. }
  39683. // indices
  39684. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  39685. var s;
  39686. i = 0;
  39687. for (s = 0; s < subdivisions; s++) {
  39688. var i0 = 0;
  39689. var i1 = 0;
  39690. var i2 = 0;
  39691. var i3 = 0;
  39692. for (j = 0; j < tessellation; j++) {
  39693. i0 = i * (e + 1) + j;
  39694. i1 = (i + 1) * (e + 1) + j;
  39695. i2 = i * (e + 1) + (j + 1);
  39696. i3 = (i + 1) * (e + 1) + (j + 1);
  39697. indices.push(i0, i1, i2);
  39698. indices.push(i3, i2, i1);
  39699. }
  39700. if (arc !== 1 && enclose) { // if enclose, add two quads
  39701. indices.push(i0 + 2, i1 + 2, i2 + 2);
  39702. indices.push(i3 + 2, i2 + 2, i1 + 2);
  39703. indices.push(i0 + 4, i1 + 4, i2 + 4);
  39704. indices.push(i3 + 4, i2 + 4, i1 + 4);
  39705. }
  39706. i = (hasRings) ? (i + 2) : (i + 1);
  39707. }
  39708. // Caps
  39709. var createCylinderCap = function (isTop) {
  39710. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  39711. if (radius === 0) {
  39712. return;
  39713. }
  39714. // Cap positions, normals & uvs
  39715. var angle;
  39716. var circleVector;
  39717. var i;
  39718. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  39719. var c = null;
  39720. if (faceColors) {
  39721. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  39722. }
  39723. // cap center
  39724. var vbase = positions.length / 3;
  39725. var offset = isTop ? height / 2 : -height / 2;
  39726. var center = new BABYLON.Vector3(0, offset, 0);
  39727. positions.push(center.x, center.y, center.z);
  39728. normals.push(0, isTop ? 1 : -1, 0);
  39729. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  39730. if (c) {
  39731. colors.push(c.r, c.g, c.b, c.a);
  39732. }
  39733. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  39734. for (i = 0; i <= tessellation; i++) {
  39735. angle = Math.PI * 2 * i * arc / tessellation;
  39736. var cos = Math.cos(-angle);
  39737. var sin = Math.sin(-angle);
  39738. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  39739. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  39740. positions.push(circleVector.x, circleVector.y, circleVector.z);
  39741. normals.push(0, isTop ? 1 : -1, 0);
  39742. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  39743. if (c) {
  39744. colors.push(c.r, c.g, c.b, c.a);
  39745. }
  39746. }
  39747. // Cap indices
  39748. for (i = 0; i < tessellation; i++) {
  39749. if (!isTop) {
  39750. indices.push(vbase);
  39751. indices.push(vbase + (i + 1));
  39752. indices.push(vbase + (i + 2));
  39753. }
  39754. else {
  39755. indices.push(vbase);
  39756. indices.push(vbase + (i + 2));
  39757. indices.push(vbase + (i + 1));
  39758. }
  39759. }
  39760. };
  39761. // add caps to geometry
  39762. createCylinderCap(false);
  39763. createCylinderCap(true);
  39764. // Sides
  39765. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  39766. var vertexData = new VertexData();
  39767. vertexData.indices = indices;
  39768. vertexData.positions = positions;
  39769. vertexData.normals = normals;
  39770. vertexData.uvs = uvs;
  39771. if (faceColors) {
  39772. vertexData.colors = colors;
  39773. }
  39774. return vertexData;
  39775. };
  39776. /**
  39777. * Creates the VertexData for a torus
  39778. * @param options an object used to set the following optional parameters for the box, required but can be empty
  39779. * * diameter the diameter of the torus, optional default 1
  39780. * * thickness the diameter of the tube forming the torus, optional default 0.5
  39781. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  39782. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39783. * * 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)
  39784. * * 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)
  39785. * @returns the VertexData of the torus
  39786. */
  39787. VertexData.CreateTorus = function (options) {
  39788. var indices = [];
  39789. var positions = [];
  39790. var normals = [];
  39791. var uvs = [];
  39792. var diameter = options.diameter || 1;
  39793. var thickness = options.thickness || 0.5;
  39794. var tessellation = options.tessellation || 16;
  39795. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  39796. var stride = tessellation + 1;
  39797. for (var i = 0; i <= tessellation; i++) {
  39798. var u = i / tessellation;
  39799. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  39800. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  39801. for (var j = 0; j <= tessellation; j++) {
  39802. var v = 1 - j / tessellation;
  39803. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  39804. var dx = Math.cos(innerAngle);
  39805. var dy = Math.sin(innerAngle);
  39806. // Create a vertex.
  39807. var normal = new BABYLON.Vector3(dx, dy, 0);
  39808. var position = normal.scale(thickness / 2);
  39809. var textureCoordinate = new BABYLON.Vector2(u, v);
  39810. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  39811. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  39812. positions.push(position.x, position.y, position.z);
  39813. normals.push(normal.x, normal.y, normal.z);
  39814. uvs.push(textureCoordinate.x, textureCoordinate.y);
  39815. // And create indices for two triangles.
  39816. var nextI = (i + 1) % stride;
  39817. var nextJ = (j + 1) % stride;
  39818. indices.push(i * stride + j);
  39819. indices.push(i * stride + nextJ);
  39820. indices.push(nextI * stride + j);
  39821. indices.push(i * stride + nextJ);
  39822. indices.push(nextI * stride + nextJ);
  39823. indices.push(nextI * stride + j);
  39824. }
  39825. }
  39826. // Sides
  39827. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  39828. // Result
  39829. var vertexData = new VertexData();
  39830. vertexData.indices = indices;
  39831. vertexData.positions = positions;
  39832. vertexData.normals = normals;
  39833. vertexData.uvs = uvs;
  39834. return vertexData;
  39835. };
  39836. /**
  39837. * Creates the VertexData of the LineSystem
  39838. * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty
  39839. * - lines an array of lines, each line being an array of successive Vector3
  39840. * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point
  39841. * @returns the VertexData of the LineSystem
  39842. */
  39843. VertexData.CreateLineSystem = function (options) {
  39844. var indices = [];
  39845. var positions = [];
  39846. var lines = options.lines;
  39847. var colors = options.colors;
  39848. var vertexColors = [];
  39849. var idx = 0;
  39850. for (var l = 0; l < lines.length; l++) {
  39851. var points = lines[l];
  39852. for (var index = 0; index < points.length; index++) {
  39853. positions.push(points[index].x, points[index].y, points[index].z);
  39854. if (colors) {
  39855. var color = colors[l];
  39856. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  39857. }
  39858. if (index > 0) {
  39859. indices.push(idx - 1);
  39860. indices.push(idx);
  39861. }
  39862. idx++;
  39863. }
  39864. }
  39865. var vertexData = new VertexData();
  39866. vertexData.indices = indices;
  39867. vertexData.positions = positions;
  39868. if (colors) {
  39869. vertexData.colors = vertexColors;
  39870. }
  39871. return vertexData;
  39872. };
  39873. /**
  39874. * Create the VertexData for a DashedLines
  39875. * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty
  39876. * - points an array successive Vector3
  39877. * - dashSize the size of the dashes relative to the dash number, optional, default 3
  39878. * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1
  39879. * - dashNb the intended total number of dashes, optional, default 200
  39880. * @returns the VertexData for the DashedLines
  39881. */
  39882. VertexData.CreateDashedLines = function (options) {
  39883. var dashSize = options.dashSize || 3;
  39884. var gapSize = options.gapSize || 1;
  39885. var dashNb = options.dashNb || 200;
  39886. var points = options.points;
  39887. var positions = new Array();
  39888. var indices = new Array();
  39889. var curvect = BABYLON.Vector3.Zero();
  39890. var lg = 0;
  39891. var nb = 0;
  39892. var shft = 0;
  39893. var dashshft = 0;
  39894. var curshft = 0;
  39895. var idx = 0;
  39896. var i = 0;
  39897. for (i = 0; i < points.length - 1; i++) {
  39898. points[i + 1].subtractToRef(points[i], curvect);
  39899. lg += curvect.length();
  39900. }
  39901. shft = lg / dashNb;
  39902. dashshft = dashSize * shft / (dashSize + gapSize);
  39903. for (i = 0; i < points.length - 1; i++) {
  39904. points[i + 1].subtractToRef(points[i], curvect);
  39905. nb = Math.floor(curvect.length() / shft);
  39906. curvect.normalize();
  39907. for (var j = 0; j < nb; j++) {
  39908. curshft = shft * j;
  39909. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  39910. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  39911. indices.push(idx, idx + 1);
  39912. idx += 2;
  39913. }
  39914. }
  39915. // Result
  39916. var vertexData = new VertexData();
  39917. vertexData.positions = positions;
  39918. vertexData.indices = indices;
  39919. return vertexData;
  39920. };
  39921. /**
  39922. * Creates the VertexData for a Ground
  39923. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  39924. * - width the width (x direction) of the ground, optional, default 1
  39925. * - height the height (z direction) of the ground, optional, default 1
  39926. * - subdivisions the number of subdivisions per side, optional, default 1
  39927. * @returns the VertexData of the Ground
  39928. */
  39929. VertexData.CreateGround = function (options) {
  39930. var indices = [];
  39931. var positions = [];
  39932. var normals = [];
  39933. var uvs = [];
  39934. var row, col;
  39935. var width = options.width || 1;
  39936. var height = options.height || 1;
  39937. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  39938. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  39939. for (row = 0; row <= subdivisionsY; row++) {
  39940. for (col = 0; col <= subdivisionsX; col++) {
  39941. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  39942. var normal = new BABYLON.Vector3(0, 1.0, 0);
  39943. positions.push(position.x, position.y, position.z);
  39944. normals.push(normal.x, normal.y, normal.z);
  39945. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  39946. }
  39947. }
  39948. for (row = 0; row < subdivisionsY; row++) {
  39949. for (col = 0; col < subdivisionsX; col++) {
  39950. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  39951. indices.push(col + 1 + row * (subdivisionsX + 1));
  39952. indices.push(col + row * (subdivisionsX + 1));
  39953. indices.push(col + (row + 1) * (subdivisionsX + 1));
  39954. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  39955. indices.push(col + row * (subdivisionsX + 1));
  39956. }
  39957. }
  39958. // Result
  39959. var vertexData = new VertexData();
  39960. vertexData.indices = indices;
  39961. vertexData.positions = positions;
  39962. vertexData.normals = normals;
  39963. vertexData.uvs = uvs;
  39964. return vertexData;
  39965. };
  39966. /**
  39967. * Creates the VertexData for a TiledGround by subdividing the ground into tiles
  39968. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  39969. * * xmin the ground minimum X coordinate, optional, default -1
  39970. * * zmin the ground minimum Z coordinate, optional, default -1
  39971. * * xmax the ground maximum X coordinate, optional, default 1
  39972. * * zmax the ground maximum Z coordinate, optional, default 1
  39973. * * 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}
  39974. * * 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}
  39975. * @returns the VertexData of the TiledGround
  39976. */
  39977. VertexData.CreateTiledGround = function (options) {
  39978. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  39979. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  39980. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  39981. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  39982. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  39983. var precision = options.precision || { w: 1, h: 1 };
  39984. var indices = new Array();
  39985. var positions = new Array();
  39986. var normals = new Array();
  39987. var uvs = new Array();
  39988. var row, col, tileRow, tileCol;
  39989. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  39990. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  39991. precision.w = (precision.w < 1) ? 1 : precision.w;
  39992. precision.h = (precision.h < 1) ? 1 : precision.h;
  39993. var tileSize = {
  39994. 'w': (xmax - xmin) / subdivisions.w,
  39995. 'h': (zmax - zmin) / subdivisions.h
  39996. };
  39997. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  39998. // Indices
  39999. var base = positions.length / 3;
  40000. var rowLength = precision.w + 1;
  40001. for (row = 0; row < precision.h; row++) {
  40002. for (col = 0; col < precision.w; col++) {
  40003. var square = [
  40004. base + col + row * rowLength,
  40005. base + (col + 1) + row * rowLength,
  40006. base + (col + 1) + (row + 1) * rowLength,
  40007. base + col + (row + 1) * rowLength
  40008. ];
  40009. indices.push(square[1]);
  40010. indices.push(square[2]);
  40011. indices.push(square[3]);
  40012. indices.push(square[0]);
  40013. indices.push(square[1]);
  40014. indices.push(square[3]);
  40015. }
  40016. }
  40017. // Position, normals and uvs
  40018. var position = BABYLON.Vector3.Zero();
  40019. var normal = new BABYLON.Vector3(0, 1.0, 0);
  40020. for (row = 0; row <= precision.h; row++) {
  40021. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  40022. for (col = 0; col <= precision.w; col++) {
  40023. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  40024. position.y = 0;
  40025. positions.push(position.x, position.y, position.z);
  40026. normals.push(normal.x, normal.y, normal.z);
  40027. uvs.push(col / precision.w, row / precision.h);
  40028. }
  40029. }
  40030. }
  40031. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  40032. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  40033. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  40034. }
  40035. }
  40036. // Result
  40037. var vertexData = new VertexData();
  40038. vertexData.indices = indices;
  40039. vertexData.positions = positions;
  40040. vertexData.normals = normals;
  40041. vertexData.uvs = uvs;
  40042. return vertexData;
  40043. };
  40044. /**
  40045. * Creates the VertexData of the Ground designed from a heightmap
  40046. * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap
  40047. * * width the width (x direction) of the ground
  40048. * * height the height (z direction) of the ground
  40049. * * subdivisions the number of subdivisions per side
  40050. * * minHeight the minimum altitude on the ground, optional, default 0
  40051. * * maxHeight the maximum altitude on the ground, optional default 1
  40052. * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)
  40053. * * buffer the array holding the image color data
  40054. * * bufferWidth the width of image
  40055. * * bufferHeight the height of image
  40056. * * alphaFilter Remove any data where the alpha channel is below this value, defaults 0 (all data visible)
  40057. * @returns the VertexData of the Ground designed from a heightmap
  40058. */
  40059. VertexData.CreateGroundFromHeightMap = function (options) {
  40060. var indices = [];
  40061. var positions = [];
  40062. var normals = [];
  40063. var uvs = [];
  40064. var row, col;
  40065. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  40066. var alphaFilter = options.alphaFilter || 0.0;
  40067. // Vertices
  40068. for (row = 0; row <= options.subdivisions; row++) {
  40069. for (col = 0; col <= options.subdivisions; col++) {
  40070. 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));
  40071. // Compute height
  40072. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  40073. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  40074. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  40075. var r = options.buffer[pos] / 255.0;
  40076. var g = options.buffer[pos + 1] / 255.0;
  40077. var b = options.buffer[pos + 2] / 255.0;
  40078. var a = options.buffer[pos + 3] / 255.0;
  40079. var gradient = r * filter.r + g * filter.g + b * filter.b;
  40080. // If our alpha channel is not within our filter then we will assign a 'special' height
  40081. // Then when building the indices, we will ignore any vertex that is using the special height
  40082. if (a >= alphaFilter) {
  40083. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  40084. }
  40085. else {
  40086. position.y = options.minHeight - BABYLON.Epsilon; // We can't have a height below minHeight, normally.
  40087. }
  40088. // Add vertex
  40089. positions.push(position.x, position.y, position.z);
  40090. normals.push(0, 0, 0);
  40091. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  40092. }
  40093. }
  40094. // Indices
  40095. for (row = 0; row < options.subdivisions; row++) {
  40096. for (col = 0; col < options.subdivisions; col++) {
  40097. // Calculate Indices
  40098. var idx1 = (col + 1 + (row + 1) * (options.subdivisions + 1));
  40099. var idx2 = (col + 1 + row * (options.subdivisions + 1));
  40100. var idx3 = (col + row * (options.subdivisions + 1));
  40101. var idx4 = (col + (row + 1) * (options.subdivisions + 1));
  40102. // Check that all indices are visible (based on our special height)
  40103. // Only display the vertex if all Indices are visible
  40104. // Positions are stored x,y,z for each vertex, hence the * 3 and + 1 for height
  40105. var isVisibleIdx1 = positions[idx1 * 3 + 1] >= options.minHeight;
  40106. var isVisibleIdx2 = positions[idx2 * 3 + 1] >= options.minHeight;
  40107. var isVisibleIdx3 = positions[idx3 * 3 + 1] >= options.minHeight;
  40108. if (isVisibleIdx1 && isVisibleIdx2 && isVisibleIdx3) {
  40109. indices.push(idx1);
  40110. indices.push(idx2);
  40111. indices.push(idx3);
  40112. }
  40113. var isVisibleIdx4 = positions[idx4 * 3 + 1] >= options.minHeight;
  40114. if (isVisibleIdx4 && isVisibleIdx1 && isVisibleIdx3) {
  40115. indices.push(idx4);
  40116. indices.push(idx1);
  40117. indices.push(idx3);
  40118. }
  40119. }
  40120. }
  40121. // Normals
  40122. VertexData.ComputeNormals(positions, indices, normals);
  40123. // Result
  40124. var vertexData = new VertexData();
  40125. vertexData.indices = indices;
  40126. vertexData.positions = positions;
  40127. vertexData.normals = normals;
  40128. vertexData.uvs = uvs;
  40129. return vertexData;
  40130. };
  40131. /**
  40132. * Creates the VertexData for a Plane
  40133. * @param options an object used to set the following optional parameters for the plane, required but can be empty
  40134. * * size sets the width and height of the plane to the value of size, optional default 1
  40135. * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size
  40136. * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size
  40137. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  40138. * * 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)
  40139. * * 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)
  40140. * @returns the VertexData of the box
  40141. */
  40142. VertexData.CreatePlane = function (options) {
  40143. var indices = [];
  40144. var positions = [];
  40145. var normals = [];
  40146. var uvs = [];
  40147. var width = options.width || options.size || 1;
  40148. var height = options.height || options.size || 1;
  40149. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  40150. // Vertices
  40151. var halfWidth = width / 2.0;
  40152. var halfHeight = height / 2.0;
  40153. positions.push(-halfWidth, -halfHeight, 0);
  40154. normals.push(0, 0, -1.0);
  40155. uvs.push(0.0, 0.0);
  40156. positions.push(halfWidth, -halfHeight, 0);
  40157. normals.push(0, 0, -1.0);
  40158. uvs.push(1.0, 0.0);
  40159. positions.push(halfWidth, halfHeight, 0);
  40160. normals.push(0, 0, -1.0);
  40161. uvs.push(1.0, 1.0);
  40162. positions.push(-halfWidth, halfHeight, 0);
  40163. normals.push(0, 0, -1.0);
  40164. uvs.push(0.0, 1.0);
  40165. // Indices
  40166. indices.push(0);
  40167. indices.push(1);
  40168. indices.push(2);
  40169. indices.push(0);
  40170. indices.push(2);
  40171. indices.push(3);
  40172. // Sides
  40173. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  40174. // Result
  40175. var vertexData = new VertexData();
  40176. vertexData.indices = indices;
  40177. vertexData.positions = positions;
  40178. vertexData.normals = normals;
  40179. vertexData.uvs = uvs;
  40180. return vertexData;
  40181. };
  40182. /**
  40183. * Creates the VertexData of the Disc or regular Polygon
  40184. * @param options an object used to set the following optional parameters for the disc, required but can be empty
  40185. * * radius the radius of the disc, optional default 0.5
  40186. * * tessellation the number of polygon sides, optional, default 64
  40187. * * 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
  40188. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  40189. * * 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)
  40190. * * 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)
  40191. * @returns the VertexData of the box
  40192. */
  40193. VertexData.CreateDisc = function (options) {
  40194. var positions = new Array();
  40195. var indices = new Array();
  40196. var normals = new Array();
  40197. var uvs = new Array();
  40198. var radius = options.radius || 0.5;
  40199. var tessellation = options.tessellation || 64;
  40200. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  40201. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  40202. // positions and uvs
  40203. positions.push(0, 0, 0); // disc center first
  40204. uvs.push(0.5, 0.5);
  40205. var theta = Math.PI * 2 * arc;
  40206. var step = theta / tessellation;
  40207. for (var a = 0; a < theta; a += step) {
  40208. var x = Math.cos(a);
  40209. var y = Math.sin(a);
  40210. var u = (x + 1) / 2;
  40211. var v = (1 - y) / 2;
  40212. positions.push(radius * x, radius * y, 0);
  40213. uvs.push(u, v);
  40214. }
  40215. if (arc === 1) {
  40216. positions.push(positions[3], positions[4], positions[5]); // close the circle
  40217. uvs.push(uvs[2], uvs[3]);
  40218. }
  40219. //indices
  40220. var vertexNb = positions.length / 3;
  40221. for (var i = 1; i < vertexNb - 1; i++) {
  40222. indices.push(i + 1, 0, i);
  40223. }
  40224. // result
  40225. VertexData.ComputeNormals(positions, indices, normals);
  40226. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  40227. var vertexData = new VertexData();
  40228. vertexData.indices = indices;
  40229. vertexData.positions = positions;
  40230. vertexData.normals = normals;
  40231. vertexData.uvs = uvs;
  40232. return vertexData;
  40233. };
  40234. /**
  40235. * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()
  40236. * All parameters are provided by MeshBuilder.CreatePolygon as needed
  40237. * @param polygon a mesh built from polygonTriangulation.build()
  40238. * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  40239. * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  40240. * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  40241. * @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)
  40242. * @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)
  40243. * @returns the VertexData of the Polygon
  40244. */
  40245. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  40246. var faceUV = fUV || new Array(3);
  40247. var faceColors = fColors;
  40248. var colors = [];
  40249. // default face colors and UV if undefined
  40250. for (var f = 0; f < 3; f++) {
  40251. if (faceUV[f] === undefined) {
  40252. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  40253. }
  40254. if (faceColors && faceColors[f] === undefined) {
  40255. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  40256. }
  40257. }
  40258. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  40259. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  40260. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  40261. var indices = polygon.getIndices();
  40262. // set face colours and textures
  40263. var idx = 0;
  40264. var face = 0;
  40265. for (var index = 0; index < normals.length; index += 3) {
  40266. //Edge Face no. 1
  40267. if (Math.abs(normals[index + 1]) < 0.001) {
  40268. face = 1;
  40269. }
  40270. //Top Face no. 0
  40271. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  40272. face = 0;
  40273. }
  40274. //Bottom Face no. 2
  40275. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  40276. face = 2;
  40277. }
  40278. idx = index / 3;
  40279. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  40280. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  40281. if (faceColors) {
  40282. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  40283. }
  40284. }
  40285. // sides
  40286. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  40287. // Result
  40288. var vertexData = new VertexData();
  40289. vertexData.indices = indices;
  40290. vertexData.positions = positions;
  40291. vertexData.normals = normals;
  40292. vertexData.uvs = uvs;
  40293. if (faceColors) {
  40294. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  40295. vertexData.colors = totalColors;
  40296. }
  40297. return vertexData;
  40298. };
  40299. /**
  40300. * Creates the VertexData of the IcoSphere
  40301. * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty
  40302. * * radius the radius of the IcoSphere, optional default 1
  40303. * * radiusX allows stretching in the x direction, optional, default radius
  40304. * * radiusY allows stretching in the y direction, optional, default radius
  40305. * * radiusZ allows stretching in the z direction, optional, default radius
  40306. * * flat when true creates a flat shaded mesh, optional, default true
  40307. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  40308. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  40309. * * 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)
  40310. * * 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)
  40311. * @returns the VertexData of the IcoSphere
  40312. */
  40313. VertexData.CreateIcoSphere = function (options) {
  40314. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  40315. var radius = options.radius || 1;
  40316. var flat = (options.flat === undefined) ? true : options.flat;
  40317. var subdivisions = options.subdivisions || 4;
  40318. var radiusX = options.radiusX || radius;
  40319. var radiusY = options.radiusY || radius;
  40320. var radiusZ = options.radiusZ || radius;
  40321. var t = (1 + Math.sqrt(5)) / 2;
  40322. // 12 vertex x,y,z
  40323. var ico_vertices = [
  40324. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  40325. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  40326. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  40327. ];
  40328. // index of 3 vertex makes a face of icopshere
  40329. var ico_indices = [
  40330. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  40331. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  40332. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  40333. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  40334. ];
  40335. // vertex for uv have aliased position, not for UV
  40336. var vertices_unalias_id = [
  40337. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  40338. // vertex alias
  40339. 0,
  40340. 2,
  40341. 3,
  40342. 3,
  40343. 3,
  40344. 4,
  40345. 7,
  40346. 8,
  40347. 9,
  40348. 9,
  40349. 10,
  40350. 11 // 23: B + 12
  40351. ];
  40352. // uv as integer step (not pixels !)
  40353. var ico_vertexuv = [
  40354. 5, 1, 3, 1, 6, 4, 0, 0,
  40355. 5, 3, 4, 2, 2, 2, 4, 0,
  40356. 2, 0, 1, 1, 6, 0, 6, 2,
  40357. // vertex alias (for same vertex on different faces)
  40358. 0, 4,
  40359. 3, 3,
  40360. 4, 4,
  40361. 3, 1,
  40362. 4, 2,
  40363. 4, 4,
  40364. 0, 2,
  40365. 1, 1,
  40366. 2, 2,
  40367. 3, 3,
  40368. 1, 3,
  40369. 2, 4 // 23: B + 12
  40370. ];
  40371. // Vertices[0, 1, ...9, A, B] : position on UV plane
  40372. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  40373. // First island of uv mapping
  40374. // v = 4h 3+ 2
  40375. // v = 3h 9+ 4
  40376. // v = 2h 9+ 5 B
  40377. // v = 1h 9 1 0
  40378. // v = 0h 3 8 7 A
  40379. // u = 0 1 2 3 4 5 6 *a
  40380. // Second island of uv mapping
  40381. // v = 4h 0+ B+ 4+
  40382. // v = 3h A+ 2+
  40383. // v = 2h 7+ 6 3+
  40384. // v = 1h 8+ 3+
  40385. // v = 0h
  40386. // u = 0 1 2 3 4 5 6 *a
  40387. // Face layout on texture UV mapping
  40388. // ============
  40389. // \ 4 /\ 16 / ======
  40390. // \ / \ / /\ 11 /
  40391. // \/ 7 \/ / \ /
  40392. // ======= / 10 \/
  40393. // /\ 17 /\ =======
  40394. // / \ / \ \ 15 /\
  40395. // / 8 \/ 12 \ \ / \
  40396. // ============ \/ 6 \
  40397. // \ 18 /\ ============
  40398. // \ / \ \ 5 /\ 0 /
  40399. // \/ 13 \ \ / \ /
  40400. // ======= \/ 1 \/
  40401. // =============
  40402. // /\ 19 /\ 2 /\
  40403. // / \ / \ / \
  40404. // / 14 \/ 9 \/ 3 \
  40405. // ===================
  40406. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  40407. var ustep = 138 / 1024;
  40408. var vstep = 239 / 1024;
  40409. var uoffset = 60 / 1024;
  40410. var voffset = 26 / 1024;
  40411. // Second island should have margin, not to touch the first island
  40412. // avoid any borderline artefact in pixel rounding
  40413. var island_u_offset = -40 / 1024;
  40414. var island_v_offset = +20 / 1024;
  40415. // face is either island 0 or 1 :
  40416. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  40417. var island = [
  40418. 0, 0, 0, 0, 1,
  40419. 0, 0, 1, 1, 0,
  40420. 0, 0, 1, 1, 0,
  40421. 0, 1, 1, 1, 0 // 15 - 19
  40422. ];
  40423. var indices = new Array();
  40424. var positions = new Array();
  40425. var normals = new Array();
  40426. var uvs = new Array();
  40427. var current_indice = 0;
  40428. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  40429. var face_vertex_pos = new Array(3);
  40430. var face_vertex_uv = new Array(3);
  40431. var v012;
  40432. for (v012 = 0; v012 < 3; v012++) {
  40433. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  40434. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  40435. }
  40436. // create all with normals
  40437. for (var face = 0; face < 20; face++) {
  40438. // 3 vertex per face
  40439. for (v012 = 0; v012 < 3; v012++) {
  40440. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  40441. var v_id = ico_indices[3 * face + v012];
  40442. // vertex have 3D position (x,y,z)
  40443. 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]);
  40444. // Normalize to get normal, then scale to radius
  40445. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  40446. // uv Coordinates from vertex ID
  40447. 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);
  40448. }
  40449. // Subdivide the face (interpolate pos, norm, uv)
  40450. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  40451. // - norm is linear interpolation of vertex corner normal
  40452. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  40453. // - uv is linear interpolation
  40454. //
  40455. // Topology is as below for sub-divide by 2
  40456. // vertex shown as v0,v1,v2
  40457. // interp index is i1 to progress in range [v0,v1[
  40458. // interp index is i2 to progress in range [v0,v2[
  40459. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  40460. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  40461. //
  40462. //
  40463. // i2 v2
  40464. // ^ ^
  40465. // / / \
  40466. // / / \
  40467. // / / \
  40468. // / / (0,1) \
  40469. // / #---------\
  40470. // / / \ (0,0)'/ \
  40471. // / / \ / \
  40472. // / / \ / \
  40473. // / / (0,0) \ / (1,0) \
  40474. // / #---------#---------\
  40475. // v0 v1
  40476. //
  40477. // --------------------> i1
  40478. //
  40479. // interp of (i1,i2):
  40480. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  40481. // along i1 : lerp(x0,x1, i1/(S-i2))
  40482. //
  40483. // centroid of triangle is needed to get help normal computation
  40484. // (c1,c2) are used for centroid location
  40485. var interp_vertex = function (i1, i2, c1, c2) {
  40486. // vertex is interpolated from
  40487. // - face_vertex_pos[0..2]
  40488. // - face_vertex_uv[0..2]
  40489. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  40490. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  40491. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  40492. pos_interp.normalize();
  40493. var vertex_normal;
  40494. if (flat) {
  40495. // in flat mode, recalculate normal as face centroid normal
  40496. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  40497. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  40498. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  40499. }
  40500. else {
  40501. // in smooth mode, recalculate normal from each single vertex position
  40502. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  40503. }
  40504. // Vertex normal need correction due to X,Y,Z radius scaling
  40505. vertex_normal.x /= radiusX;
  40506. vertex_normal.y /= radiusY;
  40507. vertex_normal.z /= radiusZ;
  40508. vertex_normal.normalize();
  40509. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  40510. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  40511. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  40512. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  40513. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  40514. uvs.push(uv_interp.x, uv_interp.y);
  40515. // push each vertex has member of a face
  40516. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  40517. indices.push(current_indice);
  40518. current_indice++;
  40519. };
  40520. for (var i2 = 0; i2 < subdivisions; i2++) {
  40521. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  40522. // face : (i1,i2) for /\ :
  40523. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  40524. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  40525. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  40526. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  40527. if (i1 + i2 + 1 < subdivisions) {
  40528. // face : (i1,i2)' for \/ :
  40529. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  40530. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  40531. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  40532. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  40533. }
  40534. }
  40535. }
  40536. }
  40537. // Sides
  40538. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  40539. // Result
  40540. var vertexData = new VertexData();
  40541. vertexData.indices = indices;
  40542. vertexData.positions = positions;
  40543. vertexData.normals = normals;
  40544. vertexData.uvs = uvs;
  40545. return vertexData;
  40546. };
  40547. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  40548. /**
  40549. * Creates the VertexData for a Polyhedron
  40550. * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty
  40551. * * type provided types are:
  40552. * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  40553. * * 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)
  40554. * * size the size of the IcoSphere, optional default 1
  40555. * * sizeX allows stretching in the x direction, optional, default size
  40556. * * sizeY allows stretching in the y direction, optional, default size
  40557. * * sizeZ allows stretching in the z direction, optional, default size
  40558. * * 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
  40559. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  40560. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  40561. * * flat when true creates a flat shaded mesh, optional, default true
  40562. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  40563. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  40564. * * 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)
  40565. * * 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)
  40566. * @returns the VertexData of the Polyhedron
  40567. */
  40568. VertexData.CreatePolyhedron = function (options) {
  40569. // provided polyhedron types :
  40570. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  40571. // 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)
  40572. var polyhedra = [];
  40573. 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]] };
  40574. 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]] };
  40575. polyhedra[2] = {
  40576. 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]],
  40577. 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]]
  40578. };
  40579. polyhedra[3] = {
  40580. 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]],
  40581. 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]]
  40582. };
  40583. polyhedra[4] = {
  40584. 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]],
  40585. 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]]
  40586. };
  40587. 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]] };
  40588. 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]] };
  40589. 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]] };
  40590. 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]] };
  40591. 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]] };
  40592. 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]] };
  40593. 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]] };
  40594. 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]] };
  40595. 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]] };
  40596. polyhedra[14] = {
  40597. 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]],
  40598. 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]]
  40599. };
  40600. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  40601. var size = options.size;
  40602. var sizeX = options.sizeX || size || 1;
  40603. var sizeY = options.sizeY || size || 1;
  40604. var sizeZ = options.sizeZ || size || 1;
  40605. var data = options.custom || polyhedra[type];
  40606. var nbfaces = data.face.length;
  40607. var faceUV = options.faceUV || new Array(nbfaces);
  40608. var faceColors = options.faceColors;
  40609. var flat = (options.flat === undefined) ? true : options.flat;
  40610. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  40611. var positions = new Array();
  40612. var indices = new Array();
  40613. var normals = new Array();
  40614. var uvs = new Array();
  40615. var colors = new Array();
  40616. var index = 0;
  40617. var faceIdx = 0; // face cursor in the array "indexes"
  40618. var indexes = new Array();
  40619. var i = 0;
  40620. var f = 0;
  40621. var u, v, ang, x, y, tmp;
  40622. // default face colors and UV if undefined
  40623. if (flat) {
  40624. for (f = 0; f < nbfaces; f++) {
  40625. if (faceColors && faceColors[f] === undefined) {
  40626. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  40627. }
  40628. if (faceUV && faceUV[f] === undefined) {
  40629. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  40630. }
  40631. }
  40632. }
  40633. if (!flat) {
  40634. for (i = 0; i < data.vertex.length; i++) {
  40635. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  40636. uvs.push(0, 0);
  40637. }
  40638. for (f = 0; f < nbfaces; f++) {
  40639. for (i = 0; i < data.face[f].length - 2; i++) {
  40640. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  40641. }
  40642. }
  40643. }
  40644. else {
  40645. for (f = 0; f < nbfaces; f++) {
  40646. var fl = data.face[f].length; // number of vertices of the current face
  40647. ang = 2 * Math.PI / fl;
  40648. x = 0.5 * Math.tan(ang / 2);
  40649. y = 0.5;
  40650. // positions, uvs, colors
  40651. for (i = 0; i < fl; i++) {
  40652. // positions
  40653. 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);
  40654. indexes.push(index);
  40655. index++;
  40656. // uvs
  40657. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  40658. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  40659. uvs.push(u, v);
  40660. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  40661. y = x * Math.sin(ang) + y * Math.cos(ang);
  40662. x = tmp;
  40663. // colors
  40664. if (faceColors) {
  40665. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  40666. }
  40667. }
  40668. // indices from indexes
  40669. for (i = 0; i < fl - 2; i++) {
  40670. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  40671. }
  40672. faceIdx += fl;
  40673. }
  40674. }
  40675. VertexData.ComputeNormals(positions, indices, normals);
  40676. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  40677. var vertexData = new VertexData();
  40678. vertexData.positions = positions;
  40679. vertexData.indices = indices;
  40680. vertexData.normals = normals;
  40681. vertexData.uvs = uvs;
  40682. if (faceColors && flat) {
  40683. vertexData.colors = colors;
  40684. }
  40685. return vertexData;
  40686. };
  40687. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  40688. /**
  40689. * Creates the VertexData for a TorusKnot
  40690. * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty
  40691. * * radius the radius of the torus knot, optional, default 2
  40692. * * tube the thickness of the tube, optional, default 0.5
  40693. * * radialSegments the number of sides on each tube segments, optional, default 32
  40694. * * tubularSegments the number of tubes to decompose the knot into, optional, default 32
  40695. * * p the number of windings around the z axis, optional, default 2
  40696. * * q the number of windings around the x axis, optional, default 3
  40697. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  40698. * * 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)
  40699. * * 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)
  40700. * @returns the VertexData of the Torus Knot
  40701. */
  40702. VertexData.CreateTorusKnot = function (options) {
  40703. var indices = new Array();
  40704. var positions = new Array();
  40705. var normals = new Array();
  40706. var uvs = new Array();
  40707. var radius = options.radius || 2;
  40708. var tube = options.tube || 0.5;
  40709. var radialSegments = options.radialSegments || 32;
  40710. var tubularSegments = options.tubularSegments || 32;
  40711. var p = options.p || 2;
  40712. var q = options.q || 3;
  40713. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  40714. // Helper
  40715. var getPos = function (angle) {
  40716. var cu = Math.cos(angle);
  40717. var su = Math.sin(angle);
  40718. var quOverP = q / p * angle;
  40719. var cs = Math.cos(quOverP);
  40720. var tx = radius * (2 + cs) * 0.5 * cu;
  40721. var ty = radius * (2 + cs) * su * 0.5;
  40722. var tz = radius * Math.sin(quOverP) * 0.5;
  40723. return new BABYLON.Vector3(tx, ty, tz);
  40724. };
  40725. // Vertices
  40726. var i;
  40727. var j;
  40728. for (i = 0; i <= radialSegments; i++) {
  40729. var modI = i % radialSegments;
  40730. var u = modI / radialSegments * 2 * p * Math.PI;
  40731. var p1 = getPos(u);
  40732. var p2 = getPos(u + 0.01);
  40733. var tang = p2.subtract(p1);
  40734. var n = p2.add(p1);
  40735. var bitan = BABYLON.Vector3.Cross(tang, n);
  40736. n = BABYLON.Vector3.Cross(bitan, tang);
  40737. bitan.normalize();
  40738. n.normalize();
  40739. for (j = 0; j < tubularSegments; j++) {
  40740. var modJ = j % tubularSegments;
  40741. var v = modJ / tubularSegments * 2 * Math.PI;
  40742. var cx = -tube * Math.cos(v);
  40743. var cy = tube * Math.sin(v);
  40744. positions.push(p1.x + cx * n.x + cy * bitan.x);
  40745. positions.push(p1.y + cx * n.y + cy * bitan.y);
  40746. positions.push(p1.z + cx * n.z + cy * bitan.z);
  40747. uvs.push(i / radialSegments);
  40748. uvs.push(j / tubularSegments);
  40749. }
  40750. }
  40751. for (i = 0; i < radialSegments; i++) {
  40752. for (j = 0; j < tubularSegments; j++) {
  40753. var jNext = (j + 1) % tubularSegments;
  40754. var a = i * tubularSegments + j;
  40755. var b = (i + 1) * tubularSegments + j;
  40756. var c = (i + 1) * tubularSegments + jNext;
  40757. var d = i * tubularSegments + jNext;
  40758. indices.push(d);
  40759. indices.push(b);
  40760. indices.push(a);
  40761. indices.push(d);
  40762. indices.push(c);
  40763. indices.push(b);
  40764. }
  40765. }
  40766. // Normals
  40767. VertexData.ComputeNormals(positions, indices, normals);
  40768. // Sides
  40769. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  40770. // Result
  40771. var vertexData = new VertexData();
  40772. vertexData.indices = indices;
  40773. vertexData.positions = positions;
  40774. vertexData.normals = normals;
  40775. vertexData.uvs = uvs;
  40776. return vertexData;
  40777. };
  40778. // Tools
  40779. /**
  40780. * Compute normals for given positions and indices
  40781. * @param positions an array of vertex positions, [...., x, y, z, ......]
  40782. * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]
  40783. * @param normals an array of vertex normals, [...., x, y, z, ......]
  40784. * @param options an object used to set the following optional parameters for the TorusKnot, optional
  40785. * * facetNormals : optional array of facet normals (vector3)
  40786. * * facetPositions : optional array of facet positions (vector3)
  40787. * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  40788. * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  40789. * * bInfo : optional bounding info, required for facetPartitioning computation
  40790. * * bbSize : optional bounding box size data, required for facetPartitioning computation
  40791. * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  40792. * * useRightHandedSystem: optional boolean to for right handed system computation
  40793. * * depthSort : optional boolean to enable the facet depth sort computation
  40794. * * distanceTo : optional Vector3 to compute the facet depth from this location
  40795. * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  40796. */
  40797. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  40798. // temporary scalar variables
  40799. var index = 0; // facet index
  40800. var p1p2x = 0.0; // p1p2 vector x coordinate
  40801. var p1p2y = 0.0; // p1p2 vector y coordinate
  40802. var p1p2z = 0.0; // p1p2 vector z coordinate
  40803. var p3p2x = 0.0; // p3p2 vector x coordinate
  40804. var p3p2y = 0.0; // p3p2 vector y coordinate
  40805. var p3p2z = 0.0; // p3p2 vector z coordinate
  40806. var faceNormalx = 0.0; // facet normal x coordinate
  40807. var faceNormaly = 0.0; // facet normal y coordinate
  40808. var faceNormalz = 0.0; // facet normal z coordinate
  40809. var length = 0.0; // facet normal length before normalization
  40810. var v1x = 0; // vector1 x index in the positions array
  40811. var v1y = 0; // vector1 y index in the positions array
  40812. var v1z = 0; // vector1 z index in the positions array
  40813. var v2x = 0; // vector2 x index in the positions array
  40814. var v2y = 0; // vector2 y index in the positions array
  40815. var v2z = 0; // vector2 z index in the positions array
  40816. var v3x = 0; // vector3 x index in the positions array
  40817. var v3y = 0; // vector3 y index in the positions array
  40818. var v3z = 0; // vector3 z index in the positions array
  40819. var computeFacetNormals = false;
  40820. var computeFacetPositions = false;
  40821. var computeFacetPartitioning = false;
  40822. var computeDepthSort = false;
  40823. var faceNormalSign = 1;
  40824. var ratio = 0;
  40825. var distanceTo = null;
  40826. if (options) {
  40827. computeFacetNormals = (options.facetNormals) ? true : false;
  40828. computeFacetPositions = (options.facetPositions) ? true : false;
  40829. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  40830. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  40831. ratio = options.ratio || 0;
  40832. computeDepthSort = (options.depthSort) ? true : false;
  40833. distanceTo = (options.distanceTo);
  40834. if (computeDepthSort) {
  40835. if (distanceTo === undefined) {
  40836. distanceTo = BABYLON.Vector3.Zero();
  40837. }
  40838. var depthSortedFacets = options.depthSortedFacets;
  40839. }
  40840. }
  40841. // facetPartitioning reinit if needed
  40842. var xSubRatio = 0;
  40843. var ySubRatio = 0;
  40844. var zSubRatio = 0;
  40845. var subSq = 0;
  40846. if (computeFacetPartitioning && options && options.bbSize) {
  40847. var ox = 0; // X partitioning index for facet position
  40848. var oy = 0; // Y partinioning index for facet position
  40849. var oz = 0; // Z partinioning index for facet position
  40850. var b1x = 0; // X partitioning index for facet v1 vertex
  40851. var b1y = 0; // Y partitioning index for facet v1 vertex
  40852. var b1z = 0; // z partitioning index for facet v1 vertex
  40853. var b2x = 0; // X partitioning index for facet v2 vertex
  40854. var b2y = 0; // Y partitioning index for facet v2 vertex
  40855. var b2z = 0; // Z partitioning index for facet v2 vertex
  40856. var b3x = 0; // X partitioning index for facet v3 vertex
  40857. var b3y = 0; // Y partitioning index for facet v3 vertex
  40858. var b3z = 0; // Z partitioning index for facet v3 vertex
  40859. var block_idx_o = 0; // facet barycenter block index
  40860. var block_idx_v1 = 0; // v1 vertex block index
  40861. var block_idx_v2 = 0; // v2 vertex block index
  40862. var block_idx_v3 = 0; // v3 vertex block index
  40863. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  40864. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  40865. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  40866. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  40867. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  40868. subSq = options.subDiv.max * options.subDiv.max;
  40869. options.facetPartitioning.length = 0;
  40870. }
  40871. // reset the normals
  40872. for (index = 0; index < positions.length; index++) {
  40873. normals[index] = 0.0;
  40874. }
  40875. // Loop : 1 indice triplet = 1 facet
  40876. var nbFaces = (indices.length / 3) | 0;
  40877. for (index = 0; index < nbFaces; index++) {
  40878. // get the indexes of the coordinates of each vertex of the facet
  40879. v1x = indices[index * 3] * 3;
  40880. v1y = v1x + 1;
  40881. v1z = v1x + 2;
  40882. v2x = indices[index * 3 + 1] * 3;
  40883. v2y = v2x + 1;
  40884. v2z = v2x + 2;
  40885. v3x = indices[index * 3 + 2] * 3;
  40886. v3y = v3x + 1;
  40887. v3z = v3x + 2;
  40888. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  40889. p1p2y = positions[v1y] - positions[v2y];
  40890. p1p2z = positions[v1z] - positions[v2z];
  40891. p3p2x = positions[v3x] - positions[v2x];
  40892. p3p2y = positions[v3y] - positions[v2y];
  40893. p3p2z = positions[v3z] - positions[v2z];
  40894. // compute the face normal with the cross product
  40895. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  40896. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  40897. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  40898. // normalize this normal and store it in the array facetData
  40899. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  40900. length = (length === 0) ? 1.0 : length;
  40901. faceNormalx /= length;
  40902. faceNormaly /= length;
  40903. faceNormalz /= length;
  40904. if (computeFacetNormals && options) {
  40905. options.facetNormals[index].x = faceNormalx;
  40906. options.facetNormals[index].y = faceNormaly;
  40907. options.facetNormals[index].z = faceNormalz;
  40908. }
  40909. if (computeFacetPositions && options) {
  40910. // compute and the facet barycenter coordinates in the array facetPositions
  40911. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  40912. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  40913. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  40914. }
  40915. if (computeFacetPartitioning && options) {
  40916. // store the facet indexes in arrays in the main facetPartitioning array :
  40917. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  40918. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  40919. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  40920. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  40921. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  40922. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  40923. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  40924. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  40925. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  40926. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  40927. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  40928. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  40929. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  40930. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  40931. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  40932. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  40933. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  40934. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  40935. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  40936. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  40937. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  40938. // push each facet index in each block containing the vertex
  40939. options.facetPartitioning[block_idx_v1].push(index);
  40940. if (block_idx_v2 != block_idx_v1) {
  40941. options.facetPartitioning[block_idx_v2].push(index);
  40942. }
  40943. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  40944. options.facetPartitioning[block_idx_v3].push(index);
  40945. }
  40946. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  40947. options.facetPartitioning[block_idx_o].push(index);
  40948. }
  40949. }
  40950. if (computeDepthSort && options && options.facetPositions) {
  40951. var dsf = depthSortedFacets[index];
  40952. dsf.ind = index * 3;
  40953. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  40954. }
  40955. // compute the normals anyway
  40956. normals[v1x] += faceNormalx; // accumulate all the normals per face
  40957. normals[v1y] += faceNormaly;
  40958. normals[v1z] += faceNormalz;
  40959. normals[v2x] += faceNormalx;
  40960. normals[v2y] += faceNormaly;
  40961. normals[v2z] += faceNormalz;
  40962. normals[v3x] += faceNormalx;
  40963. normals[v3y] += faceNormaly;
  40964. normals[v3z] += faceNormalz;
  40965. }
  40966. // last normalization of each normal
  40967. for (index = 0; index < normals.length / 3; index++) {
  40968. faceNormalx = normals[index * 3];
  40969. faceNormaly = normals[index * 3 + 1];
  40970. faceNormalz = normals[index * 3 + 2];
  40971. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  40972. length = (length === 0) ? 1.0 : length;
  40973. faceNormalx /= length;
  40974. faceNormaly /= length;
  40975. faceNormalz /= length;
  40976. normals[index * 3] = faceNormalx;
  40977. normals[index * 3 + 1] = faceNormaly;
  40978. normals[index * 3 + 2] = faceNormalz;
  40979. }
  40980. };
  40981. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  40982. var li = indices.length;
  40983. var ln = normals.length;
  40984. var i;
  40985. var n;
  40986. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  40987. switch (sideOrientation) {
  40988. case BABYLON.Mesh.FRONTSIDE:
  40989. // nothing changed
  40990. break;
  40991. case BABYLON.Mesh.BACKSIDE:
  40992. var tmp;
  40993. // indices
  40994. for (i = 0; i < li; i += 3) {
  40995. tmp = indices[i];
  40996. indices[i] = indices[i + 2];
  40997. indices[i + 2] = tmp;
  40998. }
  40999. // normals
  41000. for (n = 0; n < ln; n++) {
  41001. normals[n] = -normals[n];
  41002. }
  41003. break;
  41004. case BABYLON.Mesh.DOUBLESIDE:
  41005. // positions
  41006. var lp = positions.length;
  41007. var l = lp / 3;
  41008. for (var p = 0; p < lp; p++) {
  41009. positions[lp + p] = positions[p];
  41010. }
  41011. // indices
  41012. for (i = 0; i < li; i += 3) {
  41013. indices[i + li] = indices[i + 2] + l;
  41014. indices[i + 1 + li] = indices[i + 1] + l;
  41015. indices[i + 2 + li] = indices[i] + l;
  41016. }
  41017. // normals
  41018. for (n = 0; n < ln; n++) {
  41019. normals[ln + n] = -normals[n];
  41020. }
  41021. // uvs
  41022. var lu = uvs.length;
  41023. var u = 0;
  41024. for (u = 0; u < lu; u++) {
  41025. uvs[u + lu] = uvs[u];
  41026. }
  41027. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  41028. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  41029. u = 0;
  41030. for (i = 0; i < lu / 2; i++) {
  41031. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  41032. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  41033. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  41034. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  41035. u += 2;
  41036. }
  41037. break;
  41038. }
  41039. };
  41040. /**
  41041. * Applies VertexData created from the imported parameters to the geometry
  41042. * @param parsedVertexData the parsed data from an imported file
  41043. * @param geometry the geometry to apply the VertexData to
  41044. */
  41045. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  41046. var vertexData = new VertexData();
  41047. // positions
  41048. var positions = parsedVertexData.positions;
  41049. if (positions) {
  41050. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  41051. }
  41052. // normals
  41053. var normals = parsedVertexData.normals;
  41054. if (normals) {
  41055. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  41056. }
  41057. // tangents
  41058. var tangents = parsedVertexData.tangents;
  41059. if (tangents) {
  41060. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  41061. }
  41062. // uvs
  41063. var uvs = parsedVertexData.uvs;
  41064. if (uvs) {
  41065. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  41066. }
  41067. // uv2s
  41068. var uv2s = parsedVertexData.uv2s;
  41069. if (uv2s) {
  41070. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  41071. }
  41072. // uv3s
  41073. var uv3s = parsedVertexData.uv3s;
  41074. if (uv3s) {
  41075. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  41076. }
  41077. // uv4s
  41078. var uv4s = parsedVertexData.uv4s;
  41079. if (uv4s) {
  41080. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  41081. }
  41082. // uv5s
  41083. var uv5s = parsedVertexData.uv5s;
  41084. if (uv5s) {
  41085. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  41086. }
  41087. // uv6s
  41088. var uv6s = parsedVertexData.uv6s;
  41089. if (uv6s) {
  41090. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  41091. }
  41092. // colors
  41093. var colors = parsedVertexData.colors;
  41094. if (colors) {
  41095. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  41096. }
  41097. // matricesIndices
  41098. var matricesIndices = parsedVertexData.matricesIndices;
  41099. if (matricesIndices) {
  41100. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  41101. }
  41102. // matricesWeights
  41103. var matricesWeights = parsedVertexData.matricesWeights;
  41104. if (matricesWeights) {
  41105. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  41106. }
  41107. // indices
  41108. var indices = parsedVertexData.indices;
  41109. if (indices) {
  41110. vertexData.indices = indices;
  41111. }
  41112. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  41113. };
  41114. return VertexData;
  41115. }());
  41116. BABYLON.VertexData = VertexData;
  41117. })(BABYLON || (BABYLON = {}));
  41118. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  41119. var BABYLON;
  41120. (function (BABYLON) {
  41121. /**
  41122. * Class used to store geometry data (vertex buffers + index buffer)
  41123. */
  41124. var Geometry = /** @class */ (function () {
  41125. /**
  41126. * Creates a new geometry
  41127. * @param id defines the unique ID
  41128. * @param scene defines the hosting scene
  41129. * @param vertexData defines the VertexData used to get geometry data
  41130. * @param updatable defines if geometry must be updatable (false by default)
  41131. * @param mesh defines the mesh that will be associated with the geometry
  41132. */
  41133. function Geometry(id, scene, vertexData, updatable, mesh) {
  41134. if (updatable === void 0) { updatable = false; }
  41135. if (mesh === void 0) { mesh = null; }
  41136. /**
  41137. * Gets the delay loading state of the geometry (none by default which means not delayed)
  41138. */
  41139. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  41140. this._totalVertices = 0;
  41141. this._isDisposed = false;
  41142. this._indexBufferIsUpdatable = false;
  41143. this.id = id;
  41144. this.uniqueId = scene.getUniqueId();
  41145. this._engine = scene.getEngine();
  41146. this._meshes = [];
  41147. this._scene = scene;
  41148. //Init vertex buffer cache
  41149. this._vertexBuffers = {};
  41150. this._indices = [];
  41151. this._updatable = updatable;
  41152. // vertexData
  41153. if (vertexData) {
  41154. this.setAllVerticesData(vertexData, updatable);
  41155. }
  41156. else {
  41157. this._totalVertices = 0;
  41158. this._indices = [];
  41159. }
  41160. if (this._engine.getCaps().vertexArrayObject) {
  41161. this._vertexArrayObjects = {};
  41162. }
  41163. // applyToMesh
  41164. if (mesh) {
  41165. this.applyToMesh(mesh);
  41166. mesh.computeWorldMatrix(true);
  41167. }
  41168. }
  41169. Object.defineProperty(Geometry.prototype, "boundingBias", {
  41170. /**
  41171. * 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
  41172. */
  41173. get: function () {
  41174. return this._boundingBias;
  41175. },
  41176. /**
  41177. * 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
  41178. */
  41179. set: function (value) {
  41180. if (this._boundingBias) {
  41181. this._boundingBias.copyFrom(value);
  41182. }
  41183. else {
  41184. this._boundingBias = value.clone();
  41185. }
  41186. this._updateBoundingInfo(true, null);
  41187. },
  41188. enumerable: true,
  41189. configurable: true
  41190. });
  41191. /**
  41192. * Static function used to attach a new empty geometry to a mesh
  41193. * @param mesh defines the mesh to attach the geometry to
  41194. * @returns the new Geometry
  41195. */
  41196. Geometry.CreateGeometryForMesh = function (mesh) {
  41197. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  41198. geometry.applyToMesh(mesh);
  41199. return geometry;
  41200. };
  41201. Object.defineProperty(Geometry.prototype, "extend", {
  41202. /**
  41203. * Gets the current extend of the geometry
  41204. */
  41205. get: function () {
  41206. return this._extend;
  41207. },
  41208. enumerable: true,
  41209. configurable: true
  41210. });
  41211. /**
  41212. * Gets the hosting scene
  41213. * @returns the hosting Scene
  41214. */
  41215. Geometry.prototype.getScene = function () {
  41216. return this._scene;
  41217. };
  41218. /**
  41219. * Gets the hosting engine
  41220. * @returns the hosting Engine
  41221. */
  41222. Geometry.prototype.getEngine = function () {
  41223. return this._engine;
  41224. };
  41225. /**
  41226. * Defines if the geometry is ready to use
  41227. * @returns true if the geometry is ready to be used
  41228. */
  41229. Geometry.prototype.isReady = function () {
  41230. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  41231. };
  41232. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  41233. /**
  41234. * Gets a value indicating that the geometry should not be serialized
  41235. */
  41236. get: function () {
  41237. for (var index = 0; index < this._meshes.length; index++) {
  41238. if (!this._meshes[index].doNotSerialize) {
  41239. return false;
  41240. }
  41241. }
  41242. return true;
  41243. },
  41244. enumerable: true,
  41245. configurable: true
  41246. });
  41247. /** @hidden */
  41248. Geometry.prototype._rebuild = function () {
  41249. if (this._vertexArrayObjects) {
  41250. this._vertexArrayObjects = {};
  41251. }
  41252. // Index buffer
  41253. if (this._meshes.length !== 0 && this._indices) {
  41254. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  41255. }
  41256. // Vertex buffers
  41257. for (var key in this._vertexBuffers) {
  41258. var vertexBuffer = this._vertexBuffers[key];
  41259. vertexBuffer._rebuild();
  41260. }
  41261. };
  41262. /**
  41263. * Affects all geometry data in one call
  41264. * @param vertexData defines the geometry data
  41265. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  41266. */
  41267. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  41268. vertexData.applyToGeometry(this, updatable);
  41269. this.notifyUpdate();
  41270. };
  41271. /**
  41272. * Set specific vertex data
  41273. * @param kind defines the data kind (Position, normal, etc...)
  41274. * @param data defines the vertex data to use
  41275. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  41276. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  41277. */
  41278. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  41279. if (updatable === void 0) { updatable = false; }
  41280. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  41281. this.setVerticesBuffer(buffer);
  41282. };
  41283. /**
  41284. * Removes a specific vertex data
  41285. * @param kind defines the data kind (Position, normal, etc...)
  41286. */
  41287. Geometry.prototype.removeVerticesData = function (kind) {
  41288. if (this._vertexBuffers[kind]) {
  41289. this._vertexBuffers[kind].dispose();
  41290. delete this._vertexBuffers[kind];
  41291. }
  41292. };
  41293. /**
  41294. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  41295. * @param buffer defines the vertex buffer to use
  41296. * @param totalVertices defines the total number of vertices for position kind (could be null)
  41297. */
  41298. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  41299. if (totalVertices === void 0) { totalVertices = null; }
  41300. var kind = buffer.getKind();
  41301. if (this._vertexBuffers[kind]) {
  41302. this._vertexBuffers[kind].dispose();
  41303. }
  41304. this._vertexBuffers[kind] = buffer;
  41305. if (kind === BABYLON.VertexBuffer.PositionKind) {
  41306. var data = buffer.getData();
  41307. if (totalVertices != null) {
  41308. this._totalVertices = totalVertices;
  41309. }
  41310. else {
  41311. if (data != null) {
  41312. this._totalVertices = data.length / (buffer.byteStride / 4);
  41313. }
  41314. }
  41315. this._updateExtend(data);
  41316. this._resetPointsArrayCache();
  41317. var meshes = this._meshes;
  41318. var numOfMeshes = meshes.length;
  41319. for (var index = 0; index < numOfMeshes; index++) {
  41320. var mesh = meshes[index];
  41321. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  41322. mesh._createGlobalSubMesh(false);
  41323. mesh.computeWorldMatrix(true);
  41324. }
  41325. }
  41326. this.notifyUpdate(kind);
  41327. if (this._vertexArrayObjects) {
  41328. this._disposeVertexArrayObjects();
  41329. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  41330. }
  41331. };
  41332. /**
  41333. * Update a specific vertex buffer
  41334. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  41335. * It will do nothing if the buffer is not updatable
  41336. * @param kind defines the data kind (Position, normal, etc...)
  41337. * @param data defines the data to use
  41338. * @param offset defines the offset in the target buffer where to store the data
  41339. * @param useBytes set to true if the offset is in bytes
  41340. */
  41341. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset, useBytes) {
  41342. if (useBytes === void 0) { useBytes = false; }
  41343. var vertexBuffer = this.getVertexBuffer(kind);
  41344. if (!vertexBuffer) {
  41345. return;
  41346. }
  41347. vertexBuffer.updateDirectly(data, offset, useBytes);
  41348. this.notifyUpdate(kind);
  41349. };
  41350. /**
  41351. * Update a specific vertex buffer
  41352. * This function will create a new buffer if the current one is not updatable
  41353. * @param kind defines the data kind (Position, normal, etc...)
  41354. * @param data defines the data to use
  41355. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  41356. */
  41357. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  41358. if (updateExtends === void 0) { updateExtends = false; }
  41359. var vertexBuffer = this.getVertexBuffer(kind);
  41360. if (!vertexBuffer) {
  41361. return;
  41362. }
  41363. vertexBuffer.update(data);
  41364. if (kind === BABYLON.VertexBuffer.PositionKind) {
  41365. this._updateBoundingInfo(updateExtends, data);
  41366. }
  41367. this.notifyUpdate(kind);
  41368. };
  41369. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  41370. if (updateExtends) {
  41371. this._updateExtend(data);
  41372. }
  41373. this._resetPointsArrayCache();
  41374. if (updateExtends) {
  41375. var meshes = this._meshes;
  41376. for (var _i = 0, meshes_1 = meshes; _i < meshes_1.length; _i++) {
  41377. var mesh = meshes_1[_i];
  41378. if (mesh._boundingInfo) {
  41379. mesh._boundingInfo.reConstruct(this._extend.minimum, this._extend.maximum);
  41380. }
  41381. else {
  41382. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  41383. }
  41384. var subMeshes = mesh.subMeshes;
  41385. for (var _a = 0, subMeshes_1 = subMeshes; _a < subMeshes_1.length; _a++) {
  41386. var subMesh = subMeshes_1[_a];
  41387. subMesh.refreshBoundingInfo();
  41388. }
  41389. }
  41390. }
  41391. };
  41392. /** @hidden */
  41393. Geometry.prototype._bind = function (effect, indexToBind) {
  41394. if (!effect) {
  41395. return;
  41396. }
  41397. if (indexToBind === undefined) {
  41398. indexToBind = this._indexBuffer;
  41399. }
  41400. var vbs = this.getVertexBuffers();
  41401. if (!vbs) {
  41402. return;
  41403. }
  41404. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  41405. this._engine.bindBuffers(vbs, indexToBind, effect);
  41406. return;
  41407. }
  41408. // Using VAO
  41409. if (!this._vertexArrayObjects[effect.key]) {
  41410. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  41411. }
  41412. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  41413. };
  41414. /**
  41415. * Gets total number of vertices
  41416. * @returns the total number of vertices
  41417. */
  41418. Geometry.prototype.getTotalVertices = function () {
  41419. if (!this.isReady()) {
  41420. return 0;
  41421. }
  41422. return this._totalVertices;
  41423. };
  41424. /**
  41425. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  41426. * @param kind defines the data kind (Position, normal, etc...)
  41427. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  41428. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  41429. * @returns a float array containing vertex data
  41430. */
  41431. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  41432. var vertexBuffer = this.getVertexBuffer(kind);
  41433. if (!vertexBuffer) {
  41434. return null;
  41435. }
  41436. var data = vertexBuffer.getData();
  41437. if (!data) {
  41438. return null;
  41439. }
  41440. var tightlyPackedByteStride = vertexBuffer.getSize() * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  41441. var count = this._totalVertices * vertexBuffer.getSize();
  41442. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== tightlyPackedByteStride) {
  41443. var copy_1 = [];
  41444. vertexBuffer.forEach(count, function (value) { return copy_1.push(value); });
  41445. return copy_1;
  41446. }
  41447. if (!((data instanceof Array) || (data instanceof Float32Array)) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  41448. if (data instanceof Array) {
  41449. var offset = vertexBuffer.byteOffset / 4;
  41450. return BABYLON.Tools.Slice(data, offset, offset + count);
  41451. }
  41452. else if (data instanceof ArrayBuffer) {
  41453. return new Float32Array(data, vertexBuffer.byteOffset, count);
  41454. }
  41455. else {
  41456. var offset = data.byteOffset + vertexBuffer.byteOffset;
  41457. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  41458. var result = new Float32Array(count);
  41459. var source = new Float32Array(data.buffer, offset, count);
  41460. result.set(source);
  41461. return result;
  41462. }
  41463. return new Float32Array(data.buffer, offset, count);
  41464. }
  41465. }
  41466. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  41467. return BABYLON.Tools.Slice(data);
  41468. }
  41469. return data;
  41470. };
  41471. /**
  41472. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  41473. * @param kind defines the data kind (Position, normal, etc...)
  41474. * @returns true if the vertex buffer with the specified kind is updatable
  41475. */
  41476. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  41477. var vb = this._vertexBuffers[kind];
  41478. if (!vb) {
  41479. return false;
  41480. }
  41481. return vb.isUpdatable();
  41482. };
  41483. /**
  41484. * Gets a specific vertex buffer
  41485. * @param kind defines the data kind (Position, normal, etc...)
  41486. * @returns a VertexBuffer
  41487. */
  41488. Geometry.prototype.getVertexBuffer = function (kind) {
  41489. if (!this.isReady()) {
  41490. return null;
  41491. }
  41492. return this._vertexBuffers[kind];
  41493. };
  41494. /**
  41495. * Returns all vertex buffers
  41496. * @return an object holding all vertex buffers indexed by kind
  41497. */
  41498. Geometry.prototype.getVertexBuffers = function () {
  41499. if (!this.isReady()) {
  41500. return null;
  41501. }
  41502. return this._vertexBuffers;
  41503. };
  41504. /**
  41505. * Gets a boolean indicating if specific vertex buffer is present
  41506. * @param kind defines the data kind (Position, normal, etc...)
  41507. * @returns true if data is present
  41508. */
  41509. Geometry.prototype.isVerticesDataPresent = function (kind) {
  41510. if (!this._vertexBuffers) {
  41511. if (this._delayInfo) {
  41512. return this._delayInfo.indexOf(kind) !== -1;
  41513. }
  41514. return false;
  41515. }
  41516. return this._vertexBuffers[kind] !== undefined;
  41517. };
  41518. /**
  41519. * Gets a list of all attached data kinds (Position, normal, etc...)
  41520. * @returns a list of string containing all kinds
  41521. */
  41522. Geometry.prototype.getVerticesDataKinds = function () {
  41523. var result = [];
  41524. var kind;
  41525. if (!this._vertexBuffers && this._delayInfo) {
  41526. for (kind in this._delayInfo) {
  41527. result.push(kind);
  41528. }
  41529. }
  41530. else {
  41531. for (kind in this._vertexBuffers) {
  41532. result.push(kind);
  41533. }
  41534. }
  41535. return result;
  41536. };
  41537. /**
  41538. * Update index buffer
  41539. * @param indices defines the indices to store in the index buffer
  41540. * @param offset defines the offset in the target buffer where to store the data
  41541. */
  41542. Geometry.prototype.updateIndices = function (indices, offset) {
  41543. if (!this._indexBuffer) {
  41544. return;
  41545. }
  41546. if (!this._indexBufferIsUpdatable) {
  41547. this.setIndices(indices, null, true);
  41548. }
  41549. else {
  41550. var needToUpdateSubMeshes = indices.length !== this._indices.length;
  41551. this._indices = indices;
  41552. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  41553. if (needToUpdateSubMeshes) {
  41554. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  41555. var mesh = _a[_i];
  41556. mesh._createGlobalSubMesh(true);
  41557. }
  41558. }
  41559. }
  41560. };
  41561. /**
  41562. * Creates a new index buffer
  41563. * @param indices defines the indices to store in the index buffer
  41564. * @param totalVertices defines the total number of vertices (could be null)
  41565. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  41566. */
  41567. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  41568. if (totalVertices === void 0) { totalVertices = null; }
  41569. if (updatable === void 0) { updatable = false; }
  41570. if (this._indexBuffer) {
  41571. this._engine._releaseBuffer(this._indexBuffer);
  41572. }
  41573. this._disposeVertexArrayObjects();
  41574. this._indices = indices;
  41575. this._indexBufferIsUpdatable = updatable;
  41576. if (this._meshes.length !== 0 && this._indices) {
  41577. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  41578. }
  41579. if (totalVertices != undefined) { // including null and undefined
  41580. this._totalVertices = totalVertices;
  41581. }
  41582. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  41583. var mesh = _a[_i];
  41584. mesh._createGlobalSubMesh(true);
  41585. }
  41586. this.notifyUpdate();
  41587. };
  41588. /**
  41589. * Return the total number of indices
  41590. * @returns the total number of indices
  41591. */
  41592. Geometry.prototype.getTotalIndices = function () {
  41593. if (!this.isReady()) {
  41594. return 0;
  41595. }
  41596. return this._indices.length;
  41597. };
  41598. /**
  41599. * Gets the index buffer array
  41600. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  41601. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  41602. * @returns the index buffer array
  41603. */
  41604. Geometry.prototype.getIndices = function (copyWhenShared, forceCopy) {
  41605. if (!this.isReady()) {
  41606. return null;
  41607. }
  41608. var orig = this._indices;
  41609. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  41610. return orig;
  41611. }
  41612. else {
  41613. var len = orig.length;
  41614. var copy = [];
  41615. for (var i = 0; i < len; i++) {
  41616. copy.push(orig[i]);
  41617. }
  41618. return copy;
  41619. }
  41620. };
  41621. /**
  41622. * Gets the index buffer
  41623. * @return the index buffer
  41624. */
  41625. Geometry.prototype.getIndexBuffer = function () {
  41626. if (!this.isReady()) {
  41627. return null;
  41628. }
  41629. return this._indexBuffer;
  41630. };
  41631. /** @hidden */
  41632. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  41633. if (effect === void 0) { effect = null; }
  41634. if (!effect || !this._vertexArrayObjects) {
  41635. return;
  41636. }
  41637. if (this._vertexArrayObjects[effect.key]) {
  41638. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  41639. delete this._vertexArrayObjects[effect.key];
  41640. }
  41641. };
  41642. /**
  41643. * Release the associated resources for a specific mesh
  41644. * @param mesh defines the source mesh
  41645. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  41646. */
  41647. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  41648. var meshes = this._meshes;
  41649. var index = meshes.indexOf(mesh);
  41650. if (index === -1) {
  41651. return;
  41652. }
  41653. meshes.splice(index, 1);
  41654. mesh._geometry = null;
  41655. if (meshes.length === 0 && shouldDispose) {
  41656. this.dispose();
  41657. }
  41658. };
  41659. /**
  41660. * Apply current geometry to a given mesh
  41661. * @param mesh defines the mesh to apply geometry to
  41662. */
  41663. Geometry.prototype.applyToMesh = function (mesh) {
  41664. if (mesh._geometry === this) {
  41665. return;
  41666. }
  41667. var previousGeometry = mesh._geometry;
  41668. if (previousGeometry) {
  41669. previousGeometry.releaseForMesh(mesh);
  41670. }
  41671. var meshes = this._meshes;
  41672. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  41673. mesh._geometry = this;
  41674. this._scene.pushGeometry(this);
  41675. meshes.push(mesh);
  41676. if (this.isReady()) {
  41677. this._applyToMesh(mesh);
  41678. }
  41679. else {
  41680. mesh._boundingInfo = this._boundingInfo;
  41681. }
  41682. };
  41683. Geometry.prototype._updateExtend = function (data) {
  41684. if (data === void 0) { data = null; }
  41685. if (!data) {
  41686. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  41687. }
  41688. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  41689. };
  41690. Geometry.prototype._applyToMesh = function (mesh) {
  41691. var numOfMeshes = this._meshes.length;
  41692. // vertexBuffers
  41693. for (var kind in this._vertexBuffers) {
  41694. if (numOfMeshes === 1) {
  41695. this._vertexBuffers[kind].create();
  41696. }
  41697. var buffer = this._vertexBuffers[kind].getBuffer();
  41698. if (buffer) {
  41699. buffer.references = numOfMeshes;
  41700. }
  41701. if (kind === BABYLON.VertexBuffer.PositionKind) {
  41702. if (!this._extend) {
  41703. this._updateExtend();
  41704. }
  41705. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  41706. mesh._createGlobalSubMesh(false);
  41707. //bounding info was just created again, world matrix should be applied again.
  41708. mesh._updateBoundingInfo();
  41709. }
  41710. }
  41711. // indexBuffer
  41712. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  41713. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  41714. }
  41715. if (this._indexBuffer) {
  41716. this._indexBuffer.references = numOfMeshes;
  41717. }
  41718. // morphTargets
  41719. mesh._syncGeometryWithMorphTargetManager();
  41720. // instances
  41721. mesh.synchronizeInstances();
  41722. };
  41723. Geometry.prototype.notifyUpdate = function (kind) {
  41724. if (this.onGeometryUpdated) {
  41725. this.onGeometryUpdated(this, kind);
  41726. }
  41727. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  41728. var mesh = _a[_i];
  41729. mesh._markSubMeshesAsAttributesDirty();
  41730. }
  41731. };
  41732. /**
  41733. * Load the geometry if it was flagged as delay loaded
  41734. * @param scene defines the hosting scene
  41735. * @param onLoaded defines a callback called when the geometry is loaded
  41736. */
  41737. Geometry.prototype.load = function (scene, onLoaded) {
  41738. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  41739. return;
  41740. }
  41741. if (this.isReady()) {
  41742. if (onLoaded) {
  41743. onLoaded();
  41744. }
  41745. return;
  41746. }
  41747. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  41748. this._queueLoad(scene, onLoaded);
  41749. };
  41750. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  41751. var _this = this;
  41752. if (!this.delayLoadingFile) {
  41753. return;
  41754. }
  41755. scene._addPendingData(this);
  41756. scene._loadFile(this.delayLoadingFile, function (data) {
  41757. if (!_this._delayLoadingFunction) {
  41758. return;
  41759. }
  41760. _this._delayLoadingFunction(JSON.parse(data), _this);
  41761. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  41762. _this._delayInfo = [];
  41763. scene._removePendingData(_this);
  41764. var meshes = _this._meshes;
  41765. var numOfMeshes = meshes.length;
  41766. for (var index = 0; index < numOfMeshes; index++) {
  41767. _this._applyToMesh(meshes[index]);
  41768. }
  41769. if (onLoaded) {
  41770. onLoaded();
  41771. }
  41772. }, undefined, true);
  41773. };
  41774. /**
  41775. * Invert the geometry to move from a right handed system to a left handed one.
  41776. */
  41777. Geometry.prototype.toLeftHanded = function () {
  41778. // Flip faces
  41779. var tIndices = this.getIndices(false);
  41780. if (tIndices != null && tIndices.length > 0) {
  41781. for (var i = 0; i < tIndices.length; i += 3) {
  41782. var tTemp = tIndices[i + 0];
  41783. tIndices[i + 0] = tIndices[i + 2];
  41784. tIndices[i + 2] = tTemp;
  41785. }
  41786. this.setIndices(tIndices);
  41787. }
  41788. // Negate position.z
  41789. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  41790. if (tPositions != null && tPositions.length > 0) {
  41791. for (var i = 0; i < tPositions.length; i += 3) {
  41792. tPositions[i + 2] = -tPositions[i + 2];
  41793. }
  41794. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  41795. }
  41796. // Negate normal.z
  41797. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  41798. if (tNormals != null && tNormals.length > 0) {
  41799. for (var i = 0; i < tNormals.length; i += 3) {
  41800. tNormals[i + 2] = -tNormals[i + 2];
  41801. }
  41802. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  41803. }
  41804. };
  41805. // Cache
  41806. /** @hidden */
  41807. Geometry.prototype._resetPointsArrayCache = function () {
  41808. this._positions = null;
  41809. };
  41810. /** @hidden */
  41811. Geometry.prototype._generatePointsArray = function () {
  41812. if (this._positions) {
  41813. return true;
  41814. }
  41815. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  41816. if (!data || data.length === 0) {
  41817. return false;
  41818. }
  41819. this._positions = [];
  41820. for (var index = 0; index < data.length; index += 3) {
  41821. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  41822. }
  41823. return true;
  41824. };
  41825. /**
  41826. * Gets a value indicating if the geometry is disposed
  41827. * @returns true if the geometry was disposed
  41828. */
  41829. Geometry.prototype.isDisposed = function () {
  41830. return this._isDisposed;
  41831. };
  41832. Geometry.prototype._disposeVertexArrayObjects = function () {
  41833. if (this._vertexArrayObjects) {
  41834. for (var kind in this._vertexArrayObjects) {
  41835. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  41836. }
  41837. this._vertexArrayObjects = {};
  41838. }
  41839. };
  41840. /**
  41841. * Free all associated resources
  41842. */
  41843. Geometry.prototype.dispose = function () {
  41844. var meshes = this._meshes;
  41845. var numOfMeshes = meshes.length;
  41846. var index;
  41847. for (index = 0; index < numOfMeshes; index++) {
  41848. this.releaseForMesh(meshes[index]);
  41849. }
  41850. this._meshes = [];
  41851. this._disposeVertexArrayObjects();
  41852. for (var kind in this._vertexBuffers) {
  41853. this._vertexBuffers[kind].dispose();
  41854. }
  41855. this._vertexBuffers = {};
  41856. this._totalVertices = 0;
  41857. if (this._indexBuffer) {
  41858. this._engine._releaseBuffer(this._indexBuffer);
  41859. }
  41860. this._indexBuffer = null;
  41861. this._indices = [];
  41862. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  41863. this.delayLoadingFile = null;
  41864. this._delayLoadingFunction = null;
  41865. this._delayInfo = [];
  41866. this._boundingInfo = null;
  41867. this._scene.removeGeometry(this);
  41868. this._isDisposed = true;
  41869. };
  41870. /**
  41871. * Clone the current geometry into a new geometry
  41872. * @param id defines the unique ID of the new geometry
  41873. * @returns a new geometry object
  41874. */
  41875. Geometry.prototype.copy = function (id) {
  41876. var vertexData = new BABYLON.VertexData();
  41877. vertexData.indices = [];
  41878. var indices = this.getIndices();
  41879. if (indices) {
  41880. for (var index = 0; index < indices.length; index++) {
  41881. vertexData.indices.push(indices[index]);
  41882. }
  41883. }
  41884. var updatable = false;
  41885. var stopChecking = false;
  41886. var kind;
  41887. for (kind in this._vertexBuffers) {
  41888. // using slice() to make a copy of the array and not just reference it
  41889. var data = this.getVerticesData(kind);
  41890. if (data) {
  41891. if (data instanceof Float32Array) {
  41892. vertexData.set(new Float32Array(data), kind);
  41893. }
  41894. else {
  41895. vertexData.set(data.slice(0), kind);
  41896. }
  41897. if (!stopChecking) {
  41898. var vb = this.getVertexBuffer(kind);
  41899. if (vb) {
  41900. updatable = vb.isUpdatable();
  41901. stopChecking = !updatable;
  41902. }
  41903. }
  41904. }
  41905. }
  41906. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  41907. geometry.delayLoadState = this.delayLoadState;
  41908. geometry.delayLoadingFile = this.delayLoadingFile;
  41909. geometry._delayLoadingFunction = this._delayLoadingFunction;
  41910. for (kind in this._delayInfo) {
  41911. geometry._delayInfo = geometry._delayInfo || [];
  41912. geometry._delayInfo.push(kind);
  41913. }
  41914. // Bounding info
  41915. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  41916. return geometry;
  41917. };
  41918. /**
  41919. * Serialize the current geometry info (and not the vertices data) into a JSON object
  41920. * @return a JSON representation of the current geometry data (without the vertices data)
  41921. */
  41922. Geometry.prototype.serialize = function () {
  41923. var serializationObject = {};
  41924. serializationObject.id = this.id;
  41925. serializationObject.updatable = this._updatable;
  41926. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  41927. serializationObject.tags = BABYLON.Tags.GetTags(this);
  41928. }
  41929. return serializationObject;
  41930. };
  41931. Geometry.prototype.toNumberArray = function (origin) {
  41932. if (Array.isArray(origin)) {
  41933. return origin;
  41934. }
  41935. else {
  41936. return Array.prototype.slice.call(origin);
  41937. }
  41938. };
  41939. /**
  41940. * Serialize all vertices data into a JSON oject
  41941. * @returns a JSON representation of the current geometry data
  41942. */
  41943. Geometry.prototype.serializeVerticeData = function () {
  41944. var serializationObject = this.serialize();
  41945. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  41946. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  41947. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  41948. serializationObject.positions._updatable = true;
  41949. }
  41950. }
  41951. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  41952. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  41953. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  41954. serializationObject.normals._updatable = true;
  41955. }
  41956. }
  41957. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  41958. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  41959. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  41960. serializationObject.tangets._updatable = true;
  41961. }
  41962. }
  41963. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  41964. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  41965. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  41966. serializationObject.uvs._updatable = true;
  41967. }
  41968. }
  41969. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  41970. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  41971. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  41972. serializationObject.uv2s._updatable = true;
  41973. }
  41974. }
  41975. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  41976. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  41977. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  41978. serializationObject.uv3s._updatable = true;
  41979. }
  41980. }
  41981. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  41982. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  41983. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  41984. serializationObject.uv4s._updatable = true;
  41985. }
  41986. }
  41987. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  41988. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  41989. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  41990. serializationObject.uv5s._updatable = true;
  41991. }
  41992. }
  41993. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  41994. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  41995. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  41996. serializationObject.uv6s._updatable = true;
  41997. }
  41998. }
  41999. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  42000. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  42001. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  42002. serializationObject.colors._updatable = true;
  42003. }
  42004. }
  42005. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  42006. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  42007. serializationObject.matricesIndices._isExpanded = true;
  42008. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  42009. serializationObject.matricesIndices._updatable = true;
  42010. }
  42011. }
  42012. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  42013. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  42014. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  42015. serializationObject.matricesWeights._updatable = true;
  42016. }
  42017. }
  42018. serializationObject.indices = this.toNumberArray(this.getIndices());
  42019. return serializationObject;
  42020. };
  42021. // Statics
  42022. /**
  42023. * Extracts a clone of a mesh geometry
  42024. * @param mesh defines the source mesh
  42025. * @param id defines the unique ID of the new geometry object
  42026. * @returns the new geometry object
  42027. */
  42028. Geometry.ExtractFromMesh = function (mesh, id) {
  42029. var geometry = mesh._geometry;
  42030. if (!geometry) {
  42031. return null;
  42032. }
  42033. return geometry.copy(id);
  42034. };
  42035. /**
  42036. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  42037. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  42038. * Be aware Math.random() could cause collisions, but:
  42039. * "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"
  42040. * @returns a string containing a new GUID
  42041. */
  42042. Geometry.RandomId = function () {
  42043. return BABYLON.Tools.RandomId();
  42044. };
  42045. /** @hidden */
  42046. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  42047. var scene = mesh.getScene();
  42048. // Geometry
  42049. var geometryId = parsedGeometry.geometryId;
  42050. if (geometryId) {
  42051. var geometry = scene.getGeometryByID(geometryId);
  42052. if (geometry) {
  42053. geometry.applyToMesh(mesh);
  42054. }
  42055. }
  42056. else if (parsedGeometry instanceof ArrayBuffer) {
  42057. var binaryInfo = mesh._binaryInfo;
  42058. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  42059. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  42060. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  42061. }
  42062. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  42063. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  42064. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  42065. }
  42066. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  42067. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  42068. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  42069. }
  42070. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  42071. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  42072. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  42073. }
  42074. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  42075. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  42076. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  42077. }
  42078. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  42079. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  42080. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  42081. }
  42082. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  42083. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  42084. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  42085. }
  42086. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  42087. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  42088. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  42089. }
  42090. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  42091. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  42092. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  42093. }
  42094. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  42095. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  42096. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  42097. }
  42098. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  42099. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  42100. var floatIndices = [];
  42101. for (var i = 0; i < matricesIndicesData.length; i++) {
  42102. var index = matricesIndicesData[i];
  42103. floatIndices.push(index & 0x000000FF);
  42104. floatIndices.push((index & 0x0000FF00) >> 8);
  42105. floatIndices.push((index & 0x00FF0000) >> 16);
  42106. floatIndices.push(index >> 24);
  42107. }
  42108. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  42109. }
  42110. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  42111. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  42112. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  42113. }
  42114. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  42115. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  42116. mesh.setIndices(indicesData, null);
  42117. }
  42118. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  42119. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  42120. mesh.subMeshes = [];
  42121. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  42122. var materialIndex = subMeshesData[(i * 5) + 0];
  42123. var verticesStart = subMeshesData[(i * 5) + 1];
  42124. var verticesCount = subMeshesData[(i * 5) + 2];
  42125. var indexStart = subMeshesData[(i * 5) + 3];
  42126. var indexCount = subMeshesData[(i * 5) + 4];
  42127. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  42128. }
  42129. }
  42130. }
  42131. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  42132. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  42133. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  42134. if (parsedGeometry.tangents) {
  42135. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  42136. }
  42137. if (parsedGeometry.uvs) {
  42138. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  42139. }
  42140. if (parsedGeometry.uvs2) {
  42141. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  42142. }
  42143. if (parsedGeometry.uvs3) {
  42144. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  42145. }
  42146. if (parsedGeometry.uvs4) {
  42147. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  42148. }
  42149. if (parsedGeometry.uvs5) {
  42150. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  42151. }
  42152. if (parsedGeometry.uvs6) {
  42153. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  42154. }
  42155. if (parsedGeometry.colors) {
  42156. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  42157. }
  42158. if (parsedGeometry.matricesIndices) {
  42159. if (!parsedGeometry.matricesIndices._isExpanded) {
  42160. var floatIndices = [];
  42161. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  42162. var matricesIndex = parsedGeometry.matricesIndices[i];
  42163. floatIndices.push(matricesIndex & 0x000000FF);
  42164. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  42165. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  42166. floatIndices.push(matricesIndex >> 24);
  42167. }
  42168. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  42169. }
  42170. else {
  42171. delete parsedGeometry.matricesIndices._isExpanded;
  42172. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  42173. }
  42174. }
  42175. if (parsedGeometry.matricesIndicesExtra) {
  42176. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  42177. var floatIndices = [];
  42178. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  42179. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  42180. floatIndices.push(matricesIndex & 0x000000FF);
  42181. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  42182. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  42183. floatIndices.push(matricesIndex >> 24);
  42184. }
  42185. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  42186. }
  42187. else {
  42188. delete parsedGeometry.matricesIndices._isExpanded;
  42189. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  42190. }
  42191. }
  42192. if (parsedGeometry.matricesWeights) {
  42193. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  42194. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  42195. }
  42196. if (parsedGeometry.matricesWeightsExtra) {
  42197. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  42198. }
  42199. mesh.setIndices(parsedGeometry.indices, null);
  42200. }
  42201. // SubMeshes
  42202. if (parsedGeometry.subMeshes) {
  42203. mesh.subMeshes = [];
  42204. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  42205. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  42206. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  42207. }
  42208. }
  42209. // Flat shading
  42210. if (mesh._shouldGenerateFlatShading) {
  42211. mesh.convertToFlatShadedMesh();
  42212. delete mesh._shouldGenerateFlatShading;
  42213. }
  42214. // Update
  42215. mesh.computeWorldMatrix(true);
  42216. scene.onMeshImportedObservable.notifyObservers(mesh);
  42217. };
  42218. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  42219. var epsilon = 1e-3;
  42220. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  42221. return;
  42222. }
  42223. var noInfluenceBoneIndex = 0.0;
  42224. if (parsedGeometry.skeletonId > -1) {
  42225. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  42226. if (!skeleton) {
  42227. return;
  42228. }
  42229. noInfluenceBoneIndex = skeleton.bones.length;
  42230. }
  42231. else {
  42232. return;
  42233. }
  42234. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  42235. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  42236. var matricesWeights = parsedGeometry.matricesWeights;
  42237. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  42238. var influencers = parsedGeometry.numBoneInfluencer;
  42239. var size = matricesWeights.length;
  42240. for (var i = 0; i < size; i += 4) {
  42241. var weight = 0.0;
  42242. var firstZeroWeight = -1;
  42243. for (var j = 0; j < 4; j++) {
  42244. var w = matricesWeights[i + j];
  42245. weight += w;
  42246. if (w < epsilon && firstZeroWeight < 0) {
  42247. firstZeroWeight = j;
  42248. }
  42249. }
  42250. if (matricesWeightsExtra) {
  42251. for (var j = 0; j < 4; j++) {
  42252. var w = matricesWeightsExtra[i + j];
  42253. weight += w;
  42254. if (w < epsilon && firstZeroWeight < 0) {
  42255. firstZeroWeight = j + 4;
  42256. }
  42257. }
  42258. }
  42259. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  42260. firstZeroWeight = influencers - 1;
  42261. }
  42262. if (weight > epsilon) {
  42263. var mweight = 1.0 / weight;
  42264. for (var j = 0; j < 4; j++) {
  42265. matricesWeights[i + j] *= mweight;
  42266. }
  42267. if (matricesWeightsExtra) {
  42268. for (var j = 0; j < 4; j++) {
  42269. matricesWeightsExtra[i + j] *= mweight;
  42270. }
  42271. }
  42272. }
  42273. else {
  42274. if (firstZeroWeight >= 4) {
  42275. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  42276. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  42277. }
  42278. else {
  42279. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  42280. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  42281. }
  42282. }
  42283. }
  42284. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  42285. if (parsedGeometry.matricesWeightsExtra) {
  42286. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  42287. }
  42288. };
  42289. /**
  42290. * Create a new geometry from persisted data (Using .babylon file format)
  42291. * @param parsedVertexData defines the persisted data
  42292. * @param scene defines the hosting scene
  42293. * @param rootUrl defines the root url to use to load assets (like delayed data)
  42294. * @returns the new geometry object
  42295. */
  42296. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  42297. if (scene.getGeometryByID(parsedVertexData.id)) {
  42298. return null; // null since geometry could be something else than a box...
  42299. }
  42300. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  42301. if (BABYLON.Tags) {
  42302. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  42303. }
  42304. if (parsedVertexData.delayLoadingFile) {
  42305. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  42306. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  42307. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  42308. geometry._delayInfo = [];
  42309. if (parsedVertexData.hasUVs) {
  42310. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  42311. }
  42312. if (parsedVertexData.hasUVs2) {
  42313. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  42314. }
  42315. if (parsedVertexData.hasUVs3) {
  42316. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  42317. }
  42318. if (parsedVertexData.hasUVs4) {
  42319. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  42320. }
  42321. if (parsedVertexData.hasUVs5) {
  42322. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  42323. }
  42324. if (parsedVertexData.hasUVs6) {
  42325. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  42326. }
  42327. if (parsedVertexData.hasColors) {
  42328. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  42329. }
  42330. if (parsedVertexData.hasMatricesIndices) {
  42331. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  42332. }
  42333. if (parsedVertexData.hasMatricesWeights) {
  42334. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  42335. }
  42336. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  42337. }
  42338. else {
  42339. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  42340. }
  42341. scene.pushGeometry(geometry, true);
  42342. return geometry;
  42343. };
  42344. return Geometry;
  42345. }());
  42346. BABYLON.Geometry = Geometry;
  42347. // Primitives
  42348. /// Abstract class
  42349. /**
  42350. * Abstract class used to provide common services for all typed geometries
  42351. * @hidden
  42352. */
  42353. var _PrimitiveGeometry = /** @class */ (function (_super) {
  42354. __extends(_PrimitiveGeometry, _super);
  42355. /**
  42356. * Creates a new typed geometry
  42357. * @param id defines the unique ID of the geometry
  42358. * @param scene defines the hosting scene
  42359. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  42360. * @param mesh defines the hosting mesh (can be null)
  42361. */
  42362. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  42363. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  42364. if (mesh === void 0) { mesh = null; }
  42365. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  42366. _this._canBeRegenerated = _canBeRegenerated;
  42367. _this._beingRegenerated = true;
  42368. _this.regenerate();
  42369. _this._beingRegenerated = false;
  42370. return _this;
  42371. }
  42372. /**
  42373. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  42374. * @returns true if the geometry can be regenerated
  42375. */
  42376. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  42377. return this._canBeRegenerated;
  42378. };
  42379. /**
  42380. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  42381. */
  42382. _PrimitiveGeometry.prototype.regenerate = function () {
  42383. if (!this._canBeRegenerated) {
  42384. return;
  42385. }
  42386. this._beingRegenerated = true;
  42387. this.setAllVerticesData(this._regenerateVertexData(), false);
  42388. this._beingRegenerated = false;
  42389. };
  42390. /**
  42391. * Clone the geometry
  42392. * @param id defines the unique ID of the new geometry
  42393. * @returns the new geometry
  42394. */
  42395. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  42396. return _super.prototype.copy.call(this, id);
  42397. };
  42398. // overrides
  42399. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  42400. if (!this._beingRegenerated) {
  42401. return;
  42402. }
  42403. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  42404. };
  42405. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  42406. if (!this._beingRegenerated) {
  42407. return;
  42408. }
  42409. _super.prototype.setVerticesData.call(this, kind, data, false);
  42410. };
  42411. // to override
  42412. /** @hidden */
  42413. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  42414. throw new Error("Abstract method");
  42415. };
  42416. _PrimitiveGeometry.prototype.copy = function (id) {
  42417. throw new Error("Must be overriden in sub-classes.");
  42418. };
  42419. _PrimitiveGeometry.prototype.serialize = function () {
  42420. var serializationObject = _super.prototype.serialize.call(this);
  42421. serializationObject.canBeRegenerated = this.canBeRegenerated();
  42422. return serializationObject;
  42423. };
  42424. return _PrimitiveGeometry;
  42425. }(Geometry));
  42426. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  42427. /**
  42428. * Creates a ribbon geometry
  42429. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  42430. */
  42431. var RibbonGeometry = /** @class */ (function (_super) {
  42432. __extends(RibbonGeometry, _super);
  42433. /**
  42434. * Creates a ribbon geometry
  42435. * @param id defines the unique ID of the geometry
  42436. * @param scene defines the hosting scene
  42437. * @param pathArray defines the array of paths to use
  42438. * @param closeArray defines if the last path and the first path must be joined
  42439. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  42440. * @param offset defines the offset between points
  42441. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  42442. * @param mesh defines the hosting mesh (can be null)
  42443. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  42444. */
  42445. function RibbonGeometry(id, scene,
  42446. /**
  42447. * Defines the array of paths to use
  42448. */
  42449. pathArray,
  42450. /**
  42451. * Defines if the last and first points of each path in your pathArray must be joined
  42452. */
  42453. closeArray,
  42454. /**
  42455. * Defines if the last and first points of each path in your pathArray must be joined
  42456. */
  42457. closePath,
  42458. /**
  42459. * Defines the offset between points
  42460. */
  42461. offset, canBeRegenerated, mesh,
  42462. /**
  42463. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  42464. */
  42465. side) {
  42466. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  42467. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  42468. _this.pathArray = pathArray;
  42469. _this.closeArray = closeArray;
  42470. _this.closePath = closePath;
  42471. _this.offset = offset;
  42472. _this.side = side;
  42473. return _this;
  42474. }
  42475. /** @hidden */
  42476. RibbonGeometry.prototype._regenerateVertexData = function () {
  42477. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  42478. };
  42479. RibbonGeometry.prototype.copy = function (id) {
  42480. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  42481. };
  42482. return RibbonGeometry;
  42483. }(_PrimitiveGeometry));
  42484. BABYLON.RibbonGeometry = RibbonGeometry;
  42485. /**
  42486. * Creates a box geometry
  42487. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  42488. */
  42489. var BoxGeometry = /** @class */ (function (_super) {
  42490. __extends(BoxGeometry, _super);
  42491. /**
  42492. * Creates a box geometry
  42493. * @param id defines the unique ID of the geometry
  42494. * @param scene defines the hosting scene
  42495. * @param size defines the zise of the box (width, height and depth are the same)
  42496. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  42497. * @param mesh defines the hosting mesh (can be null)
  42498. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  42499. */
  42500. function BoxGeometry(id, scene,
  42501. /**
  42502. * Defines the zise of the box (width, height and depth are the same)
  42503. */
  42504. size, canBeRegenerated, mesh,
  42505. /**
  42506. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  42507. */
  42508. side) {
  42509. if (mesh === void 0) { mesh = null; }
  42510. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  42511. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  42512. _this.size = size;
  42513. _this.side = side;
  42514. return _this;
  42515. }
  42516. /** @hidden */
  42517. BoxGeometry.prototype._regenerateVertexData = function () {
  42518. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  42519. };
  42520. BoxGeometry.prototype.copy = function (id) {
  42521. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  42522. };
  42523. BoxGeometry.prototype.serialize = function () {
  42524. var serializationObject = _super.prototype.serialize.call(this);
  42525. serializationObject.size = this.size;
  42526. return serializationObject;
  42527. };
  42528. BoxGeometry.Parse = function (parsedBox, scene) {
  42529. if (scene.getGeometryByID(parsedBox.id)) {
  42530. return null; // null since geometry could be something else than a box...
  42531. }
  42532. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  42533. if (BABYLON.Tags) {
  42534. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  42535. }
  42536. scene.pushGeometry(box, true);
  42537. return box;
  42538. };
  42539. return BoxGeometry;
  42540. }(_PrimitiveGeometry));
  42541. BABYLON.BoxGeometry = BoxGeometry;
  42542. /**
  42543. * Creates a sphere geometry
  42544. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  42545. */
  42546. var SphereGeometry = /** @class */ (function (_super) {
  42547. __extends(SphereGeometry, _super);
  42548. /**
  42549. * Create a new sphere geometry
  42550. * @param id defines the unique ID of the geometry
  42551. * @param scene defines the hosting scene
  42552. * @param segments defines the number of segments to use to create the sphere
  42553. * @param diameter defines the diameter of the sphere
  42554. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  42555. * @param mesh defines the hosting mesh (can be null)
  42556. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  42557. */
  42558. function SphereGeometry(id, scene,
  42559. /**
  42560. * Defines the number of segments to use to create the sphere
  42561. */
  42562. segments,
  42563. /**
  42564. * Defines the diameter of the sphere
  42565. */
  42566. diameter, canBeRegenerated, mesh,
  42567. /**
  42568. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  42569. */
  42570. side) {
  42571. if (mesh === void 0) { mesh = null; }
  42572. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  42573. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  42574. _this.segments = segments;
  42575. _this.diameter = diameter;
  42576. _this.side = side;
  42577. return _this;
  42578. }
  42579. /** @hidden */
  42580. SphereGeometry.prototype._regenerateVertexData = function () {
  42581. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  42582. };
  42583. SphereGeometry.prototype.copy = function (id) {
  42584. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  42585. };
  42586. SphereGeometry.prototype.serialize = function () {
  42587. var serializationObject = _super.prototype.serialize.call(this);
  42588. serializationObject.segments = this.segments;
  42589. serializationObject.diameter = this.diameter;
  42590. return serializationObject;
  42591. };
  42592. SphereGeometry.Parse = function (parsedSphere, scene) {
  42593. if (scene.getGeometryByID(parsedSphere.id)) {
  42594. return null; // null since geometry could be something else than a sphere...
  42595. }
  42596. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  42597. if (BABYLON.Tags) {
  42598. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  42599. }
  42600. scene.pushGeometry(sphere, true);
  42601. return sphere;
  42602. };
  42603. return SphereGeometry;
  42604. }(_PrimitiveGeometry));
  42605. BABYLON.SphereGeometry = SphereGeometry;
  42606. /**
  42607. * Creates a disc geometry
  42608. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  42609. */
  42610. var DiscGeometry = /** @class */ (function (_super) {
  42611. __extends(DiscGeometry, _super);
  42612. /**
  42613. * Creates a new disc geometry
  42614. * @param id defines the unique ID of the geometry
  42615. * @param scene defines the hosting scene
  42616. * @param radius defines the radius of the disc
  42617. * @param tessellation defines the tesselation factor to apply to the disc
  42618. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  42619. * @param mesh defines the hosting mesh (can be null)
  42620. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  42621. */
  42622. function DiscGeometry(id, scene,
  42623. /**
  42624. * Defines the radius of the disc
  42625. */
  42626. radius,
  42627. /**
  42628. * Defines the tesselation factor to apply to the disc
  42629. */
  42630. tessellation, canBeRegenerated, mesh,
  42631. /**
  42632. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  42633. */
  42634. side) {
  42635. if (mesh === void 0) { mesh = null; }
  42636. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  42637. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  42638. _this.radius = radius;
  42639. _this.tessellation = tessellation;
  42640. _this.side = side;
  42641. return _this;
  42642. }
  42643. /** @hidden */
  42644. DiscGeometry.prototype._regenerateVertexData = function () {
  42645. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  42646. };
  42647. DiscGeometry.prototype.copy = function (id) {
  42648. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  42649. };
  42650. return DiscGeometry;
  42651. }(_PrimitiveGeometry));
  42652. BABYLON.DiscGeometry = DiscGeometry;
  42653. /**
  42654. * Creates a new cylinder geometry
  42655. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  42656. */
  42657. var CylinderGeometry = /** @class */ (function (_super) {
  42658. __extends(CylinderGeometry, _super);
  42659. /**
  42660. * Creates a new cylinder geometry
  42661. * @param id defines the unique ID of the geometry
  42662. * @param scene defines the hosting scene
  42663. * @param height defines the height of the cylinder
  42664. * @param diameterTop defines the diameter of the cylinder's top cap
  42665. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  42666. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  42667. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  42668. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  42669. * @param mesh defines the hosting mesh (can be null)
  42670. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  42671. */
  42672. function CylinderGeometry(id, scene,
  42673. /**
  42674. * Defines the height of the cylinder
  42675. */
  42676. height,
  42677. /**
  42678. * Defines the diameter of the cylinder's top cap
  42679. */
  42680. diameterTop,
  42681. /**
  42682. * Defines the diameter of the cylinder's bottom cap
  42683. */
  42684. diameterBottom,
  42685. /**
  42686. * Defines the tessellation factor to apply to the cylinder
  42687. */
  42688. tessellation,
  42689. /**
  42690. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  42691. */
  42692. subdivisions, canBeRegenerated, mesh,
  42693. /**
  42694. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  42695. */
  42696. side) {
  42697. if (subdivisions === void 0) { subdivisions = 1; }
  42698. if (mesh === void 0) { mesh = null; }
  42699. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  42700. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  42701. _this.height = height;
  42702. _this.diameterTop = diameterTop;
  42703. _this.diameterBottom = diameterBottom;
  42704. _this.tessellation = tessellation;
  42705. _this.subdivisions = subdivisions;
  42706. _this.side = side;
  42707. return _this;
  42708. }
  42709. /** @hidden */
  42710. CylinderGeometry.prototype._regenerateVertexData = function () {
  42711. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  42712. };
  42713. CylinderGeometry.prototype.copy = function (id) {
  42714. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  42715. };
  42716. CylinderGeometry.prototype.serialize = function () {
  42717. var serializationObject = _super.prototype.serialize.call(this);
  42718. serializationObject.height = this.height;
  42719. serializationObject.diameterTop = this.diameterTop;
  42720. serializationObject.diameterBottom = this.diameterBottom;
  42721. serializationObject.tessellation = this.tessellation;
  42722. return serializationObject;
  42723. };
  42724. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  42725. if (scene.getGeometryByID(parsedCylinder.id)) {
  42726. return null; // null since geometry could be something else than a cylinder...
  42727. }
  42728. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  42729. if (BABYLON.Tags) {
  42730. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  42731. }
  42732. scene.pushGeometry(cylinder, true);
  42733. return cylinder;
  42734. };
  42735. return CylinderGeometry;
  42736. }(_PrimitiveGeometry));
  42737. BABYLON.CylinderGeometry = CylinderGeometry;
  42738. /**
  42739. * Creates a new torus geometry
  42740. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  42741. */
  42742. var TorusGeometry = /** @class */ (function (_super) {
  42743. __extends(TorusGeometry, _super);
  42744. /**
  42745. * Creates a new torus geometry
  42746. * @param id defines the unique ID of the geometry
  42747. * @param scene defines the hosting scene
  42748. * @param diameter defines the diameter of the torus
  42749. * @param thickness defines the thickness of the torus (ie. internal diameter)
  42750. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  42751. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  42752. * @param mesh defines the hosting mesh (can be null)
  42753. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  42754. */
  42755. function TorusGeometry(id, scene,
  42756. /**
  42757. * Defines the diameter of the torus
  42758. */
  42759. diameter,
  42760. /**
  42761. * Defines the thickness of the torus (ie. internal diameter)
  42762. */
  42763. thickness,
  42764. /**
  42765. * Defines the tesselation factor to apply to the torus
  42766. */
  42767. tessellation, canBeRegenerated, mesh,
  42768. /**
  42769. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  42770. */
  42771. side) {
  42772. if (mesh === void 0) { mesh = null; }
  42773. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  42774. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  42775. _this.diameter = diameter;
  42776. _this.thickness = thickness;
  42777. _this.tessellation = tessellation;
  42778. _this.side = side;
  42779. return _this;
  42780. }
  42781. /** @hidden */
  42782. TorusGeometry.prototype._regenerateVertexData = function () {
  42783. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  42784. };
  42785. TorusGeometry.prototype.copy = function (id) {
  42786. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  42787. };
  42788. TorusGeometry.prototype.serialize = function () {
  42789. var serializationObject = _super.prototype.serialize.call(this);
  42790. serializationObject.diameter = this.diameter;
  42791. serializationObject.thickness = this.thickness;
  42792. serializationObject.tessellation = this.tessellation;
  42793. return serializationObject;
  42794. };
  42795. TorusGeometry.Parse = function (parsedTorus, scene) {
  42796. if (scene.getGeometryByID(parsedTorus.id)) {
  42797. return null; // null since geometry could be something else than a torus...
  42798. }
  42799. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  42800. if (BABYLON.Tags) {
  42801. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  42802. }
  42803. scene.pushGeometry(torus, true);
  42804. return torus;
  42805. };
  42806. return TorusGeometry;
  42807. }(_PrimitiveGeometry));
  42808. BABYLON.TorusGeometry = TorusGeometry;
  42809. /**
  42810. * Creates a new ground geometry
  42811. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  42812. */
  42813. var GroundGeometry = /** @class */ (function (_super) {
  42814. __extends(GroundGeometry, _super);
  42815. /**
  42816. * Creates a new ground geometry
  42817. * @param id defines the unique ID of the geometry
  42818. * @param scene defines the hosting scene
  42819. * @param width defines the width of the ground
  42820. * @param height defines the height of the ground
  42821. * @param subdivisions defines the subdivisions to apply to the ground
  42822. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  42823. * @param mesh defines the hosting mesh (can be null)
  42824. */
  42825. function GroundGeometry(id, scene,
  42826. /**
  42827. * Defines the width of the ground
  42828. */
  42829. width,
  42830. /**
  42831. * Defines the height of the ground
  42832. */
  42833. height,
  42834. /**
  42835. * Defines the subdivisions to apply to the ground
  42836. */
  42837. subdivisions, canBeRegenerated, mesh) {
  42838. if (mesh === void 0) { mesh = null; }
  42839. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  42840. _this.width = width;
  42841. _this.height = height;
  42842. _this.subdivisions = subdivisions;
  42843. return _this;
  42844. }
  42845. /** @hidden */
  42846. GroundGeometry.prototype._regenerateVertexData = function () {
  42847. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  42848. };
  42849. GroundGeometry.prototype.copy = function (id) {
  42850. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  42851. };
  42852. GroundGeometry.prototype.serialize = function () {
  42853. var serializationObject = _super.prototype.serialize.call(this);
  42854. serializationObject.width = this.width;
  42855. serializationObject.height = this.height;
  42856. serializationObject.subdivisions = this.subdivisions;
  42857. return serializationObject;
  42858. };
  42859. GroundGeometry.Parse = function (parsedGround, scene) {
  42860. if (scene.getGeometryByID(parsedGround.id)) {
  42861. return null; // null since geometry could be something else than a ground...
  42862. }
  42863. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  42864. if (BABYLON.Tags) {
  42865. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  42866. }
  42867. scene.pushGeometry(ground, true);
  42868. return ground;
  42869. };
  42870. return GroundGeometry;
  42871. }(_PrimitiveGeometry));
  42872. BABYLON.GroundGeometry = GroundGeometry;
  42873. /**
  42874. * Creates a tiled ground geometry
  42875. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  42876. */
  42877. var TiledGroundGeometry = /** @class */ (function (_super) {
  42878. __extends(TiledGroundGeometry, _super);
  42879. /**
  42880. * Creates a tiled ground geometry
  42881. * @param id defines the unique ID of the geometry
  42882. * @param scene defines the hosting scene
  42883. * @param xmin defines the minimum value on X axis
  42884. * @param zmin defines the minimum value on Z axis
  42885. * @param xmax defines the maximum value on X axis
  42886. * @param zmax defines the maximum value on Z axis
  42887. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  42888. * @param precision defines the precision to use when computing the tiles
  42889. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  42890. * @param mesh defines the hosting mesh (can be null)
  42891. */
  42892. function TiledGroundGeometry(id, scene,
  42893. /**
  42894. * Defines the minimum value on X axis
  42895. */
  42896. xmin,
  42897. /**
  42898. * Defines the minimum value on Z axis
  42899. */
  42900. zmin,
  42901. /**
  42902. * Defines the maximum value on X axis
  42903. */
  42904. xmax,
  42905. /**
  42906. * Defines the maximum value on Z axis
  42907. */
  42908. zmax,
  42909. /**
  42910. * Defines the subdivisions to apply to the ground
  42911. */
  42912. subdivisions,
  42913. /**
  42914. * Defines the precision to use when computing the tiles
  42915. */
  42916. precision, canBeRegenerated, mesh) {
  42917. if (mesh === void 0) { mesh = null; }
  42918. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  42919. _this.xmin = xmin;
  42920. _this.zmin = zmin;
  42921. _this.xmax = xmax;
  42922. _this.zmax = zmax;
  42923. _this.subdivisions = subdivisions;
  42924. _this.precision = precision;
  42925. return _this;
  42926. }
  42927. /** @hidden */
  42928. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  42929. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  42930. };
  42931. TiledGroundGeometry.prototype.copy = function (id) {
  42932. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  42933. };
  42934. return TiledGroundGeometry;
  42935. }(_PrimitiveGeometry));
  42936. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  42937. /**
  42938. * Creates a plane geometry
  42939. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  42940. */
  42941. var PlaneGeometry = /** @class */ (function (_super) {
  42942. __extends(PlaneGeometry, _super);
  42943. /**
  42944. * Creates a plane geometry
  42945. * @param id defines the unique ID of the geometry
  42946. * @param scene defines the hosting scene
  42947. * @param size defines the size of the plane (width === height)
  42948. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  42949. * @param mesh defines the hosting mesh (can be null)
  42950. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  42951. */
  42952. function PlaneGeometry(id, scene,
  42953. /**
  42954. * Defines the size of the plane (width === height)
  42955. */
  42956. size, canBeRegenerated, mesh,
  42957. /**
  42958. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  42959. */
  42960. side) {
  42961. if (mesh === void 0) { mesh = null; }
  42962. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  42963. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  42964. _this.size = size;
  42965. _this.side = side;
  42966. return _this;
  42967. }
  42968. /** @hidden */
  42969. PlaneGeometry.prototype._regenerateVertexData = function () {
  42970. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  42971. };
  42972. PlaneGeometry.prototype.copy = function (id) {
  42973. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  42974. };
  42975. PlaneGeometry.prototype.serialize = function () {
  42976. var serializationObject = _super.prototype.serialize.call(this);
  42977. serializationObject.size = this.size;
  42978. return serializationObject;
  42979. };
  42980. PlaneGeometry.Parse = function (parsedPlane, scene) {
  42981. if (scene.getGeometryByID(parsedPlane.id)) {
  42982. return null; // null since geometry could be something else than a ground...
  42983. }
  42984. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  42985. if (BABYLON.Tags) {
  42986. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  42987. }
  42988. scene.pushGeometry(plane, true);
  42989. return plane;
  42990. };
  42991. return PlaneGeometry;
  42992. }(_PrimitiveGeometry));
  42993. BABYLON.PlaneGeometry = PlaneGeometry;
  42994. /**
  42995. * Creates a torus knot geometry
  42996. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  42997. */
  42998. var TorusKnotGeometry = /** @class */ (function (_super) {
  42999. __extends(TorusKnotGeometry, _super);
  43000. /**
  43001. * Creates a torus knot geometry
  43002. * @param id defines the unique ID of the geometry
  43003. * @param scene defines the hosting scene
  43004. * @param radius defines the radius of the torus knot
  43005. * @param tube defines the thickness of the torus knot tube
  43006. * @param radialSegments defines the number of radial segments
  43007. * @param tubularSegments defines the number of tubular segments
  43008. * @param p defines the first number of windings
  43009. * @param q defines the second number of windings
  43010. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  43011. * @param mesh defines the hosting mesh (can be null)
  43012. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  43013. */
  43014. function TorusKnotGeometry(id, scene,
  43015. /**
  43016. * Defines the radius of the torus knot
  43017. */
  43018. radius,
  43019. /**
  43020. * Defines the thickness of the torus knot tube
  43021. */
  43022. tube,
  43023. /**
  43024. * Defines the number of radial segments
  43025. */
  43026. radialSegments,
  43027. /**
  43028. * Defines the number of tubular segments
  43029. */
  43030. tubularSegments,
  43031. /**
  43032. * Defines the first number of windings
  43033. */
  43034. p,
  43035. /**
  43036. * Defines the second number of windings
  43037. */
  43038. q, canBeRegenerated, mesh,
  43039. /**
  43040. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  43041. */
  43042. side) {
  43043. if (mesh === void 0) { mesh = null; }
  43044. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  43045. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  43046. _this.radius = radius;
  43047. _this.tube = tube;
  43048. _this.radialSegments = radialSegments;
  43049. _this.tubularSegments = tubularSegments;
  43050. _this.p = p;
  43051. _this.q = q;
  43052. _this.side = side;
  43053. return _this;
  43054. }
  43055. /** @hidden */
  43056. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  43057. 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 });
  43058. };
  43059. TorusKnotGeometry.prototype.copy = function (id) {
  43060. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  43061. };
  43062. TorusKnotGeometry.prototype.serialize = function () {
  43063. var serializationObject = _super.prototype.serialize.call(this);
  43064. serializationObject.radius = this.radius;
  43065. serializationObject.tube = this.tube;
  43066. serializationObject.radialSegments = this.radialSegments;
  43067. serializationObject.tubularSegments = this.tubularSegments;
  43068. serializationObject.p = this.p;
  43069. serializationObject.q = this.q;
  43070. return serializationObject;
  43071. };
  43072. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  43073. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  43074. return null; // null since geometry could be something else than a ground...
  43075. }
  43076. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  43077. if (BABYLON.Tags) {
  43078. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  43079. }
  43080. scene.pushGeometry(torusKnot, true);
  43081. return torusKnot;
  43082. };
  43083. return TorusKnotGeometry;
  43084. }(_PrimitiveGeometry));
  43085. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  43086. //}
  43087. })(BABYLON || (BABYLON = {}));
  43088. //# sourceMappingURL=babylon.geometry.js.map
  43089. var BABYLON;
  43090. (function (BABYLON) {
  43091. /**
  43092. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  43093. */
  43094. var PerformanceMonitor = /** @class */ (function () {
  43095. /**
  43096. * constructor
  43097. * @param frameSampleSize The number of samples required to saturate the sliding window
  43098. */
  43099. function PerformanceMonitor(frameSampleSize) {
  43100. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  43101. this._enabled = true;
  43102. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  43103. }
  43104. /**
  43105. * Samples current frame
  43106. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  43107. */
  43108. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  43109. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  43110. if (!this._enabled) {
  43111. return;
  43112. }
  43113. if (this._lastFrameTimeMs != null) {
  43114. var dt = timeMs - this._lastFrameTimeMs;
  43115. this._rollingFrameTime.add(dt);
  43116. }
  43117. this._lastFrameTimeMs = timeMs;
  43118. };
  43119. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  43120. /**
  43121. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  43122. */
  43123. get: function () {
  43124. return this._rollingFrameTime.average;
  43125. },
  43126. enumerable: true,
  43127. configurable: true
  43128. });
  43129. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  43130. /**
  43131. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  43132. */
  43133. get: function () {
  43134. return this._rollingFrameTime.variance;
  43135. },
  43136. enumerable: true,
  43137. configurable: true
  43138. });
  43139. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  43140. /**
  43141. * Returns the frame time of the most recent frame
  43142. */
  43143. get: function () {
  43144. return this._rollingFrameTime.history(0);
  43145. },
  43146. enumerable: true,
  43147. configurable: true
  43148. });
  43149. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  43150. /**
  43151. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  43152. */
  43153. get: function () {
  43154. return 1000.0 / this._rollingFrameTime.average;
  43155. },
  43156. enumerable: true,
  43157. configurable: true
  43158. });
  43159. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  43160. /**
  43161. * Returns the average framerate in frames per second using the most recent frame time
  43162. */
  43163. get: function () {
  43164. var history = this._rollingFrameTime.history(0);
  43165. if (history === 0) {
  43166. return 0;
  43167. }
  43168. return 1000.0 / history;
  43169. },
  43170. enumerable: true,
  43171. configurable: true
  43172. });
  43173. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  43174. /**
  43175. * Returns true if enough samples have been taken to completely fill the sliding window
  43176. */
  43177. get: function () {
  43178. return this._rollingFrameTime.isSaturated();
  43179. },
  43180. enumerable: true,
  43181. configurable: true
  43182. });
  43183. /**
  43184. * Enables contributions to the sliding window sample set
  43185. */
  43186. PerformanceMonitor.prototype.enable = function () {
  43187. this._enabled = true;
  43188. };
  43189. /**
  43190. * Disables contributions to the sliding window sample set
  43191. * Samples will not be interpolated over the disabled period
  43192. */
  43193. PerformanceMonitor.prototype.disable = function () {
  43194. this._enabled = false;
  43195. //clear last sample to avoid interpolating over the disabled period when next enabled
  43196. this._lastFrameTimeMs = null;
  43197. };
  43198. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  43199. /**
  43200. * Returns true if sampling is enabled
  43201. */
  43202. get: function () {
  43203. return this._enabled;
  43204. },
  43205. enumerable: true,
  43206. configurable: true
  43207. });
  43208. /**
  43209. * Resets performance monitor
  43210. */
  43211. PerformanceMonitor.prototype.reset = function () {
  43212. //clear last sample to avoid interpolating over the disabled period when next enabled
  43213. this._lastFrameTimeMs = null;
  43214. //wipe record
  43215. this._rollingFrameTime.reset();
  43216. };
  43217. return PerformanceMonitor;
  43218. }());
  43219. BABYLON.PerformanceMonitor = PerformanceMonitor;
  43220. /**
  43221. * RollingAverage
  43222. *
  43223. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  43224. */
  43225. var RollingAverage = /** @class */ (function () {
  43226. /**
  43227. * constructor
  43228. * @param length The number of samples required to saturate the sliding window
  43229. */
  43230. function RollingAverage(length) {
  43231. this._samples = new Array(length);
  43232. this.reset();
  43233. }
  43234. /**
  43235. * Adds a sample to the sample set
  43236. * @param v The sample value
  43237. */
  43238. RollingAverage.prototype.add = function (v) {
  43239. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  43240. var delta;
  43241. //we need to check if we've already wrapped round
  43242. if (this.isSaturated()) {
  43243. //remove bottom of stack from mean
  43244. var bottomValue = this._samples[this._pos];
  43245. delta = bottomValue - this.average;
  43246. this.average -= delta / (this._sampleCount - 1);
  43247. this._m2 -= delta * (bottomValue - this.average);
  43248. }
  43249. else {
  43250. this._sampleCount++;
  43251. }
  43252. //add new value to mean
  43253. delta = v - this.average;
  43254. this.average += delta / (this._sampleCount);
  43255. this._m2 += delta * (v - this.average);
  43256. //set the new variance
  43257. this.variance = this._m2 / (this._sampleCount - 1);
  43258. this._samples[this._pos] = v;
  43259. this._pos++;
  43260. this._pos %= this._samples.length; //positive wrap around
  43261. };
  43262. /**
  43263. * Returns previously added values or null if outside of history or outside the sliding window domain
  43264. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  43265. * @return Value previously recorded with add() or null if outside of range
  43266. */
  43267. RollingAverage.prototype.history = function (i) {
  43268. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  43269. return 0;
  43270. }
  43271. var i0 = this._wrapPosition(this._pos - 1.0);
  43272. return this._samples[this._wrapPosition(i0 - i)];
  43273. };
  43274. /**
  43275. * Returns true if enough samples have been taken to completely fill the sliding window
  43276. * @return true if sample-set saturated
  43277. */
  43278. RollingAverage.prototype.isSaturated = function () {
  43279. return this._sampleCount >= this._samples.length;
  43280. };
  43281. /**
  43282. * Resets the rolling average (equivalent to 0 samples taken so far)
  43283. */
  43284. RollingAverage.prototype.reset = function () {
  43285. this.average = 0;
  43286. this.variance = 0;
  43287. this._sampleCount = 0;
  43288. this._pos = 0;
  43289. this._m2 = 0;
  43290. };
  43291. /**
  43292. * Wraps a value around the sample range boundaries
  43293. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  43294. * @return Wrapped position in sample range
  43295. */
  43296. RollingAverage.prototype._wrapPosition = function (i) {
  43297. var max = this._samples.length;
  43298. return ((i % max) + max) % max;
  43299. };
  43300. return RollingAverage;
  43301. }());
  43302. BABYLON.RollingAverage = RollingAverage;
  43303. })(BABYLON || (BABYLON = {}));
  43304. //# sourceMappingURL=babylon.performanceMonitor.js.map
  43305. var BABYLON;
  43306. (function (BABYLON) {
  43307. /**
  43308. * "Static Class" containing the most commonly used helper while dealing with material for
  43309. * rendering purpose.
  43310. *
  43311. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  43312. *
  43313. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  43314. */
  43315. var MaterialHelper = /** @class */ (function () {
  43316. function MaterialHelper() {
  43317. }
  43318. /**
  43319. * Bind the current view position to an effect.
  43320. * @param effect The effect to be bound
  43321. * @param scene The scene the eyes position is used from
  43322. */
  43323. MaterialHelper.BindEyePosition = function (effect, scene) {
  43324. if (scene._forcedViewPosition) {
  43325. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  43326. return;
  43327. }
  43328. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  43329. };
  43330. /**
  43331. * Helps preparing the defines values about the UVs in used in the effect.
  43332. * UVs are shared as much as we can accross channels in the shaders.
  43333. * @param texture The texture we are preparing the UVs for
  43334. * @param defines The defines to update
  43335. * @param key The channel key "diffuse", "specular"... used in the shader
  43336. */
  43337. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  43338. defines._needUVs = true;
  43339. defines[key] = true;
  43340. if (texture.getTextureMatrix().isIdentityAs3x2()) {
  43341. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  43342. if (texture.coordinatesIndex === 0) {
  43343. defines["MAINUV1"] = true;
  43344. }
  43345. else {
  43346. defines["MAINUV2"] = true;
  43347. }
  43348. }
  43349. else {
  43350. defines[key + "DIRECTUV"] = 0;
  43351. }
  43352. };
  43353. /**
  43354. * Binds a texture matrix value to its corrsponding uniform
  43355. * @param texture The texture to bind the matrix for
  43356. * @param uniformBuffer The uniform buffer receivin the data
  43357. * @param key The channel key "diffuse", "specular"... used in the shader
  43358. */
  43359. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  43360. var matrix = texture.getTextureMatrix();
  43361. if (!matrix.isIdentityAs3x2()) {
  43362. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  43363. }
  43364. };
  43365. /**
  43366. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  43367. * @param mesh defines the current mesh
  43368. * @param scene defines the current scene
  43369. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  43370. * @param pointsCloud defines if point cloud rendering has to be turned on
  43371. * @param fogEnabled defines if fog has to be turned on
  43372. * @param alphaTest defines if alpha testing has to be turned on
  43373. * @param defines defines the current list of defines
  43374. */
  43375. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  43376. if (defines._areMiscDirty) {
  43377. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  43378. defines["POINTSIZE"] = pointsCloud;
  43379. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  43380. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  43381. defines["ALPHATEST"] = alphaTest;
  43382. }
  43383. };
  43384. /**
  43385. * Helper used to prepare the list of defines associated with frame values for shader compilation
  43386. * @param scene defines the current scene
  43387. * @param engine defines the current engine
  43388. * @param defines specifies the list of active defines
  43389. * @param useInstances defines if instances have to be turned on
  43390. * @param useClipPlane defines if clip plane have to be turned on
  43391. */
  43392. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  43393. if (useClipPlane === void 0) { useClipPlane = null; }
  43394. var changed = false;
  43395. var useClipPlane1 = false;
  43396. var useClipPlane2 = false;
  43397. var useClipPlane3 = false;
  43398. var useClipPlane4 = false;
  43399. useClipPlane1 = useClipPlane == null ? (scene.clipPlane !== undefined && scene.clipPlane !== null) : useClipPlane;
  43400. useClipPlane2 = useClipPlane == null ? (scene.clipPlane2 !== undefined && scene.clipPlane2 !== null) : useClipPlane;
  43401. useClipPlane3 = useClipPlane == null ? (scene.clipPlane3 !== undefined && scene.clipPlane3 !== null) : useClipPlane;
  43402. useClipPlane4 = useClipPlane == null ? (scene.clipPlane4 !== undefined && scene.clipPlane4 !== null) : useClipPlane;
  43403. if (defines["CLIPPLANE"] !== useClipPlane1) {
  43404. defines["CLIPPLANE"] = useClipPlane1;
  43405. changed = true;
  43406. }
  43407. if (defines["CLIPPLANE2"] !== useClipPlane2) {
  43408. defines["CLIPPLANE2"] = useClipPlane2;
  43409. changed = true;
  43410. }
  43411. if (defines["CLIPPLANE3"] !== useClipPlane3) {
  43412. defines["CLIPPLANE3"] = useClipPlane3;
  43413. changed = true;
  43414. }
  43415. if (defines["CLIPPLANE4"] !== useClipPlane4) {
  43416. defines["CLIPPLANE4"] = useClipPlane4;
  43417. changed = true;
  43418. }
  43419. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  43420. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  43421. changed = true;
  43422. }
  43423. if (defines["INSTANCES"] !== useInstances) {
  43424. defines["INSTANCES"] = useInstances;
  43425. changed = true;
  43426. }
  43427. if (changed) {
  43428. defines.markAsUnprocessed();
  43429. }
  43430. };
  43431. /**
  43432. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  43433. * @param mesh The mesh containing the geometry data we will draw
  43434. * @param defines The defines to update
  43435. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  43436. * @param useBones Precise whether bones should be used or not (override mesh info)
  43437. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  43438. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  43439. * @returns false if defines are considered not dirty and have not been checked
  43440. */
  43441. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  43442. if (useMorphTargets === void 0) { useMorphTargets = false; }
  43443. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  43444. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  43445. return false;
  43446. }
  43447. defines._normals = defines._needNormals;
  43448. defines._uvs = defines._needUVs;
  43449. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  43450. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  43451. defines["TANGENT"] = true;
  43452. }
  43453. if (defines._needUVs) {
  43454. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  43455. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  43456. }
  43457. else {
  43458. defines["UV1"] = false;
  43459. defines["UV2"] = false;
  43460. }
  43461. if (useVertexColor) {
  43462. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  43463. defines["VERTEXCOLOR"] = hasVertexColors;
  43464. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  43465. }
  43466. if (useBones) {
  43467. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  43468. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  43469. var materialSupportsBoneTexture = defines["BONETEXTURE"] !== undefined;
  43470. if (mesh.skeleton.isUsingTextureForMatrices && materialSupportsBoneTexture) {
  43471. defines["BONETEXTURE"] = true;
  43472. }
  43473. else {
  43474. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  43475. defines["BONETEXTURE"] = materialSupportsBoneTexture ? false : undefined;
  43476. }
  43477. }
  43478. else {
  43479. defines["NUM_BONE_INFLUENCERS"] = 0;
  43480. defines["BonesPerMesh"] = 0;
  43481. }
  43482. }
  43483. if (useMorphTargets) {
  43484. var manager = mesh.morphTargetManager;
  43485. if (manager) {
  43486. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  43487. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  43488. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  43489. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  43490. }
  43491. else {
  43492. defines["MORPHTARGETS_TANGENT"] = false;
  43493. defines["MORPHTARGETS_NORMAL"] = false;
  43494. defines["MORPHTARGETS"] = false;
  43495. defines["NUM_MORPH_INFLUENCERS"] = 0;
  43496. }
  43497. }
  43498. return true;
  43499. };
  43500. /**
  43501. * Prepares the defines related to the light information passed in parameter
  43502. * @param scene The scene we are intending to draw
  43503. * @param mesh The mesh the effect is compiling for
  43504. * @param defines The defines to update
  43505. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  43506. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  43507. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  43508. * @returns true if normals will be required for the rest of the effect
  43509. */
  43510. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  43511. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  43512. if (disableLighting === void 0) { disableLighting = false; }
  43513. if (!defines._areLightsDirty) {
  43514. return defines._needNormals;
  43515. }
  43516. var lightIndex = 0;
  43517. var needNormals = false;
  43518. var needRebuild = false;
  43519. var lightmapMode = false;
  43520. var shadowEnabled = false;
  43521. var specularEnabled = false;
  43522. if (scene.lightsEnabled && !disableLighting) {
  43523. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  43524. var light = _a[_i];
  43525. needNormals = true;
  43526. if (defines["LIGHT" + lightIndex] === undefined) {
  43527. needRebuild = true;
  43528. }
  43529. defines["LIGHT" + lightIndex] = true;
  43530. defines["SPOTLIGHT" + lightIndex] = false;
  43531. defines["HEMILIGHT" + lightIndex] = false;
  43532. defines["POINTLIGHT" + lightIndex] = false;
  43533. defines["DIRLIGHT" + lightIndex] = false;
  43534. light.prepareLightSpecificDefines(defines, lightIndex);
  43535. // FallOff.
  43536. defines["LIGHT_FALLOFF_PHYSICAL" + lightIndex] = false;
  43537. defines["LIGHT_FALLOFF_GLTF" + lightIndex] = false;
  43538. defines["LIGHT_FALLOFF_STANDARD" + lightIndex] = false;
  43539. switch (light.falloffType) {
  43540. case BABYLON.Light.FALLOFF_GLTF:
  43541. defines["LIGHT_FALLOFF_GLTF" + lightIndex] = true;
  43542. break;
  43543. case BABYLON.Light.FALLOFF_PHYSICAL:
  43544. defines["LIGHT_FALLOFF_PHYSICAL" + lightIndex] = true;
  43545. break;
  43546. case BABYLON.Light.FALLOFF_STANDARD:
  43547. defines["LIGHT_FALLOFF_STANDARD" + lightIndex] = true;
  43548. break;
  43549. }
  43550. // Specular
  43551. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  43552. specularEnabled = true;
  43553. }
  43554. // Shadows
  43555. defines["SHADOW" + lightIndex] = false;
  43556. defines["SHADOWPCF" + lightIndex] = false;
  43557. defines["SHADOWPCSS" + lightIndex] = false;
  43558. defines["SHADOWPOISSON" + lightIndex] = false;
  43559. defines["SHADOWESM" + lightIndex] = false;
  43560. defines["SHADOWCUBE" + lightIndex] = false;
  43561. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  43562. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  43563. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  43564. var shadowGenerator = light.getShadowGenerator();
  43565. if (shadowGenerator) {
  43566. var shadowMap = shadowGenerator.getShadowMap();
  43567. if (shadowMap) {
  43568. if (shadowMap.renderList && shadowMap.renderList.length > 0) {
  43569. shadowEnabled = true;
  43570. shadowGenerator.prepareDefines(defines, lightIndex);
  43571. }
  43572. }
  43573. }
  43574. }
  43575. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  43576. lightmapMode = true;
  43577. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  43578. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  43579. }
  43580. else {
  43581. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  43582. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  43583. }
  43584. lightIndex++;
  43585. if (lightIndex === maxSimultaneousLights) {
  43586. break;
  43587. }
  43588. }
  43589. }
  43590. defines["SPECULARTERM"] = specularEnabled;
  43591. defines["SHADOWS"] = shadowEnabled;
  43592. // Resetting all other lights if any
  43593. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  43594. if (defines["LIGHT" + index] !== undefined) {
  43595. defines["LIGHT" + index] = false;
  43596. defines["HEMILIGHT" + lightIndex] = false;
  43597. defines["POINTLIGHT" + lightIndex] = false;
  43598. defines["DIRLIGHT" + lightIndex] = false;
  43599. defines["SPOTLIGHT" + lightIndex] = false;
  43600. defines["SHADOW" + lightIndex] = false;
  43601. }
  43602. }
  43603. var caps = scene.getEngine().getCaps();
  43604. if (defines["SHADOWFLOAT"] === undefined) {
  43605. needRebuild = true;
  43606. }
  43607. defines["SHADOWFLOAT"] = shadowEnabled &&
  43608. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  43609. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  43610. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  43611. if (needRebuild) {
  43612. defines.rebuild();
  43613. }
  43614. return needNormals;
  43615. };
  43616. /**
  43617. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  43618. * that won t be acctive due to defines being turned off.
  43619. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  43620. * @param samplersList The samplers list
  43621. * @param defines The defines helping in the list generation
  43622. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  43623. */
  43624. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  43625. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  43626. var uniformsList;
  43627. var uniformBuffersList = null;
  43628. if (uniformsListOrOptions.uniformsNames) {
  43629. var options = uniformsListOrOptions;
  43630. uniformsList = options.uniformsNames;
  43631. uniformBuffersList = options.uniformBuffersNames;
  43632. samplersList = options.samplers;
  43633. defines = options.defines;
  43634. maxSimultaneousLights = options.maxSimultaneousLights;
  43635. }
  43636. else {
  43637. uniformsList = uniformsListOrOptions;
  43638. if (!samplersList) {
  43639. samplersList = [];
  43640. }
  43641. }
  43642. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  43643. if (!defines["LIGHT" + lightIndex]) {
  43644. break;
  43645. }
  43646. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightFalloff" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  43647. if (uniformBuffersList) {
  43648. uniformBuffersList.push("Light" + lightIndex);
  43649. }
  43650. samplersList.push("shadowSampler" + lightIndex);
  43651. samplersList.push("depthSampler" + lightIndex);
  43652. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  43653. samplersList.push("projectionLightSampler" + lightIndex);
  43654. uniformsList.push("textureProjectionMatrix" + lightIndex);
  43655. }
  43656. }
  43657. if (defines["NUM_MORPH_INFLUENCERS"]) {
  43658. uniformsList.push("morphTargetInfluences");
  43659. }
  43660. };
  43661. /**
  43662. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  43663. * @param defines The defines to update while falling back
  43664. * @param fallbacks The authorized effect fallbacks
  43665. * @param maxSimultaneousLights The maximum number of lights allowed
  43666. * @param rank the current rank of the Effect
  43667. * @returns The newly affected rank
  43668. */
  43669. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  43670. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  43671. if (rank === void 0) { rank = 0; }
  43672. var lightFallbackRank = 0;
  43673. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  43674. if (!defines["LIGHT" + lightIndex]) {
  43675. break;
  43676. }
  43677. if (lightIndex > 0) {
  43678. lightFallbackRank = rank + lightIndex;
  43679. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  43680. }
  43681. if (!defines["SHADOWS"]) {
  43682. if (defines["SHADOW" + lightIndex]) {
  43683. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  43684. }
  43685. if (defines["SHADOWPCF" + lightIndex]) {
  43686. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  43687. }
  43688. if (defines["SHADOWPCSS" + lightIndex]) {
  43689. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  43690. }
  43691. if (defines["SHADOWPOISSON" + lightIndex]) {
  43692. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  43693. }
  43694. if (defines["SHADOWESM" + lightIndex]) {
  43695. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  43696. }
  43697. }
  43698. }
  43699. return lightFallbackRank++;
  43700. };
  43701. /**
  43702. * Prepares the list of attributes required for morph targets according to the effect defines.
  43703. * @param attribs The current list of supported attribs
  43704. * @param mesh The mesh to prepare the morph targets attributes for
  43705. * @param defines The current Defines of the effect
  43706. */
  43707. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  43708. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  43709. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  43710. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  43711. var manager = mesh.morphTargetManager;
  43712. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  43713. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  43714. for (var index = 0; index < influencers; index++) {
  43715. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  43716. if (normal) {
  43717. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  43718. }
  43719. if (tangent) {
  43720. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  43721. }
  43722. if (attribs.length > maxAttributesCount) {
  43723. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  43724. }
  43725. }
  43726. }
  43727. };
  43728. /**
  43729. * Prepares the list of attributes required for bones according to the effect defines.
  43730. * @param attribs The current list of supported attribs
  43731. * @param mesh The mesh to prepare the bones attributes for
  43732. * @param defines The current Defines of the effect
  43733. * @param fallbacks The current efffect fallback strategy
  43734. */
  43735. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  43736. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  43737. fallbacks.addCPUSkinningFallback(0, mesh);
  43738. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  43739. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  43740. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  43741. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  43742. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  43743. }
  43744. }
  43745. };
  43746. /**
  43747. * Prepares the list of attributes required for instances according to the effect defines.
  43748. * @param attribs The current list of supported attribs
  43749. * @param defines The current Defines of the effect
  43750. */
  43751. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  43752. if (defines["INSTANCES"]) {
  43753. attribs.push("world0");
  43754. attribs.push("world1");
  43755. attribs.push("world2");
  43756. attribs.push("world3");
  43757. }
  43758. };
  43759. /**
  43760. * Binds the light shadow information to the effect for the given mesh.
  43761. * @param light The light containing the generator
  43762. * @param scene The scene the lights belongs to
  43763. * @param mesh The mesh we are binding the information to render
  43764. * @param lightIndex The light index in the effect used to render the mesh
  43765. * @param effect The effect we are binding the data to
  43766. */
  43767. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  43768. if (light.shadowEnabled && mesh.receiveShadows) {
  43769. var shadowGenerator = light.getShadowGenerator();
  43770. if (shadowGenerator) {
  43771. shadowGenerator.bindShadowLight(lightIndex, effect);
  43772. }
  43773. }
  43774. };
  43775. /**
  43776. * Binds the light information to the effect.
  43777. * @param light The light containing the generator
  43778. * @param effect The effect we are binding the data to
  43779. * @param lightIndex The light index in the effect used to render
  43780. */
  43781. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  43782. light.transferToEffect(effect, lightIndex + "");
  43783. };
  43784. /**
  43785. * Binds the lights information from the scene to the effect for the given mesh.
  43786. * @param scene The scene the lights belongs to
  43787. * @param mesh The mesh we are binding the information to render
  43788. * @param effect The effect we are binding the data to
  43789. * @param defines The generated defines for the effect
  43790. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  43791. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  43792. */
  43793. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  43794. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  43795. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  43796. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  43797. for (var i = 0; i < len; i++) {
  43798. var light = mesh._lightSources[i];
  43799. var iAsString = i.toString();
  43800. var scaledIntensity = light.getScaledIntensity();
  43801. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  43802. MaterialHelper.BindLightProperties(light, effect, i);
  43803. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  43804. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  43805. if (defines["SPECULARTERM"]) {
  43806. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  43807. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  43808. }
  43809. // Shadows
  43810. if (scene.shadowsEnabled) {
  43811. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  43812. }
  43813. light._uniformBuffer.update();
  43814. }
  43815. };
  43816. /**
  43817. * Binds the fog information from the scene to the effect for the given mesh.
  43818. * @param scene The scene the lights belongs to
  43819. * @param mesh The mesh we are binding the information to render
  43820. * @param effect The effect we are binding the data to
  43821. * @param linearSpace Defines if the fog effect is applied in linear space
  43822. */
  43823. MaterialHelper.BindFogParameters = function (scene, mesh, effect, linearSpace) {
  43824. if (linearSpace === void 0) { linearSpace = false; }
  43825. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  43826. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  43827. // Convert fog color to linear space if used in a linear space computed shader.
  43828. if (linearSpace) {
  43829. scene.fogColor.toLinearSpaceToRef(this._tempFogColor);
  43830. effect.setColor3("vFogColor", this._tempFogColor);
  43831. }
  43832. else {
  43833. effect.setColor3("vFogColor", scene.fogColor);
  43834. }
  43835. }
  43836. };
  43837. /**
  43838. * Binds the bones information from the mesh to the effect.
  43839. * @param mesh The mesh we are binding the information to render
  43840. * @param effect The effect we are binding the data to
  43841. */
  43842. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  43843. if (!effect || !mesh) {
  43844. return;
  43845. }
  43846. if (mesh.computeBonesUsingShaders && effect._bonesComputationForcedToCPU) {
  43847. mesh.computeBonesUsingShaders = false;
  43848. }
  43849. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  43850. var skeleton = mesh.skeleton;
  43851. if (skeleton.isUsingTextureForMatrices && effect.getUniformIndex("boneTextureWidth") > -1) {
  43852. var boneTexture = skeleton.getTransformMatrixTexture();
  43853. effect.setTexture("boneSampler", boneTexture);
  43854. effect.setFloat("boneTextureWidth", 4.0 * (skeleton.bones.length + 1));
  43855. }
  43856. else {
  43857. var matrices = skeleton.getTransformMatrices(mesh);
  43858. if (matrices) {
  43859. effect.setMatrices("mBones", matrices);
  43860. }
  43861. }
  43862. }
  43863. };
  43864. /**
  43865. * Binds the morph targets information from the mesh to the effect.
  43866. * @param abstractMesh The mesh we are binding the information to render
  43867. * @param effect The effect we are binding the data to
  43868. */
  43869. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  43870. var manager = abstractMesh.morphTargetManager;
  43871. if (!abstractMesh || !manager) {
  43872. return;
  43873. }
  43874. effect.setFloatArray("morphTargetInfluences", manager.influences);
  43875. };
  43876. /**
  43877. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  43878. * @param defines The generated defines used in the effect
  43879. * @param effect The effect we are binding the data to
  43880. * @param scene The scene we are willing to render with logarithmic scale for
  43881. */
  43882. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  43883. if (defines["LOGARITHMICDEPTH"]) {
  43884. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  43885. }
  43886. };
  43887. /**
  43888. * Binds the clip plane information from the scene to the effect.
  43889. * @param scene The scene the clip plane information are extracted from
  43890. * @param effect The effect we are binding the data to
  43891. */
  43892. MaterialHelper.BindClipPlane = function (effect, scene) {
  43893. if (scene.clipPlane) {
  43894. var clipPlane = scene.clipPlane;
  43895. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  43896. }
  43897. if (scene.clipPlane2) {
  43898. var clipPlane = scene.clipPlane2;
  43899. effect.setFloat4("vClipPlane2", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  43900. }
  43901. if (scene.clipPlane3) {
  43902. var clipPlane = scene.clipPlane3;
  43903. effect.setFloat4("vClipPlane3", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  43904. }
  43905. if (scene.clipPlane4) {
  43906. var clipPlane = scene.clipPlane4;
  43907. effect.setFloat4("vClipPlane4", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  43908. }
  43909. };
  43910. MaterialHelper._tempFogColor = BABYLON.Color3.Black();
  43911. return MaterialHelper;
  43912. }());
  43913. BABYLON.MaterialHelper = MaterialHelper;
  43914. })(BABYLON || (BABYLON = {}));
  43915. //# sourceMappingURL=babylon.materialHelper.js.map
  43916. var BABYLON;
  43917. (function (BABYLON) {
  43918. /**
  43919. * Base class of materials working in push mode in babylon JS
  43920. * @hidden
  43921. */
  43922. var PushMaterial = /** @class */ (function (_super) {
  43923. __extends(PushMaterial, _super);
  43924. function PushMaterial(name, scene) {
  43925. var _this = _super.call(this, name, scene) || this;
  43926. _this._normalMatrix = new BABYLON.Matrix();
  43927. /**
  43928. * Gets or sets a boolean indicating that the material is allowed to do shader hot swapping.
  43929. * This means that the material can keep using a previous shader while a new one is being compiled.
  43930. * This is mostly used when shader parallel compilation is supported (true by default)
  43931. */
  43932. _this.allowShaderHotSwapping = true;
  43933. _this._storeEffectOnSubMeshes = true;
  43934. return _this;
  43935. }
  43936. PushMaterial.prototype.getEffect = function () {
  43937. return this._activeEffect;
  43938. };
  43939. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  43940. if (!mesh) {
  43941. return false;
  43942. }
  43943. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  43944. return true;
  43945. }
  43946. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  43947. };
  43948. /**
  43949. * Binds the given world matrix to the active effect
  43950. *
  43951. * @param world the matrix to bind
  43952. */
  43953. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  43954. this._activeEffect.setMatrix("world", world);
  43955. };
  43956. /**
  43957. * Binds the given normal matrix to the active effect
  43958. *
  43959. * @param normalMatrix the matrix to bind
  43960. */
  43961. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  43962. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  43963. };
  43964. PushMaterial.prototype.bind = function (world, mesh) {
  43965. if (!mesh) {
  43966. return;
  43967. }
  43968. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  43969. };
  43970. PushMaterial.prototype._afterBind = function (mesh, effect) {
  43971. if (effect === void 0) { effect = null; }
  43972. _super.prototype._afterBind.call(this, mesh);
  43973. this.getScene()._cachedEffect = effect;
  43974. };
  43975. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  43976. if (visibility === void 0) { visibility = 1; }
  43977. return scene.isCachedMaterialInvalid(this, effect, visibility);
  43978. };
  43979. return PushMaterial;
  43980. }(BABYLON.Material));
  43981. BABYLON.PushMaterial = PushMaterial;
  43982. })(BABYLON || (BABYLON = {}));
  43983. //# sourceMappingURL=babylon.pushMaterial.js.map
  43984. var BABYLON;
  43985. (function (BABYLON) {
  43986. /** @hidden */
  43987. var StandardMaterialDefines = /** @class */ (function (_super) {
  43988. __extends(StandardMaterialDefines, _super);
  43989. function StandardMaterialDefines() {
  43990. var _this = _super.call(this) || this;
  43991. _this.MAINUV1 = false;
  43992. _this.MAINUV2 = false;
  43993. _this.DIFFUSE = false;
  43994. _this.DIFFUSEDIRECTUV = 0;
  43995. _this.AMBIENT = false;
  43996. _this.AMBIENTDIRECTUV = 0;
  43997. _this.OPACITY = false;
  43998. _this.OPACITYDIRECTUV = 0;
  43999. _this.OPACITYRGB = false;
  44000. _this.REFLECTION = false;
  44001. _this.EMISSIVE = false;
  44002. _this.EMISSIVEDIRECTUV = 0;
  44003. _this.SPECULAR = false;
  44004. _this.SPECULARDIRECTUV = 0;
  44005. _this.BUMP = false;
  44006. _this.BUMPDIRECTUV = 0;
  44007. _this.PARALLAX = false;
  44008. _this.PARALLAXOCCLUSION = false;
  44009. _this.SPECULAROVERALPHA = false;
  44010. _this.CLIPPLANE = false;
  44011. _this.CLIPPLANE2 = false;
  44012. _this.CLIPPLANE3 = false;
  44013. _this.CLIPPLANE4 = false;
  44014. _this.ALPHATEST = false;
  44015. _this.DEPTHPREPASS = false;
  44016. _this.ALPHAFROMDIFFUSE = false;
  44017. _this.POINTSIZE = false;
  44018. _this.FOG = false;
  44019. _this.SPECULARTERM = false;
  44020. _this.DIFFUSEFRESNEL = false;
  44021. _this.OPACITYFRESNEL = false;
  44022. _this.REFLECTIONFRESNEL = false;
  44023. _this.REFRACTIONFRESNEL = false;
  44024. _this.EMISSIVEFRESNEL = false;
  44025. _this.FRESNEL = false;
  44026. _this.NORMAL = false;
  44027. _this.UV1 = false;
  44028. _this.UV2 = false;
  44029. _this.VERTEXCOLOR = false;
  44030. _this.VERTEXALPHA = false;
  44031. _this.NUM_BONE_INFLUENCERS = 0;
  44032. _this.BonesPerMesh = 0;
  44033. _this.BONETEXTURE = false;
  44034. _this.INSTANCES = false;
  44035. _this.GLOSSINESS = false;
  44036. _this.ROUGHNESS = false;
  44037. _this.EMISSIVEASILLUMINATION = false;
  44038. _this.LINKEMISSIVEWITHDIFFUSE = false;
  44039. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  44040. _this.LIGHTMAP = false;
  44041. _this.LIGHTMAPDIRECTUV = 0;
  44042. _this.OBJECTSPACE_NORMALMAP = false;
  44043. _this.USELIGHTMAPASSHADOWMAP = false;
  44044. _this.REFLECTIONMAP_3D = false;
  44045. _this.REFLECTIONMAP_SPHERICAL = false;
  44046. _this.REFLECTIONMAP_PLANAR = false;
  44047. _this.REFLECTIONMAP_CUBIC = false;
  44048. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  44049. _this.REFLECTIONMAP_PROJECTION = false;
  44050. _this.REFLECTIONMAP_SKYBOX = false;
  44051. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  44052. _this.REFLECTIONMAP_EXPLICIT = false;
  44053. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  44054. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  44055. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  44056. _this.INVERTCUBICMAP = false;
  44057. _this.LOGARITHMICDEPTH = false;
  44058. _this.REFRACTION = false;
  44059. _this.REFRACTIONMAP_3D = false;
  44060. _this.REFLECTIONOVERALPHA = false;
  44061. _this.TWOSIDEDLIGHTING = false;
  44062. _this.SHADOWFLOAT = false;
  44063. _this.MORPHTARGETS = false;
  44064. _this.MORPHTARGETS_NORMAL = false;
  44065. _this.MORPHTARGETS_TANGENT = false;
  44066. _this.NUM_MORPH_INFLUENCERS = 0;
  44067. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  44068. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  44069. _this.IMAGEPROCESSING = false;
  44070. _this.VIGNETTE = false;
  44071. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  44072. _this.VIGNETTEBLENDMODEOPAQUE = false;
  44073. _this.TONEMAPPING = false;
  44074. _this.TONEMAPPING_ACES = false;
  44075. _this.CONTRAST = false;
  44076. _this.COLORCURVES = false;
  44077. _this.COLORGRADING = false;
  44078. _this.COLORGRADING3D = false;
  44079. _this.SAMPLER3DGREENDEPTH = false;
  44080. _this.SAMPLER3DBGRMAP = false;
  44081. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  44082. /**
  44083. * If the reflection texture on this material is in linear color space
  44084. * @hidden
  44085. */
  44086. _this.IS_REFLECTION_LINEAR = false;
  44087. /**
  44088. * If the refraction texture on this material is in linear color space
  44089. * @hidden
  44090. */
  44091. _this.IS_REFRACTION_LINEAR = false;
  44092. _this.EXPOSURE = false;
  44093. _this.rebuild();
  44094. return _this;
  44095. }
  44096. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  44097. var modes = [
  44098. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  44099. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  44100. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  44101. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  44102. ];
  44103. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  44104. var mode = modes_1[_i];
  44105. this[mode] = (mode === modeToEnable);
  44106. }
  44107. };
  44108. return StandardMaterialDefines;
  44109. }(BABYLON.MaterialDefines));
  44110. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  44111. /**
  44112. * This is the default material used in Babylon. It is the best trade off between quality
  44113. * and performances.
  44114. * @see http://doc.babylonjs.com/babylon101/materials
  44115. */
  44116. var StandardMaterial = /** @class */ (function (_super) {
  44117. __extends(StandardMaterial, _super);
  44118. /**
  44119. * Instantiates a new standard material.
  44120. * This is the default material used in Babylon. It is the best trade off between quality
  44121. * and performances.
  44122. * @see http://doc.babylonjs.com/babylon101/materials
  44123. * @param name Define the name of the material in the scene
  44124. * @param scene Define the scene the material belong to
  44125. */
  44126. function StandardMaterial(name, scene) {
  44127. var _this = _super.call(this, name, scene) || this;
  44128. /**
  44129. * The color of the material lit by the environmental background lighting.
  44130. * @see http://doc.babylonjs.com/babylon101/materials#ambient-color-example
  44131. */
  44132. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  44133. /**
  44134. * The basic color of the material as viewed under a light.
  44135. */
  44136. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  44137. /**
  44138. * Define how the color and intensity of the highlight given by the light in the material.
  44139. */
  44140. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  44141. /**
  44142. * Define the color of the material as if self lit.
  44143. * This will be mixed in the final result even in the absence of light.
  44144. */
  44145. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  44146. /**
  44147. * Defines how sharp are the highlights in the material.
  44148. * The bigger the value the sharper giving a more glossy feeling to the result.
  44149. * Reversely, the smaller the value the blurrier giving a more rough feeling to the result.
  44150. */
  44151. _this.specularPower = 64;
  44152. _this._useAlphaFromDiffuseTexture = false;
  44153. _this._useEmissiveAsIllumination = false;
  44154. _this._linkEmissiveWithDiffuse = false;
  44155. _this._useSpecularOverAlpha = false;
  44156. _this._useReflectionOverAlpha = false;
  44157. _this._disableLighting = false;
  44158. _this._useObjectSpaceNormalMap = false;
  44159. _this._useParallax = false;
  44160. _this._useParallaxOcclusion = false;
  44161. /**
  44162. * 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.
  44163. */
  44164. _this.parallaxScaleBias = 0.05;
  44165. _this._roughness = 0;
  44166. /**
  44167. * In case of refraction, define the value of the indice of refraction.
  44168. * @see http://doc.babylonjs.com/how_to/reflect#how-to-obtain-reflections-and-refractions
  44169. */
  44170. _this.indexOfRefraction = 0.98;
  44171. /**
  44172. * Invert the refraction texture alongside the y axis.
  44173. * It can be useful with procedural textures or probe for instance.
  44174. * @see http://doc.babylonjs.com/how_to/reflect#how-to-obtain-reflections-and-refractions
  44175. */
  44176. _this.invertRefractionY = true;
  44177. /**
  44178. * Defines the alpha limits in alpha test mode.
  44179. */
  44180. _this.alphaCutOff = 0.4;
  44181. _this._useLightmapAsShadowmap = false;
  44182. _this._useReflectionFresnelFromSpecular = false;
  44183. _this._useGlossinessFromSpecularMapAlpha = false;
  44184. _this._maxSimultaneousLights = 4;
  44185. _this._invertNormalMapX = false;
  44186. _this._invertNormalMapY = false;
  44187. _this._twoSidedLighting = false;
  44188. _this._renderTargets = new BABYLON.SmartArray(16);
  44189. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  44190. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  44191. // Setup the default processing configuration to the scene.
  44192. _this._attachImageProcessingConfiguration(null);
  44193. _this.getRenderTargetTextures = function () {
  44194. _this._renderTargets.reset();
  44195. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  44196. _this._renderTargets.push(_this._reflectionTexture);
  44197. }
  44198. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  44199. _this._renderTargets.push(_this._refractionTexture);
  44200. }
  44201. return _this._renderTargets;
  44202. };
  44203. return _this;
  44204. }
  44205. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  44206. /**
  44207. * Gets the image processing configuration used either in this material.
  44208. */
  44209. get: function () {
  44210. return this._imageProcessingConfiguration;
  44211. },
  44212. /**
  44213. * Sets the Default image processing configuration used either in the this material.
  44214. *
  44215. * If sets to null, the scene one is in use.
  44216. */
  44217. set: function (value) {
  44218. this._attachImageProcessingConfiguration(value);
  44219. // Ensure the effect will be rebuilt.
  44220. this._markAllSubMeshesAsTexturesDirty();
  44221. },
  44222. enumerable: true,
  44223. configurable: true
  44224. });
  44225. /**
  44226. * Attaches a new image processing configuration to the Standard Material.
  44227. * @param configuration
  44228. */
  44229. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  44230. var _this = this;
  44231. if (configuration === this._imageProcessingConfiguration) {
  44232. return;
  44233. }
  44234. // Detaches observer.
  44235. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44236. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44237. }
  44238. // Pick the scene configuration if needed.
  44239. if (!configuration) {
  44240. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  44241. }
  44242. else {
  44243. this._imageProcessingConfiguration = configuration;
  44244. }
  44245. // Attaches observer.
  44246. if (this._imageProcessingConfiguration) {
  44247. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  44248. _this._markAllSubMeshesAsImageProcessingDirty();
  44249. });
  44250. }
  44251. };
  44252. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  44253. /**
  44254. * Gets wether the color curves effect is enabled.
  44255. */
  44256. get: function () {
  44257. return this.imageProcessingConfiguration.colorCurvesEnabled;
  44258. },
  44259. /**
  44260. * Sets wether the color curves effect is enabled.
  44261. */
  44262. set: function (value) {
  44263. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  44264. },
  44265. enumerable: true,
  44266. configurable: true
  44267. });
  44268. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  44269. /**
  44270. * Gets wether the color grading effect is enabled.
  44271. */
  44272. get: function () {
  44273. return this.imageProcessingConfiguration.colorGradingEnabled;
  44274. },
  44275. /**
  44276. * Gets wether the color grading effect is enabled.
  44277. */
  44278. set: function (value) {
  44279. this.imageProcessingConfiguration.colorGradingEnabled = value;
  44280. },
  44281. enumerable: true,
  44282. configurable: true
  44283. });
  44284. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  44285. /**
  44286. * Gets wether tonemapping is enabled or not.
  44287. */
  44288. get: function () {
  44289. return this._imageProcessingConfiguration.toneMappingEnabled;
  44290. },
  44291. /**
  44292. * Sets wether tonemapping is enabled or not
  44293. */
  44294. set: function (value) {
  44295. this._imageProcessingConfiguration.toneMappingEnabled = value;
  44296. },
  44297. enumerable: true,
  44298. configurable: true
  44299. });
  44300. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  44301. /**
  44302. * The camera exposure used on this material.
  44303. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  44304. * This corresponds to a photographic exposure.
  44305. */
  44306. get: function () {
  44307. return this._imageProcessingConfiguration.exposure;
  44308. },
  44309. /**
  44310. * The camera exposure used on this material.
  44311. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  44312. * This corresponds to a photographic exposure.
  44313. */
  44314. set: function (value) {
  44315. this._imageProcessingConfiguration.exposure = value;
  44316. },
  44317. enumerable: true,
  44318. configurable: true
  44319. });
  44320. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  44321. /**
  44322. * Gets The camera contrast used on this material.
  44323. */
  44324. get: function () {
  44325. return this._imageProcessingConfiguration.contrast;
  44326. },
  44327. /**
  44328. * Sets The camera contrast used on this material.
  44329. */
  44330. set: function (value) {
  44331. this._imageProcessingConfiguration.contrast = value;
  44332. },
  44333. enumerable: true,
  44334. configurable: true
  44335. });
  44336. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  44337. /**
  44338. * Gets the Color Grading 2D Lookup Texture.
  44339. */
  44340. get: function () {
  44341. return this._imageProcessingConfiguration.colorGradingTexture;
  44342. },
  44343. /**
  44344. * Sets the Color Grading 2D Lookup Texture.
  44345. */
  44346. set: function (value) {
  44347. this._imageProcessingConfiguration.colorGradingTexture = value;
  44348. },
  44349. enumerable: true,
  44350. configurable: true
  44351. });
  44352. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  44353. /**
  44354. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  44355. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  44356. * 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;
  44357. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  44358. */
  44359. get: function () {
  44360. return this._imageProcessingConfiguration.colorCurves;
  44361. },
  44362. /**
  44363. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  44364. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  44365. * 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;
  44366. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  44367. */
  44368. set: function (value) {
  44369. this._imageProcessingConfiguration.colorCurves = value;
  44370. },
  44371. enumerable: true,
  44372. configurable: true
  44373. });
  44374. Object.defineProperty(StandardMaterial.prototype, "hasRenderTargetTextures", {
  44375. /**
  44376. * Gets a boolean indicating that current material needs to register RTT
  44377. */
  44378. get: function () {
  44379. if (StandardMaterial.ReflectionTextureEnabled && this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  44380. return true;
  44381. }
  44382. if (StandardMaterial.RefractionTextureEnabled && this._refractionTexture && this._refractionTexture.isRenderTarget) {
  44383. return true;
  44384. }
  44385. return false;
  44386. },
  44387. enumerable: true,
  44388. configurable: true
  44389. });
  44390. /**
  44391. * Gets the current class name of the material e.g. "StandardMaterial"
  44392. * Mainly use in serialization.
  44393. * @returns the class name
  44394. */
  44395. StandardMaterial.prototype.getClassName = function () {
  44396. return "StandardMaterial";
  44397. };
  44398. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  44399. /**
  44400. * In case the depth buffer does not allow enough depth precision for your scene (might be the case in large scenes)
  44401. * You can try switching to logarithmic depth.
  44402. * @see http://doc.babylonjs.com/how_to/using_logarithmic_depth_buffer
  44403. */
  44404. get: function () {
  44405. return this._useLogarithmicDepth;
  44406. },
  44407. set: function (value) {
  44408. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  44409. this._markAllSubMeshesAsMiscDirty();
  44410. },
  44411. enumerable: true,
  44412. configurable: true
  44413. });
  44414. /**
  44415. * Specifies if the material will require alpha blending
  44416. * @returns a boolean specifying if alpha blending is needed
  44417. */
  44418. StandardMaterial.prototype.needAlphaBlending = function () {
  44419. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  44420. };
  44421. /**
  44422. * Specifies if this material should be rendered in alpha test mode
  44423. * @returns a boolean specifying if an alpha test is needed.
  44424. */
  44425. StandardMaterial.prototype.needAlphaTesting = function () {
  44426. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  44427. };
  44428. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  44429. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  44430. };
  44431. /**
  44432. * Get the texture used for alpha test purpose.
  44433. * @returns the diffuse texture in case of the standard material.
  44434. */
  44435. StandardMaterial.prototype.getAlphaTestTexture = function () {
  44436. return this._diffuseTexture;
  44437. };
  44438. /**
  44439. * Get if the submesh is ready to be used and all its information available.
  44440. * Child classes can use it to update shaders
  44441. * @param mesh defines the mesh to check
  44442. * @param subMesh defines which submesh to check
  44443. * @param useInstances specifies that instances should be used
  44444. * @returns a boolean indicating that the submesh is ready or not
  44445. */
  44446. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  44447. if (useInstances === void 0) { useInstances = false; }
  44448. if (subMesh.effect && this.isFrozen) {
  44449. if (this._wasPreviouslyReady) {
  44450. return true;
  44451. }
  44452. }
  44453. if (!subMesh._materialDefines) {
  44454. subMesh._materialDefines = new StandardMaterialDefines();
  44455. }
  44456. var scene = this.getScene();
  44457. var defines = subMesh._materialDefines;
  44458. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  44459. if (defines._renderId === scene.getRenderId()) {
  44460. return true;
  44461. }
  44462. }
  44463. var engine = scene.getEngine();
  44464. // Lights
  44465. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  44466. // Textures
  44467. if (defines._areTexturesDirty) {
  44468. defines._needUVs = false;
  44469. defines.MAINUV1 = false;
  44470. defines.MAINUV2 = false;
  44471. if (scene.texturesEnabled) {
  44472. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  44473. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  44474. return false;
  44475. }
  44476. else {
  44477. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  44478. }
  44479. }
  44480. else {
  44481. defines.DIFFUSE = false;
  44482. }
  44483. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  44484. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  44485. return false;
  44486. }
  44487. else {
  44488. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  44489. }
  44490. }
  44491. else {
  44492. defines.AMBIENT = false;
  44493. }
  44494. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  44495. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  44496. return false;
  44497. }
  44498. else {
  44499. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  44500. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  44501. }
  44502. }
  44503. else {
  44504. defines.OPACITY = false;
  44505. }
  44506. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  44507. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  44508. return false;
  44509. }
  44510. else {
  44511. defines._needNormals = true;
  44512. defines.REFLECTION = true;
  44513. defines.ROUGHNESS = (this._roughness > 0);
  44514. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  44515. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  44516. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  44517. switch (this._reflectionTexture.coordinatesMode) {
  44518. case BABYLON.Texture.EXPLICIT_MODE:
  44519. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  44520. break;
  44521. case BABYLON.Texture.PLANAR_MODE:
  44522. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  44523. break;
  44524. case BABYLON.Texture.PROJECTION_MODE:
  44525. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  44526. break;
  44527. case BABYLON.Texture.SKYBOX_MODE:
  44528. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  44529. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !this._reflectionTexture.getReflectionTextureMatrix().isIdentity();
  44530. break;
  44531. case BABYLON.Texture.SPHERICAL_MODE:
  44532. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  44533. break;
  44534. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  44535. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  44536. break;
  44537. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  44538. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  44539. break;
  44540. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  44541. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  44542. break;
  44543. case BABYLON.Texture.CUBIC_MODE:
  44544. case BABYLON.Texture.INVCUBIC_MODE:
  44545. default:
  44546. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  44547. break;
  44548. }
  44549. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  44550. }
  44551. }
  44552. else {
  44553. defines.REFLECTION = false;
  44554. }
  44555. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  44556. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  44557. return false;
  44558. }
  44559. else {
  44560. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  44561. }
  44562. }
  44563. else {
  44564. defines.EMISSIVE = false;
  44565. }
  44566. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  44567. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  44568. return false;
  44569. }
  44570. else {
  44571. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  44572. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  44573. }
  44574. }
  44575. else {
  44576. defines.LIGHTMAP = false;
  44577. }
  44578. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  44579. if (!this._specularTexture.isReadyOrNotBlocking()) {
  44580. return false;
  44581. }
  44582. else {
  44583. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  44584. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  44585. }
  44586. }
  44587. else {
  44588. defines.SPECULAR = false;
  44589. }
  44590. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  44591. // Bump texure can not be not blocking.
  44592. if (!this._bumpTexture.isReady()) {
  44593. return false;
  44594. }
  44595. else {
  44596. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  44597. defines.PARALLAX = this._useParallax;
  44598. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  44599. }
  44600. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  44601. }
  44602. else {
  44603. defines.BUMP = false;
  44604. }
  44605. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  44606. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  44607. return false;
  44608. }
  44609. else {
  44610. defines._needUVs = true;
  44611. defines.REFRACTION = true;
  44612. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  44613. }
  44614. }
  44615. else {
  44616. defines.REFRACTION = false;
  44617. }
  44618. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  44619. }
  44620. else {
  44621. defines.DIFFUSE = false;
  44622. defines.AMBIENT = false;
  44623. defines.OPACITY = false;
  44624. defines.REFLECTION = false;
  44625. defines.EMISSIVE = false;
  44626. defines.LIGHTMAP = false;
  44627. defines.BUMP = false;
  44628. defines.REFRACTION = false;
  44629. }
  44630. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  44631. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  44632. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  44633. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  44634. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  44635. }
  44636. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  44637. if (!this._imageProcessingConfiguration.isReady()) {
  44638. return false;
  44639. }
  44640. this._imageProcessingConfiguration.prepareDefines(defines);
  44641. defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace);
  44642. defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace);
  44643. }
  44644. if (defines._areFresnelDirty) {
  44645. if (StandardMaterial.FresnelEnabled) {
  44646. // Fresnel
  44647. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  44648. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  44649. this._reflectionFresnelParameters) {
  44650. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  44651. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  44652. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  44653. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  44654. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  44655. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  44656. defines._needNormals = true;
  44657. defines.FRESNEL = true;
  44658. }
  44659. }
  44660. else {
  44661. defines.FRESNEL = false;
  44662. }
  44663. }
  44664. // Misc.
  44665. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  44666. // Attribs
  44667. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  44668. // Values that need to be evaluated on every frame
  44669. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  44670. // Get correct effect
  44671. if (defines.isDirty) {
  44672. defines.markAsProcessed();
  44673. // Fallbacks
  44674. var fallbacks = new BABYLON.EffectFallbacks();
  44675. if (defines.REFLECTION) {
  44676. fallbacks.addFallback(0, "REFLECTION");
  44677. }
  44678. if (defines.SPECULAR) {
  44679. fallbacks.addFallback(0, "SPECULAR");
  44680. }
  44681. if (defines.BUMP) {
  44682. fallbacks.addFallback(0, "BUMP");
  44683. }
  44684. if (defines.PARALLAX) {
  44685. fallbacks.addFallback(1, "PARALLAX");
  44686. }
  44687. if (defines.PARALLAXOCCLUSION) {
  44688. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  44689. }
  44690. if (defines.SPECULAROVERALPHA) {
  44691. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  44692. }
  44693. if (defines.FOG) {
  44694. fallbacks.addFallback(1, "FOG");
  44695. }
  44696. if (defines.POINTSIZE) {
  44697. fallbacks.addFallback(0, "POINTSIZE");
  44698. }
  44699. if (defines.LOGARITHMICDEPTH) {
  44700. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  44701. }
  44702. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  44703. if (defines.SPECULARTERM) {
  44704. fallbacks.addFallback(0, "SPECULARTERM");
  44705. }
  44706. if (defines.DIFFUSEFRESNEL) {
  44707. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  44708. }
  44709. if (defines.OPACITYFRESNEL) {
  44710. fallbacks.addFallback(2, "OPACITYFRESNEL");
  44711. }
  44712. if (defines.REFLECTIONFRESNEL) {
  44713. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  44714. }
  44715. if (defines.EMISSIVEFRESNEL) {
  44716. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  44717. }
  44718. if (defines.FRESNEL) {
  44719. fallbacks.addFallback(4, "FRESNEL");
  44720. }
  44721. //Attributes
  44722. var attribs = [BABYLON.VertexBuffer.PositionKind];
  44723. if (defines.NORMAL) {
  44724. attribs.push(BABYLON.VertexBuffer.NormalKind);
  44725. }
  44726. if (defines.UV1) {
  44727. attribs.push(BABYLON.VertexBuffer.UVKind);
  44728. }
  44729. if (defines.UV2) {
  44730. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  44731. }
  44732. if (defines.VERTEXCOLOR) {
  44733. attribs.push(BABYLON.VertexBuffer.ColorKind);
  44734. }
  44735. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  44736. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  44737. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  44738. var shaderName = "default";
  44739. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  44740. "vFogInfos", "vFogColor", "pointSize",
  44741. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  44742. "mBones",
  44743. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  44744. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  44745. "vReflectionPosition", "vReflectionSize",
  44746. "logarithmicDepthConstant", "vTangentSpaceParams", "alphaCutOff", "boneTextureWidth"
  44747. ];
  44748. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler",
  44749. "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler",
  44750. "refractionCubeSampler", "refraction2DSampler", "boneSampler"];
  44751. var uniformBuffers = ["Material", "Scene"];
  44752. if (BABYLON.ImageProcessingConfiguration) {
  44753. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  44754. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  44755. }
  44756. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  44757. uniformsNames: uniforms,
  44758. uniformBuffersNames: uniformBuffers,
  44759. samplers: samplers,
  44760. defines: defines,
  44761. maxSimultaneousLights: this._maxSimultaneousLights
  44762. });
  44763. if (this.customShaderNameResolve) {
  44764. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  44765. }
  44766. var join = defines.toString();
  44767. var previousEffect = subMesh.effect;
  44768. var effect = scene.getEngine().createEffect(shaderName, {
  44769. attributes: attribs,
  44770. uniformsNames: uniforms,
  44771. uniformBuffersNames: uniformBuffers,
  44772. samplers: samplers,
  44773. defines: join,
  44774. fallbacks: fallbacks,
  44775. onCompiled: this.onCompiled,
  44776. onError: this.onError,
  44777. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  44778. }, engine);
  44779. if (effect) {
  44780. // Use previous effect while new one is compiling
  44781. if (this.allowShaderHotSwapping && previousEffect && !effect.isReady()) {
  44782. effect = previousEffect;
  44783. defines.markAsUnprocessed();
  44784. }
  44785. else {
  44786. scene.resetCachedMaterial();
  44787. subMesh.setEffect(effect, defines);
  44788. this.buildUniformLayout();
  44789. }
  44790. }
  44791. }
  44792. if (!subMesh.effect || !subMesh.effect.isReady()) {
  44793. return false;
  44794. }
  44795. defines._renderId = scene.getRenderId();
  44796. this._wasPreviouslyReady = true;
  44797. return true;
  44798. };
  44799. /**
  44800. * Builds the material UBO layouts.
  44801. * Used internally during the effect preparation.
  44802. */
  44803. StandardMaterial.prototype.buildUniformLayout = function () {
  44804. // Order is important !
  44805. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  44806. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  44807. this._uniformBuffer.addUniform("opacityParts", 4);
  44808. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  44809. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  44810. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  44811. this._uniformBuffer.addUniform("refractionRightColor", 4);
  44812. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  44813. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  44814. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  44815. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  44816. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  44817. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  44818. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  44819. this._uniformBuffer.addUniform("vReflectionSize", 3);
  44820. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  44821. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  44822. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  44823. this._uniformBuffer.addUniform("vBumpInfos", 3);
  44824. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  44825. this._uniformBuffer.addUniform("ambientMatrix", 16);
  44826. this._uniformBuffer.addUniform("opacityMatrix", 16);
  44827. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  44828. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  44829. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  44830. this._uniformBuffer.addUniform("specularMatrix", 16);
  44831. this._uniformBuffer.addUniform("bumpMatrix", 16);
  44832. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  44833. this._uniformBuffer.addUniform("refractionMatrix", 16);
  44834. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  44835. this._uniformBuffer.addUniform("vSpecularColor", 4);
  44836. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  44837. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  44838. this._uniformBuffer.addUniform("pointSize", 1);
  44839. this._uniformBuffer.create();
  44840. };
  44841. /**
  44842. * Unbinds the material from the mesh
  44843. */
  44844. StandardMaterial.prototype.unbind = function () {
  44845. if (this._activeEffect) {
  44846. var needFlag = false;
  44847. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  44848. this._activeEffect.setTexture("reflection2DSampler", null);
  44849. needFlag = true;
  44850. }
  44851. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  44852. this._activeEffect.setTexture("refraction2DSampler", null);
  44853. needFlag = true;
  44854. }
  44855. if (needFlag) {
  44856. this._markAllSubMeshesAsTexturesDirty();
  44857. }
  44858. }
  44859. _super.prototype.unbind.call(this);
  44860. };
  44861. /**
  44862. * Binds the submesh to this material by preparing the effect and shader to draw
  44863. * @param world defines the world transformation matrix
  44864. * @param mesh defines the mesh containing the submesh
  44865. * @param subMesh defines the submesh to bind the material to
  44866. */
  44867. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  44868. var scene = this.getScene();
  44869. var defines = subMesh._materialDefines;
  44870. if (!defines) {
  44871. return;
  44872. }
  44873. var effect = subMesh.effect;
  44874. if (!effect) {
  44875. return;
  44876. }
  44877. this._activeEffect = effect;
  44878. // Matrices
  44879. this.bindOnlyWorldMatrix(world);
  44880. // Normal Matrix
  44881. if (defines.OBJECTSPACE_NORMALMAP) {
  44882. world.toNormalMatrix(this._normalMatrix);
  44883. this.bindOnlyNormalMatrix(this._normalMatrix);
  44884. }
  44885. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  44886. // Bones
  44887. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  44888. if (mustRebind) {
  44889. this._uniformBuffer.bindToEffect(effect, "Material");
  44890. this.bindViewProjection(effect);
  44891. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  44892. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  44893. // Fresnel
  44894. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  44895. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  44896. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  44897. }
  44898. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  44899. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  44900. }
  44901. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  44902. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  44903. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  44904. }
  44905. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  44906. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  44907. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  44908. }
  44909. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  44910. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  44911. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  44912. }
  44913. }
  44914. // Textures
  44915. if (scene.texturesEnabled) {
  44916. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  44917. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  44918. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  44919. if (this._diffuseTexture.hasAlpha) {
  44920. effect.setFloat("alphaCutOff", this.alphaCutOff);
  44921. }
  44922. }
  44923. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  44924. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  44925. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  44926. }
  44927. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  44928. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  44929. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  44930. }
  44931. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  44932. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  44933. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  44934. if (this._reflectionTexture.boundingBoxSize) {
  44935. var cubeTexture = this._reflectionTexture;
  44936. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  44937. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  44938. }
  44939. }
  44940. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  44941. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  44942. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  44943. }
  44944. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  44945. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  44946. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  44947. }
  44948. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  44949. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  44950. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  44951. }
  44952. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  44953. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  44954. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  44955. if (scene._mirroredCameraPosition) {
  44956. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  44957. }
  44958. else {
  44959. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  44960. }
  44961. }
  44962. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  44963. var depth = 1.0;
  44964. if (!this._refractionTexture.isCube) {
  44965. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  44966. if (this._refractionTexture.depth) {
  44967. depth = this._refractionTexture.depth;
  44968. }
  44969. }
  44970. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  44971. }
  44972. }
  44973. // Point size
  44974. if (this.pointsCloud) {
  44975. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  44976. }
  44977. if (defines.SPECULARTERM) {
  44978. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  44979. }
  44980. this._uniformBuffer.updateColor3("vEmissiveColor", StandardMaterial.EmissiveTextureEnabled ? this.emissiveColor : BABYLON.Color3.BlackReadOnly);
  44981. // Diffuse
  44982. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  44983. }
  44984. // Textures
  44985. if (scene.texturesEnabled) {
  44986. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  44987. effect.setTexture("diffuseSampler", this._diffuseTexture);
  44988. }
  44989. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  44990. effect.setTexture("ambientSampler", this._ambientTexture);
  44991. }
  44992. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  44993. effect.setTexture("opacitySampler", this._opacityTexture);
  44994. }
  44995. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  44996. if (this._reflectionTexture.isCube) {
  44997. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  44998. }
  44999. else {
  45000. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  45001. }
  45002. }
  45003. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  45004. effect.setTexture("emissiveSampler", this._emissiveTexture);
  45005. }
  45006. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  45007. effect.setTexture("lightmapSampler", this._lightmapTexture);
  45008. }
  45009. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  45010. effect.setTexture("specularSampler", this._specularTexture);
  45011. }
  45012. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  45013. effect.setTexture("bumpSampler", this._bumpTexture);
  45014. }
  45015. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  45016. var depth = 1.0;
  45017. if (this._refractionTexture.isCube) {
  45018. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  45019. }
  45020. else {
  45021. effect.setTexture("refraction2DSampler", this._refractionTexture);
  45022. }
  45023. }
  45024. }
  45025. // Clip plane
  45026. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  45027. // Colors
  45028. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  45029. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  45030. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  45031. }
  45032. if (mustRebind || !this.isFrozen) {
  45033. // Lights
  45034. if (scene.lightsEnabled && !this._disableLighting) {
  45035. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  45036. }
  45037. // View
  45038. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  45039. this.bindView(effect);
  45040. }
  45041. // Fog
  45042. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  45043. // Morph targets
  45044. if (defines.NUM_MORPH_INFLUENCERS) {
  45045. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  45046. }
  45047. // Log. depth
  45048. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  45049. // image processing
  45050. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  45051. this._imageProcessingConfiguration.bind(this._activeEffect);
  45052. }
  45053. }
  45054. this._uniformBuffer.update();
  45055. this._afterBind(mesh, this._activeEffect);
  45056. };
  45057. /**
  45058. * Get the list of animatables in the material.
  45059. * @returns the list of animatables object used in the material
  45060. */
  45061. StandardMaterial.prototype.getAnimatables = function () {
  45062. var results = [];
  45063. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  45064. results.push(this._diffuseTexture);
  45065. }
  45066. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  45067. results.push(this._ambientTexture);
  45068. }
  45069. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  45070. results.push(this._opacityTexture);
  45071. }
  45072. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  45073. results.push(this._reflectionTexture);
  45074. }
  45075. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  45076. results.push(this._emissiveTexture);
  45077. }
  45078. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  45079. results.push(this._specularTexture);
  45080. }
  45081. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  45082. results.push(this._bumpTexture);
  45083. }
  45084. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  45085. results.push(this._lightmapTexture);
  45086. }
  45087. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  45088. results.push(this._refractionTexture);
  45089. }
  45090. return results;
  45091. };
  45092. /**
  45093. * Gets the active textures from the material
  45094. * @returns an array of textures
  45095. */
  45096. StandardMaterial.prototype.getActiveTextures = function () {
  45097. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45098. if (this._diffuseTexture) {
  45099. activeTextures.push(this._diffuseTexture);
  45100. }
  45101. if (this._ambientTexture) {
  45102. activeTextures.push(this._ambientTexture);
  45103. }
  45104. if (this._opacityTexture) {
  45105. activeTextures.push(this._opacityTexture);
  45106. }
  45107. if (this._reflectionTexture) {
  45108. activeTextures.push(this._reflectionTexture);
  45109. }
  45110. if (this._emissiveTexture) {
  45111. activeTextures.push(this._emissiveTexture);
  45112. }
  45113. if (this._specularTexture) {
  45114. activeTextures.push(this._specularTexture);
  45115. }
  45116. if (this._bumpTexture) {
  45117. activeTextures.push(this._bumpTexture);
  45118. }
  45119. if (this._lightmapTexture) {
  45120. activeTextures.push(this._lightmapTexture);
  45121. }
  45122. if (this._refractionTexture) {
  45123. activeTextures.push(this._refractionTexture);
  45124. }
  45125. return activeTextures;
  45126. };
  45127. /**
  45128. * Specifies if the material uses a texture
  45129. * @param texture defines the texture to check against the material
  45130. * @returns a boolean specifying if the material uses the texture
  45131. */
  45132. StandardMaterial.prototype.hasTexture = function (texture) {
  45133. if (_super.prototype.hasTexture.call(this, texture)) {
  45134. return true;
  45135. }
  45136. if (this._diffuseTexture === texture) {
  45137. return true;
  45138. }
  45139. if (this._ambientTexture === texture) {
  45140. return true;
  45141. }
  45142. if (this._opacityTexture === texture) {
  45143. return true;
  45144. }
  45145. if (this._reflectionTexture === texture) {
  45146. return true;
  45147. }
  45148. if (this._emissiveTexture === texture) {
  45149. return true;
  45150. }
  45151. if (this._specularTexture === texture) {
  45152. return true;
  45153. }
  45154. if (this._bumpTexture === texture) {
  45155. return true;
  45156. }
  45157. if (this._lightmapTexture === texture) {
  45158. return true;
  45159. }
  45160. if (this._refractionTexture === texture) {
  45161. return true;
  45162. }
  45163. return false;
  45164. };
  45165. /**
  45166. * Disposes the material
  45167. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  45168. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  45169. */
  45170. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  45171. if (forceDisposeTextures) {
  45172. if (this._diffuseTexture) {
  45173. this._diffuseTexture.dispose();
  45174. }
  45175. if (this._ambientTexture) {
  45176. this._ambientTexture.dispose();
  45177. }
  45178. if (this._opacityTexture) {
  45179. this._opacityTexture.dispose();
  45180. }
  45181. if (this._reflectionTexture) {
  45182. this._reflectionTexture.dispose();
  45183. }
  45184. if (this._emissiveTexture) {
  45185. this._emissiveTexture.dispose();
  45186. }
  45187. if (this._specularTexture) {
  45188. this._specularTexture.dispose();
  45189. }
  45190. if (this._bumpTexture) {
  45191. this._bumpTexture.dispose();
  45192. }
  45193. if (this._lightmapTexture) {
  45194. this._lightmapTexture.dispose();
  45195. }
  45196. if (this._refractionTexture) {
  45197. this._refractionTexture.dispose();
  45198. }
  45199. }
  45200. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  45201. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  45202. }
  45203. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  45204. };
  45205. /**
  45206. * Makes a duplicate of the material, and gives it a new name
  45207. * @param name defines the new name for the duplicated material
  45208. * @returns the cloned material
  45209. */
  45210. StandardMaterial.prototype.clone = function (name) {
  45211. var _this = this;
  45212. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  45213. result.name = name;
  45214. result.id = name;
  45215. return result;
  45216. };
  45217. /**
  45218. * Serializes this material in a JSON representation
  45219. * @returns the serialized material object
  45220. */
  45221. StandardMaterial.prototype.serialize = function () {
  45222. return BABYLON.SerializationHelper.Serialize(this);
  45223. };
  45224. /**
  45225. * Creates a standard material from parsed material data
  45226. * @param source defines the JSON representation of the material
  45227. * @param scene defines the hosting scene
  45228. * @param rootUrl defines the root URL to use to load textures and relative dependencies
  45229. * @returns a new standard material
  45230. */
  45231. StandardMaterial.Parse = function (source, scene, rootUrl) {
  45232. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  45233. };
  45234. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  45235. /**
  45236. * Are diffuse textures enabled in the application.
  45237. */
  45238. get: function () {
  45239. return StandardMaterial._DiffuseTextureEnabled;
  45240. },
  45241. set: function (value) {
  45242. if (StandardMaterial._DiffuseTextureEnabled === value) {
  45243. return;
  45244. }
  45245. StandardMaterial._DiffuseTextureEnabled = value;
  45246. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  45247. },
  45248. enumerable: true,
  45249. configurable: true
  45250. });
  45251. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  45252. /**
  45253. * Are ambient textures enabled in the application.
  45254. */
  45255. get: function () {
  45256. return StandardMaterial._AmbientTextureEnabled;
  45257. },
  45258. set: function (value) {
  45259. if (StandardMaterial._AmbientTextureEnabled === value) {
  45260. return;
  45261. }
  45262. StandardMaterial._AmbientTextureEnabled = value;
  45263. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  45264. },
  45265. enumerable: true,
  45266. configurable: true
  45267. });
  45268. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  45269. /**
  45270. * Are opacity textures enabled in the application.
  45271. */
  45272. get: function () {
  45273. return StandardMaterial._OpacityTextureEnabled;
  45274. },
  45275. set: function (value) {
  45276. if (StandardMaterial._OpacityTextureEnabled === value) {
  45277. return;
  45278. }
  45279. StandardMaterial._OpacityTextureEnabled = value;
  45280. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  45281. },
  45282. enumerable: true,
  45283. configurable: true
  45284. });
  45285. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  45286. /**
  45287. * Are reflection textures enabled in the application.
  45288. */
  45289. get: function () {
  45290. return StandardMaterial._ReflectionTextureEnabled;
  45291. },
  45292. set: function (value) {
  45293. if (StandardMaterial._ReflectionTextureEnabled === value) {
  45294. return;
  45295. }
  45296. StandardMaterial._ReflectionTextureEnabled = value;
  45297. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  45298. },
  45299. enumerable: true,
  45300. configurable: true
  45301. });
  45302. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  45303. /**
  45304. * Are emissive textures enabled in the application.
  45305. */
  45306. get: function () {
  45307. return StandardMaterial._EmissiveTextureEnabled;
  45308. },
  45309. set: function (value) {
  45310. if (StandardMaterial._EmissiveTextureEnabled === value) {
  45311. return;
  45312. }
  45313. StandardMaterial._EmissiveTextureEnabled = value;
  45314. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  45315. },
  45316. enumerable: true,
  45317. configurable: true
  45318. });
  45319. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  45320. /**
  45321. * Are specular textures enabled in the application.
  45322. */
  45323. get: function () {
  45324. return StandardMaterial._SpecularTextureEnabled;
  45325. },
  45326. set: function (value) {
  45327. if (StandardMaterial._SpecularTextureEnabled === value) {
  45328. return;
  45329. }
  45330. StandardMaterial._SpecularTextureEnabled = value;
  45331. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  45332. },
  45333. enumerable: true,
  45334. configurable: true
  45335. });
  45336. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  45337. /**
  45338. * Are bump textures enabled in the application.
  45339. */
  45340. get: function () {
  45341. return StandardMaterial._BumpTextureEnabled;
  45342. },
  45343. set: function (value) {
  45344. if (StandardMaterial._BumpTextureEnabled === value) {
  45345. return;
  45346. }
  45347. StandardMaterial._BumpTextureEnabled = value;
  45348. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  45349. },
  45350. enumerable: true,
  45351. configurable: true
  45352. });
  45353. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  45354. /**
  45355. * Are lightmap textures enabled in the application.
  45356. */
  45357. get: function () {
  45358. return StandardMaterial._LightmapTextureEnabled;
  45359. },
  45360. set: function (value) {
  45361. if (StandardMaterial._LightmapTextureEnabled === value) {
  45362. return;
  45363. }
  45364. StandardMaterial._LightmapTextureEnabled = value;
  45365. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  45366. },
  45367. enumerable: true,
  45368. configurable: true
  45369. });
  45370. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  45371. /**
  45372. * Are refraction textures enabled in the application.
  45373. */
  45374. get: function () {
  45375. return StandardMaterial._RefractionTextureEnabled;
  45376. },
  45377. set: function (value) {
  45378. if (StandardMaterial._RefractionTextureEnabled === value) {
  45379. return;
  45380. }
  45381. StandardMaterial._RefractionTextureEnabled = value;
  45382. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  45383. },
  45384. enumerable: true,
  45385. configurable: true
  45386. });
  45387. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  45388. /**
  45389. * Are color grading textures enabled in the application.
  45390. */
  45391. get: function () {
  45392. return StandardMaterial._ColorGradingTextureEnabled;
  45393. },
  45394. set: function (value) {
  45395. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  45396. return;
  45397. }
  45398. StandardMaterial._ColorGradingTextureEnabled = value;
  45399. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  45400. },
  45401. enumerable: true,
  45402. configurable: true
  45403. });
  45404. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  45405. /**
  45406. * Are fresnels enabled in the application.
  45407. */
  45408. get: function () {
  45409. return StandardMaterial._FresnelEnabled;
  45410. },
  45411. set: function (value) {
  45412. if (StandardMaterial._FresnelEnabled === value) {
  45413. return;
  45414. }
  45415. StandardMaterial._FresnelEnabled = value;
  45416. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  45417. },
  45418. enumerable: true,
  45419. configurable: true
  45420. });
  45421. // Flags used to enable or disable a type of texture for all Standard Materials
  45422. StandardMaterial._DiffuseTextureEnabled = true;
  45423. StandardMaterial._AmbientTextureEnabled = true;
  45424. StandardMaterial._OpacityTextureEnabled = true;
  45425. StandardMaterial._ReflectionTextureEnabled = true;
  45426. StandardMaterial._EmissiveTextureEnabled = true;
  45427. StandardMaterial._SpecularTextureEnabled = true;
  45428. StandardMaterial._BumpTextureEnabled = true;
  45429. StandardMaterial._LightmapTextureEnabled = true;
  45430. StandardMaterial._RefractionTextureEnabled = true;
  45431. StandardMaterial._ColorGradingTextureEnabled = true;
  45432. StandardMaterial._FresnelEnabled = true;
  45433. __decorate([
  45434. BABYLON.serializeAsTexture("diffuseTexture")
  45435. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  45436. __decorate([
  45437. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45438. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  45439. __decorate([
  45440. BABYLON.serializeAsTexture("ambientTexture")
  45441. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  45442. __decorate([
  45443. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45444. ], StandardMaterial.prototype, "ambientTexture", void 0);
  45445. __decorate([
  45446. BABYLON.serializeAsTexture("opacityTexture")
  45447. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  45448. __decorate([
  45449. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45450. ], StandardMaterial.prototype, "opacityTexture", void 0);
  45451. __decorate([
  45452. BABYLON.serializeAsTexture("reflectionTexture")
  45453. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  45454. __decorate([
  45455. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45456. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  45457. __decorate([
  45458. BABYLON.serializeAsTexture("emissiveTexture")
  45459. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  45460. __decorate([
  45461. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45462. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  45463. __decorate([
  45464. BABYLON.serializeAsTexture("specularTexture")
  45465. ], StandardMaterial.prototype, "_specularTexture", void 0);
  45466. __decorate([
  45467. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45468. ], StandardMaterial.prototype, "specularTexture", void 0);
  45469. __decorate([
  45470. BABYLON.serializeAsTexture("bumpTexture")
  45471. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  45472. __decorate([
  45473. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45474. ], StandardMaterial.prototype, "bumpTexture", void 0);
  45475. __decorate([
  45476. BABYLON.serializeAsTexture("lightmapTexture")
  45477. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  45478. __decorate([
  45479. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45480. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  45481. __decorate([
  45482. BABYLON.serializeAsTexture("refractionTexture")
  45483. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  45484. __decorate([
  45485. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45486. ], StandardMaterial.prototype, "refractionTexture", void 0);
  45487. __decorate([
  45488. BABYLON.serializeAsColor3("ambient")
  45489. ], StandardMaterial.prototype, "ambientColor", void 0);
  45490. __decorate([
  45491. BABYLON.serializeAsColor3("diffuse")
  45492. ], StandardMaterial.prototype, "diffuseColor", void 0);
  45493. __decorate([
  45494. BABYLON.serializeAsColor3("specular")
  45495. ], StandardMaterial.prototype, "specularColor", void 0);
  45496. __decorate([
  45497. BABYLON.serializeAsColor3("emissive")
  45498. ], StandardMaterial.prototype, "emissiveColor", void 0);
  45499. __decorate([
  45500. BABYLON.serialize()
  45501. ], StandardMaterial.prototype, "specularPower", void 0);
  45502. __decorate([
  45503. BABYLON.serialize("useAlphaFromDiffuseTexture")
  45504. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  45505. __decorate([
  45506. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45507. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  45508. __decorate([
  45509. BABYLON.serialize("useEmissiveAsIllumination")
  45510. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  45511. __decorate([
  45512. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45513. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  45514. __decorate([
  45515. BABYLON.serialize("linkEmissiveWithDiffuse")
  45516. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  45517. __decorate([
  45518. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45519. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  45520. __decorate([
  45521. BABYLON.serialize("useSpecularOverAlpha")
  45522. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  45523. __decorate([
  45524. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45525. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  45526. __decorate([
  45527. BABYLON.serialize("useReflectionOverAlpha")
  45528. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  45529. __decorate([
  45530. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45531. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  45532. __decorate([
  45533. BABYLON.serialize("disableLighting")
  45534. ], StandardMaterial.prototype, "_disableLighting", void 0);
  45535. __decorate([
  45536. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45537. ], StandardMaterial.prototype, "disableLighting", void 0);
  45538. __decorate([
  45539. BABYLON.serialize("useObjectSpaceNormalMap")
  45540. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  45541. __decorate([
  45542. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45543. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  45544. __decorate([
  45545. BABYLON.serialize("useParallax")
  45546. ], StandardMaterial.prototype, "_useParallax", void 0);
  45547. __decorate([
  45548. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45549. ], StandardMaterial.prototype, "useParallax", void 0);
  45550. __decorate([
  45551. BABYLON.serialize("useParallaxOcclusion")
  45552. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  45553. __decorate([
  45554. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45555. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  45556. __decorate([
  45557. BABYLON.serialize()
  45558. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  45559. __decorate([
  45560. BABYLON.serialize("roughness")
  45561. ], StandardMaterial.prototype, "_roughness", void 0);
  45562. __decorate([
  45563. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45564. ], StandardMaterial.prototype, "roughness", void 0);
  45565. __decorate([
  45566. BABYLON.serialize()
  45567. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  45568. __decorate([
  45569. BABYLON.serialize()
  45570. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  45571. __decorate([
  45572. BABYLON.serialize()
  45573. ], StandardMaterial.prototype, "alphaCutOff", void 0);
  45574. __decorate([
  45575. BABYLON.serialize("useLightmapAsShadowmap")
  45576. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  45577. __decorate([
  45578. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45579. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45580. __decorate([
  45581. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  45582. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  45583. __decorate([
  45584. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  45585. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  45586. __decorate([
  45587. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  45588. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  45589. __decorate([
  45590. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  45591. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  45592. __decorate([
  45593. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  45594. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  45595. __decorate([
  45596. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  45597. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  45598. __decorate([
  45599. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  45600. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  45601. __decorate([
  45602. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  45603. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  45604. __decorate([
  45605. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  45606. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  45607. __decorate([
  45608. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  45609. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  45610. __decorate([
  45611. BABYLON.serialize("useReflectionFresnelFromSpecular")
  45612. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  45613. __decorate([
  45614. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  45615. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  45616. __decorate([
  45617. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  45618. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  45619. __decorate([
  45620. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45621. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  45622. __decorate([
  45623. BABYLON.serialize("maxSimultaneousLights")
  45624. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  45625. __decorate([
  45626. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45627. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  45628. __decorate([
  45629. BABYLON.serialize("invertNormalMapX")
  45630. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  45631. __decorate([
  45632. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45633. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  45634. __decorate([
  45635. BABYLON.serialize("invertNormalMapY")
  45636. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  45637. __decorate([
  45638. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45639. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  45640. __decorate([
  45641. BABYLON.serialize("twoSidedLighting")
  45642. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  45643. __decorate([
  45644. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45645. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  45646. __decorate([
  45647. BABYLON.serialize()
  45648. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  45649. return StandardMaterial;
  45650. }(BABYLON.PushMaterial));
  45651. BABYLON.StandardMaterial = StandardMaterial;
  45652. })(BABYLON || (BABYLON = {}));
  45653. //# sourceMappingURL=babylon.standardMaterial.js.map
  45654. var BABYLON;
  45655. (function (BABYLON) {
  45656. /**
  45657. * Class representing spherical polynomial coefficients to the 3rd degree
  45658. */
  45659. var SphericalPolynomial = /** @class */ (function () {
  45660. function SphericalPolynomial() {
  45661. /**
  45662. * The x coefficients of the spherical polynomial
  45663. */
  45664. this.x = BABYLON.Vector3.Zero();
  45665. /**
  45666. * The y coefficients of the spherical polynomial
  45667. */
  45668. this.y = BABYLON.Vector3.Zero();
  45669. /**
  45670. * The z coefficients of the spherical polynomial
  45671. */
  45672. this.z = BABYLON.Vector3.Zero();
  45673. /**
  45674. * The xx coefficients of the spherical polynomial
  45675. */
  45676. this.xx = BABYLON.Vector3.Zero();
  45677. /**
  45678. * The yy coefficients of the spherical polynomial
  45679. */
  45680. this.yy = BABYLON.Vector3.Zero();
  45681. /**
  45682. * The zz coefficients of the spherical polynomial
  45683. */
  45684. this.zz = BABYLON.Vector3.Zero();
  45685. /**
  45686. * The xy coefficients of the spherical polynomial
  45687. */
  45688. this.xy = BABYLON.Vector3.Zero();
  45689. /**
  45690. * The yz coefficients of the spherical polynomial
  45691. */
  45692. this.yz = BABYLON.Vector3.Zero();
  45693. /**
  45694. * The zx coefficients of the spherical polynomial
  45695. */
  45696. this.zx = BABYLON.Vector3.Zero();
  45697. }
  45698. /**
  45699. * Adds an ambient color to the spherical polynomial
  45700. * @param color the color to add
  45701. */
  45702. SphericalPolynomial.prototype.addAmbient = function (color) {
  45703. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  45704. this.xx = this.xx.add(colorVector);
  45705. this.yy = this.yy.add(colorVector);
  45706. this.zz = this.zz.add(colorVector);
  45707. };
  45708. /**
  45709. * Scales the spherical polynomial by the given amount
  45710. * @param scale the amount to scale
  45711. */
  45712. SphericalPolynomial.prototype.scale = function (scale) {
  45713. this.x = this.x.scale(scale);
  45714. this.y = this.y.scale(scale);
  45715. this.z = this.z.scale(scale);
  45716. this.xx = this.xx.scale(scale);
  45717. this.yy = this.yy.scale(scale);
  45718. this.zz = this.zz.scale(scale);
  45719. this.yz = this.yz.scale(scale);
  45720. this.zx = this.zx.scale(scale);
  45721. this.xy = this.xy.scale(scale);
  45722. };
  45723. /**
  45724. * Gets the spherical polynomial from harmonics
  45725. * @param harmonics the spherical harmonics
  45726. * @returns the spherical polynomial
  45727. */
  45728. SphericalPolynomial.FromHarmonics = function (harmonics) {
  45729. var result = new SphericalPolynomial();
  45730. result.x = harmonics.l11.scale(1.02333);
  45731. result.y = harmonics.l1_1.scale(1.02333);
  45732. result.z = harmonics.l10.scale(1.02333);
  45733. result.xx = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).add(harmonics.lL22.scale(0.429043));
  45734. result.yy = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).subtract(harmonics.lL22.scale(0.429043));
  45735. result.zz = harmonics.l00.scale(0.886277).add(harmonics.l20.scale(0.495417));
  45736. result.yz = harmonics.l2_1.scale(0.858086);
  45737. result.zx = harmonics.l21.scale(0.858086);
  45738. result.xy = harmonics.l2_2.scale(0.858086);
  45739. result.scale(1.0 / Math.PI);
  45740. return result;
  45741. };
  45742. /**
  45743. * Constructs a spherical polynomial from an array.
  45744. * @param data defines the 9x3 coefficients (x, y, z, xx, yy, zz, yz, zx, xy)
  45745. * @returns the spherical polynomial
  45746. */
  45747. SphericalPolynomial.FromArray = function (data) {
  45748. var sp = new SphericalPolynomial();
  45749. BABYLON.Vector3.FromArrayToRef(data[0], 0, sp.x);
  45750. BABYLON.Vector3.FromArrayToRef(data[1], 0, sp.y);
  45751. BABYLON.Vector3.FromArrayToRef(data[2], 0, sp.z);
  45752. BABYLON.Vector3.FromArrayToRef(data[3], 0, sp.xx);
  45753. BABYLON.Vector3.FromArrayToRef(data[4], 0, sp.yy);
  45754. BABYLON.Vector3.FromArrayToRef(data[5], 0, sp.zz);
  45755. BABYLON.Vector3.FromArrayToRef(data[6], 0, sp.yz);
  45756. BABYLON.Vector3.FromArrayToRef(data[7], 0, sp.zx);
  45757. BABYLON.Vector3.FromArrayToRef(data[8], 0, sp.xy);
  45758. return sp;
  45759. };
  45760. return SphericalPolynomial;
  45761. }());
  45762. BABYLON.SphericalPolynomial = SphericalPolynomial;
  45763. /**
  45764. * Class representing spherical harmonics coefficients to the 3rd degree
  45765. */
  45766. var SphericalHarmonics = /** @class */ (function () {
  45767. function SphericalHarmonics() {
  45768. /**
  45769. * The l0,0 coefficients of the spherical harmonics
  45770. */
  45771. this.l00 = BABYLON.Vector3.Zero();
  45772. /**
  45773. * The l1,-1 coefficients of the spherical harmonics
  45774. */
  45775. this.l1_1 = BABYLON.Vector3.Zero();
  45776. /**
  45777. * The l1,0 coefficients of the spherical harmonics
  45778. */
  45779. this.l10 = BABYLON.Vector3.Zero();
  45780. /**
  45781. * The l1,1 coefficients of the spherical harmonics
  45782. */
  45783. this.l11 = BABYLON.Vector3.Zero();
  45784. /**
  45785. * The l2,-2 coefficients of the spherical harmonics
  45786. */
  45787. this.l2_2 = BABYLON.Vector3.Zero();
  45788. /**
  45789. * The l2,-1 coefficients of the spherical harmonics
  45790. */
  45791. this.l2_1 = BABYLON.Vector3.Zero();
  45792. /**
  45793. * The l2,0 coefficients of the spherical harmonics
  45794. */
  45795. this.l20 = BABYLON.Vector3.Zero();
  45796. /**
  45797. * The l2,1 coefficients of the spherical harmonics
  45798. */
  45799. this.l21 = BABYLON.Vector3.Zero();
  45800. /**
  45801. * The l2,2 coefficients of the spherical harmonics
  45802. */
  45803. this.lL22 = BABYLON.Vector3.Zero();
  45804. }
  45805. /**
  45806. * Adds a light to the spherical harmonics
  45807. * @param direction the direction of the light
  45808. * @param color the color of the light
  45809. * @param deltaSolidAngle the delta solid angle of the light
  45810. */
  45811. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  45812. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  45813. var c = colorVector.scale(deltaSolidAngle);
  45814. this.l00 = this.l00.add(c.scale(0.282095));
  45815. this.l1_1 = this.l1_1.add(c.scale(0.488603 * direction.y));
  45816. this.l10 = this.l10.add(c.scale(0.488603 * direction.z));
  45817. this.l11 = this.l11.add(c.scale(0.488603 * direction.x));
  45818. this.l2_2 = this.l2_2.add(c.scale(1.092548 * direction.x * direction.y));
  45819. this.l2_1 = this.l2_1.add(c.scale(1.092548 * direction.y * direction.z));
  45820. this.l21 = this.l21.add(c.scale(1.092548 * direction.x * direction.z));
  45821. this.l20 = this.l20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  45822. this.lL22 = this.lL22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  45823. };
  45824. /**
  45825. * Scales the spherical harmonics by the given amount
  45826. * @param scale the amount to scale
  45827. */
  45828. SphericalHarmonics.prototype.scale = function (scale) {
  45829. this.l00 = this.l00.scale(scale);
  45830. this.l1_1 = this.l1_1.scale(scale);
  45831. this.l10 = this.l10.scale(scale);
  45832. this.l11 = this.l11.scale(scale);
  45833. this.l2_2 = this.l2_2.scale(scale);
  45834. this.l2_1 = this.l2_1.scale(scale);
  45835. this.l20 = this.l20.scale(scale);
  45836. this.l21 = this.l21.scale(scale);
  45837. this.lL22 = this.lL22.scale(scale);
  45838. };
  45839. /**
  45840. * Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  45841. *
  45842. * ```
  45843. * E_lm = A_l * L_lm
  45844. * ```
  45845. *
  45846. * In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  45847. * This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  45848. * the scaling factors are given in equation 9.
  45849. */
  45850. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  45851. // Constant (Band 0)
  45852. this.l00 = this.l00.scale(3.141593);
  45853. // Linear (Band 1)
  45854. this.l1_1 = this.l1_1.scale(2.094395);
  45855. this.l10 = this.l10.scale(2.094395);
  45856. this.l11 = this.l11.scale(2.094395);
  45857. // Quadratic (Band 2)
  45858. this.l2_2 = this.l2_2.scale(0.785398);
  45859. this.l2_1 = this.l2_1.scale(0.785398);
  45860. this.l20 = this.l20.scale(0.785398);
  45861. this.l21 = this.l21.scale(0.785398);
  45862. this.lL22 = this.lL22.scale(0.785398);
  45863. };
  45864. /**
  45865. * Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  45866. *
  45867. * ```
  45868. * L = (1/pi) * E * rho
  45869. * ```
  45870. *
  45871. * This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  45872. */
  45873. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  45874. this.scale(1.0 / Math.PI);
  45875. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  45876. // (The pixel shader must apply albedo after texture fetches, etc).
  45877. };
  45878. /**
  45879. * Gets the spherical harmonics from polynomial
  45880. * @param polynomial the spherical polynomial
  45881. * @returns the spherical harmonics
  45882. */
  45883. SphericalHarmonics.FromPolynomial = function (polynomial) {
  45884. var result = new SphericalHarmonics();
  45885. result.l00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  45886. result.l1_1 = polynomial.y.scale(0.977204);
  45887. result.l10 = polynomial.z.scale(0.977204);
  45888. result.l11 = polynomial.x.scale(0.977204);
  45889. result.l2_2 = polynomial.xy.scale(1.16538);
  45890. result.l2_1 = polynomial.yz.scale(1.16538);
  45891. result.l20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  45892. result.l21 = polynomial.zx.scale(1.16538);
  45893. result.lL22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  45894. result.scale(Math.PI);
  45895. return result;
  45896. };
  45897. /**
  45898. * Constructs a spherical harmonics from an array.
  45899. * @param data defines the 9x3 coefficients (l00, l1-1, l10, l11, l2-2, l2-1, l20, l21, l22)
  45900. * @returns the spherical harmonics
  45901. */
  45902. SphericalHarmonics.FromArray = function (data) {
  45903. var sh = new SphericalHarmonics();
  45904. BABYLON.Vector3.FromArrayToRef(data[0], 0, sh.l00);
  45905. BABYLON.Vector3.FromArrayToRef(data[1], 0, sh.l1_1);
  45906. BABYLON.Vector3.FromArrayToRef(data[2], 0, sh.l10);
  45907. BABYLON.Vector3.FromArrayToRef(data[3], 0, sh.l11);
  45908. BABYLON.Vector3.FromArrayToRef(data[4], 0, sh.l2_2);
  45909. BABYLON.Vector3.FromArrayToRef(data[5], 0, sh.l2_1);
  45910. BABYLON.Vector3.FromArrayToRef(data[6], 0, sh.l20);
  45911. BABYLON.Vector3.FromArrayToRef(data[7], 0, sh.l21);
  45912. BABYLON.Vector3.FromArrayToRef(data[8], 0, sh.lL22);
  45913. return sh;
  45914. };
  45915. return SphericalHarmonics;
  45916. }());
  45917. BABYLON.SphericalHarmonics = SphericalHarmonics;
  45918. })(BABYLON || (BABYLON = {}));
  45919. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  45920. var BABYLON;
  45921. (function (BABYLON) {
  45922. var FileFaceOrientation = /** @class */ (function () {
  45923. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  45924. this.name = name;
  45925. this.worldAxisForNormal = worldAxisForNormal;
  45926. this.worldAxisForFileX = worldAxisForFileX;
  45927. this.worldAxisForFileY = worldAxisForFileY;
  45928. }
  45929. return FileFaceOrientation;
  45930. }());
  45931. /**
  45932. * Helper class dealing with the extraction of spherical polynomial dataArray
  45933. * from a cube map.
  45934. */
  45935. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  45936. function CubeMapToSphericalPolynomialTools() {
  45937. }
  45938. /**
  45939. * Converts a texture to the according Spherical Polynomial data.
  45940. * This extracts the first 3 orders only as they are the only one used in the lighting.
  45941. *
  45942. * @param texture The texture to extract the information from.
  45943. * @return The Spherical Polynomial data.
  45944. */
  45945. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  45946. if (!texture.isCube) {
  45947. // Only supports cube Textures currently.
  45948. return null;
  45949. }
  45950. var size = texture.getSize().width;
  45951. var right = texture.readPixels(0);
  45952. var left = texture.readPixels(1);
  45953. var up;
  45954. var down;
  45955. if (texture.isRenderTarget) {
  45956. up = texture.readPixels(3);
  45957. down = texture.readPixels(2);
  45958. }
  45959. else {
  45960. up = texture.readPixels(2);
  45961. down = texture.readPixels(3);
  45962. }
  45963. var front = texture.readPixels(4);
  45964. var back = texture.readPixels(5);
  45965. var gammaSpace = texture.gammaSpace;
  45966. // Always read as RGBA.
  45967. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  45968. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  45969. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  45970. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  45971. }
  45972. var cubeInfo = {
  45973. size: size,
  45974. right: right,
  45975. left: left,
  45976. up: up,
  45977. down: down,
  45978. front: front,
  45979. back: back,
  45980. format: format,
  45981. type: type,
  45982. gammaSpace: gammaSpace,
  45983. };
  45984. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  45985. };
  45986. /**
  45987. * Converts a cubemap to the according Spherical Polynomial data.
  45988. * This extracts the first 3 orders only as they are the only one used in the lighting.
  45989. *
  45990. * @param cubeInfo The Cube map to extract the information from.
  45991. * @return The Spherical Polynomial data.
  45992. */
  45993. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  45994. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  45995. var totalSolidAngle = 0.0;
  45996. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  45997. var du = 2.0 / cubeInfo.size;
  45998. var dv = du;
  45999. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  46000. var minUV = du * 0.5 - 1.0;
  46001. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  46002. var fileFace = this.FileFaces[faceIndex];
  46003. var dataArray = cubeInfo[fileFace.name];
  46004. var v = minUV;
  46005. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  46006. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  46007. // Because SP is still linear, so summation is fine in that basis.
  46008. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  46009. for (var y = 0; y < cubeInfo.size; y++) {
  46010. var u = minUV;
  46011. for (var x = 0; x < cubeInfo.size; x++) {
  46012. // World direction (not normalised)
  46013. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  46014. worldDirection.normalize();
  46015. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  46016. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  46017. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  46018. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  46019. // Handle Integer types.
  46020. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  46021. r /= 255;
  46022. g /= 255;
  46023. b /= 255;
  46024. }
  46025. // Handle Gamma space textures.
  46026. if (cubeInfo.gammaSpace) {
  46027. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  46028. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  46029. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  46030. }
  46031. var color = new BABYLON.Color3(r, g, b);
  46032. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  46033. totalSolidAngle += deltaSolidAngle;
  46034. u += du;
  46035. }
  46036. v += dv;
  46037. }
  46038. }
  46039. // Solid angle for entire sphere is 4*pi
  46040. var sphereSolidAngle = 4.0 * Math.PI;
  46041. // Adjust the solid angle to allow for how many faces we processed.
  46042. var facesProcessed = 6.0;
  46043. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  46044. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  46045. // This is needed because the numerical integration over the cube uses a
  46046. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  46047. // and also to compensate for accumulative error due to float precision in the summation.
  46048. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  46049. sphericalHarmonics.scale(correctionFactor);
  46050. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  46051. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  46052. return BABYLON.SphericalPolynomial.FromHarmonics(sphericalHarmonics);
  46053. };
  46054. CubeMapToSphericalPolynomialTools.FileFaces = [
  46055. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  46056. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  46057. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  46058. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  46059. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  46060. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  46061. ];
  46062. return CubeMapToSphericalPolynomialTools;
  46063. }());
  46064. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  46065. })(BABYLON || (BABYLON = {}));
  46066. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  46067. var BABYLON;
  46068. (function (BABYLON) {
  46069. /**
  46070. * Manages the defines for the PBR Material.
  46071. * @hiddenChildren
  46072. */
  46073. var PBRMaterialDefines = /** @class */ (function (_super) {
  46074. __extends(PBRMaterialDefines, _super);
  46075. /**
  46076. * Initializes the PBR Material defines.
  46077. */
  46078. function PBRMaterialDefines() {
  46079. var _this = _super.call(this) || this;
  46080. _this.PBR = true;
  46081. _this.MAINUV1 = false;
  46082. _this.MAINUV2 = false;
  46083. _this.UV1 = false;
  46084. _this.UV2 = false;
  46085. _this.ALBEDO = false;
  46086. _this.ALBEDODIRECTUV = 0;
  46087. _this.VERTEXCOLOR = false;
  46088. _this.AMBIENT = false;
  46089. _this.AMBIENTDIRECTUV = 0;
  46090. _this.AMBIENTINGRAYSCALE = false;
  46091. _this.OPACITY = false;
  46092. _this.VERTEXALPHA = false;
  46093. _this.OPACITYDIRECTUV = 0;
  46094. _this.OPACITYRGB = false;
  46095. _this.ALPHATEST = false;
  46096. _this.DEPTHPREPASS = false;
  46097. _this.ALPHABLEND = false;
  46098. _this.ALPHAFROMALBEDO = false;
  46099. _this.ALPHATESTVALUE = "0.5";
  46100. _this.SPECULAROVERALPHA = false;
  46101. _this.RADIANCEOVERALPHA = false;
  46102. _this.ALPHAFRESNEL = false;
  46103. _this.LINEARALPHAFRESNEL = false;
  46104. _this.PREMULTIPLYALPHA = false;
  46105. _this.EMISSIVE = false;
  46106. _this.EMISSIVEDIRECTUV = 0;
  46107. _this.REFLECTIVITY = false;
  46108. _this.REFLECTIVITYDIRECTUV = 0;
  46109. _this.SPECULARTERM = false;
  46110. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  46111. _this.MICROSURFACEAUTOMATIC = false;
  46112. _this.LODBASEDMICROSFURACE = false;
  46113. _this.MICROSURFACEMAP = false;
  46114. _this.MICROSURFACEMAPDIRECTUV = 0;
  46115. _this.METALLICWORKFLOW = false;
  46116. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  46117. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  46118. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  46119. _this.AOSTOREINMETALMAPRED = false;
  46120. _this.ENVIRONMENTBRDF = false;
  46121. _this.NORMAL = false;
  46122. _this.TANGENT = false;
  46123. _this.BUMP = false;
  46124. _this.BUMPDIRECTUV = 0;
  46125. _this.OBJECTSPACE_NORMALMAP = false;
  46126. _this.PARALLAX = false;
  46127. _this.PARALLAXOCCLUSION = false;
  46128. _this.NORMALXYSCALE = true;
  46129. _this.LIGHTMAP = false;
  46130. _this.LIGHTMAPDIRECTUV = 0;
  46131. _this.USELIGHTMAPASSHADOWMAP = false;
  46132. _this.GAMMALIGHTMAP = false;
  46133. _this.REFLECTION = false;
  46134. _this.REFLECTIONMAP_3D = false;
  46135. _this.REFLECTIONMAP_SPHERICAL = false;
  46136. _this.REFLECTIONMAP_PLANAR = false;
  46137. _this.REFLECTIONMAP_CUBIC = false;
  46138. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  46139. _this.REFLECTIONMAP_PROJECTION = false;
  46140. _this.REFLECTIONMAP_SKYBOX = false;
  46141. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  46142. _this.REFLECTIONMAP_EXPLICIT = false;
  46143. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  46144. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  46145. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  46146. _this.INVERTCUBICMAP = false;
  46147. _this.USESPHERICALFROMREFLECTIONMAP = false;
  46148. _this.USESPHERICALINVERTEX = false;
  46149. _this.REFLECTIONMAP_OPPOSITEZ = false;
  46150. _this.LODINREFLECTIONALPHA = false;
  46151. _this.GAMMAREFLECTION = false;
  46152. _this.RGBDREFLECTION = false;
  46153. _this.RADIANCEOCCLUSION = false;
  46154. _this.HORIZONOCCLUSION = false;
  46155. _this.REFRACTION = false;
  46156. _this.REFRACTIONMAP_3D = false;
  46157. _this.REFRACTIONMAP_OPPOSITEZ = false;
  46158. _this.LODINREFRACTIONALPHA = false;
  46159. _this.GAMMAREFRACTION = false;
  46160. _this.RGBDREFRACTION = false;
  46161. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  46162. _this.INSTANCES = false;
  46163. _this.NUM_BONE_INFLUENCERS = 0;
  46164. _this.BonesPerMesh = 0;
  46165. _this.BONETEXTURE = false;
  46166. _this.NONUNIFORMSCALING = false;
  46167. _this.MORPHTARGETS = false;
  46168. _this.MORPHTARGETS_NORMAL = false;
  46169. _this.MORPHTARGETS_TANGENT = false;
  46170. _this.NUM_MORPH_INFLUENCERS = 0;
  46171. _this.IMAGEPROCESSING = false;
  46172. _this.VIGNETTE = false;
  46173. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  46174. _this.VIGNETTEBLENDMODEOPAQUE = false;
  46175. _this.TONEMAPPING = false;
  46176. _this.TONEMAPPING_ACES = false;
  46177. _this.CONTRAST = false;
  46178. _this.COLORCURVES = false;
  46179. _this.COLORGRADING = false;
  46180. _this.COLORGRADING3D = false;
  46181. _this.SAMPLER3DGREENDEPTH = false;
  46182. _this.SAMPLER3DBGRMAP = false;
  46183. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  46184. _this.EXPOSURE = false;
  46185. _this.USEPHYSICALLIGHTFALLOFF = false;
  46186. _this.USEGLTFLIGHTFALLOFF = false;
  46187. _this.TWOSIDEDLIGHTING = false;
  46188. _this.SHADOWFLOAT = false;
  46189. _this.CLIPPLANE = false;
  46190. _this.CLIPPLANE2 = false;
  46191. _this.CLIPPLANE3 = false;
  46192. _this.CLIPPLANE4 = false;
  46193. _this.POINTSIZE = false;
  46194. _this.FOG = false;
  46195. _this.LOGARITHMICDEPTH = false;
  46196. _this.FORCENORMALFORWARD = false;
  46197. _this.SPECULARAA = false;
  46198. _this.UNLIT = false;
  46199. _this.rebuild();
  46200. return _this;
  46201. }
  46202. /**
  46203. * Resets the PBR Material defines.
  46204. */
  46205. PBRMaterialDefines.prototype.reset = function () {
  46206. _super.prototype.reset.call(this);
  46207. this.ALPHATESTVALUE = "0.5";
  46208. this.PBR = true;
  46209. };
  46210. return PBRMaterialDefines;
  46211. }(BABYLON.MaterialDefines));
  46212. /**
  46213. * The Physically based material base class of BJS.
  46214. *
  46215. * This offers the main features of a standard PBR material.
  46216. * For more information, please refer to the documentation :
  46217. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  46218. */
  46219. var PBRBaseMaterial = /** @class */ (function (_super) {
  46220. __extends(PBRBaseMaterial, _super);
  46221. /**
  46222. * Instantiates a new PBRMaterial instance.
  46223. *
  46224. * @param name The material name
  46225. * @param scene The scene the material will be use in.
  46226. */
  46227. function PBRBaseMaterial(name, scene) {
  46228. var _this = _super.call(this, name, scene) || this;
  46229. /**
  46230. * Intensity of the direct lights e.g. the four lights available in your scene.
  46231. * This impacts both the direct diffuse and specular highlights.
  46232. */
  46233. _this._directIntensity = 1.0;
  46234. /**
  46235. * Intensity of the emissive part of the material.
  46236. * This helps controlling the emissive effect without modifying the emissive color.
  46237. */
  46238. _this._emissiveIntensity = 1.0;
  46239. /**
  46240. * Intensity of the environment e.g. how much the environment will light the object
  46241. * either through harmonics for rough material or through the refelction for shiny ones.
  46242. */
  46243. _this._environmentIntensity = 1.0;
  46244. /**
  46245. * This is a special control allowing the reduction of the specular highlights coming from the
  46246. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  46247. */
  46248. _this._specularIntensity = 1.0;
  46249. /**
  46250. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  46251. */
  46252. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  46253. /**
  46254. * Debug Control allowing disabling the bump map on this material.
  46255. */
  46256. _this._disableBumpMap = false;
  46257. /**
  46258. * AKA Occlusion Texture Intensity in other nomenclature.
  46259. */
  46260. _this._ambientTextureStrength = 1.0;
  46261. /**
  46262. * Defines how much the AO map is occluding the analytical lights (point spot...).
  46263. * 1 means it completely occludes it
  46264. * 0 mean it has no impact
  46265. */
  46266. _this._ambientTextureImpactOnAnalyticalLights = BABYLON.PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS;
  46267. /**
  46268. * The color of a material in ambient lighting.
  46269. */
  46270. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  46271. /**
  46272. * AKA Diffuse Color in other nomenclature.
  46273. */
  46274. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  46275. /**
  46276. * AKA Specular Color in other nomenclature.
  46277. */
  46278. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  46279. /**
  46280. * The color applied when light is reflected from a material.
  46281. */
  46282. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  46283. /**
  46284. * The color applied when light is emitted from a material.
  46285. */
  46286. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  46287. /**
  46288. * AKA Glossiness in other nomenclature.
  46289. */
  46290. _this._microSurface = 0.9;
  46291. /**
  46292. * source material index of refraction (IOR)' / 'destination material IOR.
  46293. */
  46294. _this._indexOfRefraction = 0.66;
  46295. /**
  46296. * Controls if refraction needs to be inverted on Y. This could be useful for procedural texture.
  46297. */
  46298. _this._invertRefractionY = false;
  46299. /**
  46300. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  46301. * Materials half opaque for instance using refraction could benefit from this control.
  46302. */
  46303. _this._linkRefractionWithTransparency = false;
  46304. /**
  46305. * Specifies that the material will use the light map as a show map.
  46306. */
  46307. _this._useLightmapAsShadowmap = false;
  46308. /**
  46309. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  46310. * makes the reflect vector face the model (under horizon).
  46311. */
  46312. _this._useHorizonOcclusion = true;
  46313. /**
  46314. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  46315. * too much the area relying on ambient texture to define their ambient occlusion.
  46316. */
  46317. _this._useRadianceOcclusion = true;
  46318. /**
  46319. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  46320. */
  46321. _this._useAlphaFromAlbedoTexture = false;
  46322. /**
  46323. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  46324. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  46325. */
  46326. _this._useSpecularOverAlpha = true;
  46327. /**
  46328. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  46329. */
  46330. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  46331. /**
  46332. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  46333. */
  46334. _this._useRoughnessFromMetallicTextureAlpha = true;
  46335. /**
  46336. * Specifies if the metallic texture contains the roughness information in its green channel.
  46337. */
  46338. _this._useRoughnessFromMetallicTextureGreen = false;
  46339. /**
  46340. * Specifies if the metallic texture contains the metallness information in its blue channel.
  46341. */
  46342. _this._useMetallnessFromMetallicTextureBlue = false;
  46343. /**
  46344. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  46345. */
  46346. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  46347. /**
  46348. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  46349. */
  46350. _this._useAmbientInGrayScale = false;
  46351. /**
  46352. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  46353. * The material will try to infer what glossiness each pixel should be.
  46354. */
  46355. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  46356. /**
  46357. * Defines the falloff type used in this material.
  46358. * It by default is Physical.
  46359. */
  46360. _this._lightFalloff = PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  46361. /**
  46362. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  46363. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  46364. */
  46365. _this._useRadianceOverAlpha = true;
  46366. /**
  46367. * Allows using an object space normal map (instead of tangent space).
  46368. */
  46369. _this._useObjectSpaceNormalMap = false;
  46370. /**
  46371. * Allows using the bump map in parallax mode.
  46372. */
  46373. _this._useParallax = false;
  46374. /**
  46375. * Allows using the bump map in parallax occlusion mode.
  46376. */
  46377. _this._useParallaxOcclusion = false;
  46378. /**
  46379. * Controls the scale bias of the parallax mode.
  46380. */
  46381. _this._parallaxScaleBias = 0.05;
  46382. /**
  46383. * If sets to true, disables all the lights affecting the material.
  46384. */
  46385. _this._disableLighting = false;
  46386. /**
  46387. * Number of Simultaneous lights allowed on the material.
  46388. */
  46389. _this._maxSimultaneousLights = 4;
  46390. /**
  46391. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  46392. */
  46393. _this._invertNormalMapX = false;
  46394. /**
  46395. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  46396. */
  46397. _this._invertNormalMapY = false;
  46398. /**
  46399. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  46400. */
  46401. _this._twoSidedLighting = false;
  46402. /**
  46403. * Defines the alpha limits in alpha test mode.
  46404. */
  46405. _this._alphaCutOff = 0.4;
  46406. /**
  46407. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  46408. */
  46409. _this._forceAlphaTest = false;
  46410. /**
  46411. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  46412. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  46413. */
  46414. _this._useAlphaFresnel = false;
  46415. /**
  46416. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  46417. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  46418. */
  46419. _this._useLinearAlphaFresnel = false;
  46420. /**
  46421. * The transparency mode of the material.
  46422. */
  46423. _this._transparencyMode = null;
  46424. /**
  46425. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  46426. * from cos thetav and roughness:
  46427. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  46428. */
  46429. _this._environmentBRDFTexture = null;
  46430. /**
  46431. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  46432. */
  46433. _this._forceIrradianceInFragment = false;
  46434. /**
  46435. * Force normal to face away from face.
  46436. */
  46437. _this._forceNormalForward = false;
  46438. /**
  46439. * Enables specular anti aliasing in the PBR shader.
  46440. * It will both interacts on the Geometry for analytical and IBL lighting.
  46441. * It also prefilter the roughness map based on the bump values.
  46442. */
  46443. _this._enableSpecularAntiAliasing = false;
  46444. /**
  46445. * Stores the available render targets.
  46446. */
  46447. _this._renderTargets = new BABYLON.SmartArray(16);
  46448. /**
  46449. * Sets the global ambient color for the material used in lighting calculations.
  46450. */
  46451. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  46452. /**
  46453. * If set to true, no lighting calculations will be applied.
  46454. */
  46455. _this._unlit = false;
  46456. // Setup the default processing configuration to the scene.
  46457. _this._attachImageProcessingConfiguration(null);
  46458. _this.getRenderTargetTextures = function () {
  46459. _this._renderTargets.reset();
  46460. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  46461. _this._renderTargets.push(_this._reflectionTexture);
  46462. }
  46463. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  46464. _this._renderTargets.push(_this._refractionTexture);
  46465. }
  46466. return _this._renderTargets;
  46467. };
  46468. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  46469. return _this;
  46470. }
  46471. /**
  46472. * Attaches a new image processing configuration to the PBR Material.
  46473. * @param configuration
  46474. */
  46475. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  46476. var _this = this;
  46477. if (configuration === this._imageProcessingConfiguration) {
  46478. return;
  46479. }
  46480. // Detaches observer.
  46481. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  46482. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  46483. }
  46484. // Pick the scene configuration if needed.
  46485. if (!configuration) {
  46486. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  46487. }
  46488. else {
  46489. this._imageProcessingConfiguration = configuration;
  46490. }
  46491. // Attaches observer.
  46492. if (this._imageProcessingConfiguration) {
  46493. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  46494. _this._markAllSubMeshesAsImageProcessingDirty();
  46495. });
  46496. }
  46497. };
  46498. Object.defineProperty(PBRBaseMaterial.prototype, "hasRenderTargetTextures", {
  46499. /**
  46500. * Gets a boolean indicating that current material needs to register RTT
  46501. */
  46502. get: function () {
  46503. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  46504. return true;
  46505. }
  46506. if (BABYLON.StandardMaterial.RefractionTextureEnabled && this._refractionTexture && this._refractionTexture.isRenderTarget) {
  46507. return true;
  46508. }
  46509. return false;
  46510. },
  46511. enumerable: true,
  46512. configurable: true
  46513. });
  46514. /**
  46515. * Gets the name of the material class.
  46516. */
  46517. PBRBaseMaterial.prototype.getClassName = function () {
  46518. return "PBRBaseMaterial";
  46519. };
  46520. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  46521. /**
  46522. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  46523. */
  46524. get: function () {
  46525. return this._useLogarithmicDepth;
  46526. },
  46527. /**
  46528. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  46529. */
  46530. set: function (value) {
  46531. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  46532. },
  46533. enumerable: true,
  46534. configurable: true
  46535. });
  46536. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  46537. /**
  46538. * Gets the current transparency mode.
  46539. */
  46540. get: function () {
  46541. return this._transparencyMode;
  46542. },
  46543. /**
  46544. * Sets the transparency mode of the material.
  46545. *
  46546. * | Value | Type | Description |
  46547. * | ----- | ----------------------------------- | ----------- |
  46548. * | 0 | OPAQUE | |
  46549. * | 1 | ALPHATEST | |
  46550. * | 2 | ALPHABLEND | |
  46551. * | 3 | ALPHATESTANDBLEND | |
  46552. *
  46553. */
  46554. set: function (value) {
  46555. if (this._transparencyMode === value) {
  46556. return;
  46557. }
  46558. this._transparencyMode = value;
  46559. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  46560. this._markAllSubMeshesAsTexturesAndMiscDirty();
  46561. },
  46562. enumerable: true,
  46563. configurable: true
  46564. });
  46565. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  46566. /**
  46567. * Returns true if alpha blending should be disabled.
  46568. */
  46569. get: function () {
  46570. return (this._linkRefractionWithTransparency ||
  46571. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  46572. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  46573. },
  46574. enumerable: true,
  46575. configurable: true
  46576. });
  46577. /**
  46578. * Specifies whether or not this material should be rendered in alpha blend mode.
  46579. */
  46580. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  46581. if (this._disableAlphaBlending) {
  46582. return false;
  46583. }
  46584. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  46585. };
  46586. /**
  46587. * Specifies if the mesh will require alpha blending.
  46588. * @param mesh - BJS mesh.
  46589. */
  46590. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  46591. if (this._disableAlphaBlending) {
  46592. return false;
  46593. }
  46594. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  46595. };
  46596. /**
  46597. * Specifies whether or not this material should be rendered in alpha test mode.
  46598. */
  46599. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  46600. if (this._forceAlphaTest) {
  46601. return true;
  46602. }
  46603. if (this._linkRefractionWithTransparency) {
  46604. return false;
  46605. }
  46606. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  46607. };
  46608. /**
  46609. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  46610. */
  46611. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  46612. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  46613. };
  46614. /**
  46615. * Gets the texture used for the alpha test.
  46616. */
  46617. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  46618. return this._albedoTexture;
  46619. };
  46620. /**
  46621. * Specifies that the submesh is ready to be used.
  46622. * @param mesh - BJS mesh.
  46623. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  46624. * @param useInstances - Specifies that instances should be used.
  46625. * @returns - boolean indicating that the submesh is ready or not.
  46626. */
  46627. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  46628. if (subMesh.effect && this.isFrozen) {
  46629. if (this._wasPreviouslyReady) {
  46630. return true;
  46631. }
  46632. }
  46633. if (!subMesh._materialDefines) {
  46634. subMesh._materialDefines = new PBRMaterialDefines();
  46635. }
  46636. var defines = subMesh._materialDefines;
  46637. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  46638. if (defines._renderId === this.getScene().getRenderId()) {
  46639. return true;
  46640. }
  46641. }
  46642. var scene = this.getScene();
  46643. var engine = scene.getEngine();
  46644. if (defines._areTexturesDirty) {
  46645. if (scene.texturesEnabled) {
  46646. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  46647. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  46648. return false;
  46649. }
  46650. }
  46651. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  46652. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  46653. return false;
  46654. }
  46655. }
  46656. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  46657. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  46658. return false;
  46659. }
  46660. }
  46661. var reflectionTexture = this._getReflectionTexture();
  46662. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  46663. if (!reflectionTexture.isReadyOrNotBlocking()) {
  46664. return false;
  46665. }
  46666. }
  46667. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  46668. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  46669. return false;
  46670. }
  46671. }
  46672. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  46673. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  46674. return false;
  46675. }
  46676. }
  46677. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  46678. if (this._metallicTexture) {
  46679. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  46680. return false;
  46681. }
  46682. }
  46683. else if (this._reflectivityTexture) {
  46684. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  46685. return false;
  46686. }
  46687. }
  46688. if (this._microSurfaceTexture) {
  46689. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  46690. return false;
  46691. }
  46692. }
  46693. }
  46694. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  46695. // Bump texture cannot be not blocking.
  46696. if (!this._bumpTexture.isReady()) {
  46697. return false;
  46698. }
  46699. }
  46700. var refractionTexture = this._getRefractionTexture();
  46701. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  46702. if (!refractionTexture.isReadyOrNotBlocking()) {
  46703. return false;
  46704. }
  46705. }
  46706. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  46707. // This is blocking.
  46708. if (!this._environmentBRDFTexture.isReady()) {
  46709. return false;
  46710. }
  46711. }
  46712. }
  46713. }
  46714. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  46715. if (!this._imageProcessingConfiguration.isReady()) {
  46716. return false;
  46717. }
  46718. }
  46719. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  46720. mesh.createNormals(true);
  46721. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  46722. }
  46723. var previousEffect = subMesh.effect;
  46724. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  46725. if (effect) {
  46726. // Use previous effect while new one is compiling
  46727. if (this.allowShaderHotSwapping && previousEffect && !effect.isReady()) {
  46728. effect = previousEffect;
  46729. defines.markAsUnprocessed();
  46730. }
  46731. else {
  46732. scene.resetCachedMaterial();
  46733. subMesh.setEffect(effect, defines);
  46734. this.buildUniformLayout();
  46735. }
  46736. }
  46737. if (!subMesh.effect || !subMesh.effect.isReady()) {
  46738. return false;
  46739. }
  46740. defines._renderId = scene.getRenderId();
  46741. this._wasPreviouslyReady = true;
  46742. return true;
  46743. };
  46744. /**
  46745. * Specifies if the material uses metallic roughness workflow.
  46746. * @returns boolean specifiying if the material uses metallic roughness workflow.
  46747. */
  46748. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  46749. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  46750. return true;
  46751. }
  46752. return false;
  46753. };
  46754. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  46755. if (onCompiled === void 0) { onCompiled = null; }
  46756. if (onError === void 0) { onError = null; }
  46757. if (useInstances === void 0) { useInstances = null; }
  46758. if (useClipPlane === void 0) { useClipPlane = null; }
  46759. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  46760. if (!defines.isDirty) {
  46761. return null;
  46762. }
  46763. defines.markAsProcessed();
  46764. var scene = this.getScene();
  46765. var engine = scene.getEngine();
  46766. // Fallbacks
  46767. var fallbacks = new BABYLON.EffectFallbacks();
  46768. var fallbackRank = 0;
  46769. if (defines.USESPHERICALINVERTEX) {
  46770. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  46771. }
  46772. if (defines.FOG) {
  46773. fallbacks.addFallback(fallbackRank, "FOG");
  46774. }
  46775. if (defines.SPECULARAA) {
  46776. fallbacks.addFallback(fallbackRank, "SPECULARAA");
  46777. }
  46778. if (defines.POINTSIZE) {
  46779. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  46780. }
  46781. if (defines.LOGARITHMICDEPTH) {
  46782. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  46783. }
  46784. if (defines.PARALLAX) {
  46785. fallbacks.addFallback(fallbackRank, "PARALLAX");
  46786. }
  46787. if (defines.PARALLAXOCCLUSION) {
  46788. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  46789. }
  46790. if (defines.ENVIRONMENTBRDF) {
  46791. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  46792. }
  46793. if (defines.TANGENT) {
  46794. fallbacks.addFallback(fallbackRank++, "TANGENT");
  46795. }
  46796. if (defines.BUMP) {
  46797. fallbacks.addFallback(fallbackRank++, "BUMP");
  46798. }
  46799. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  46800. if (defines.SPECULARTERM) {
  46801. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  46802. }
  46803. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  46804. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  46805. }
  46806. if (defines.LIGHTMAP) {
  46807. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  46808. }
  46809. if (defines.NORMAL) {
  46810. fallbacks.addFallback(fallbackRank++, "NORMAL");
  46811. }
  46812. if (defines.AMBIENT) {
  46813. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  46814. }
  46815. if (defines.EMISSIVE) {
  46816. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  46817. }
  46818. if (defines.VERTEXCOLOR) {
  46819. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  46820. }
  46821. if (defines.NUM_BONE_INFLUENCERS > 0) {
  46822. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  46823. }
  46824. if (defines.MORPHTARGETS) {
  46825. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  46826. }
  46827. //Attributes
  46828. var attribs = [BABYLON.VertexBuffer.PositionKind];
  46829. if (defines.NORMAL) {
  46830. attribs.push(BABYLON.VertexBuffer.NormalKind);
  46831. }
  46832. if (defines.TANGENT) {
  46833. attribs.push(BABYLON.VertexBuffer.TangentKind);
  46834. }
  46835. if (defines.UV1) {
  46836. attribs.push(BABYLON.VertexBuffer.UVKind);
  46837. }
  46838. if (defines.UV2) {
  46839. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  46840. }
  46841. if (defines.VERTEXCOLOR) {
  46842. attribs.push(BABYLON.VertexBuffer.ColorKind);
  46843. }
  46844. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  46845. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  46846. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  46847. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  46848. "vFogInfos", "vFogColor", "pointSize",
  46849. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  46850. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  46851. "mBones",
  46852. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  46853. "vLightingIntensity",
  46854. "logarithmicDepthConstant",
  46855. "vSphericalX", "vSphericalY", "vSphericalZ",
  46856. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  46857. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  46858. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  46859. "vTangentSpaceParams", "boneTextureWidth"
  46860. ];
  46861. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  46862. "bumpSampler", "lightmapSampler", "opacitySampler",
  46863. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  46864. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  46865. "microSurfaceSampler", "environmentBrdfSampler", "boneSampler"];
  46866. var uniformBuffers = ["Material", "Scene"];
  46867. if (BABYLON.ImageProcessingConfiguration) {
  46868. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  46869. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  46870. }
  46871. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  46872. uniformsNames: uniforms,
  46873. uniformBuffersNames: uniformBuffers,
  46874. samplers: samplers,
  46875. defines: defines,
  46876. maxSimultaneousLights: this._maxSimultaneousLights
  46877. });
  46878. var join = defines.toString();
  46879. return engine.createEffect("pbr", {
  46880. attributes: attribs,
  46881. uniformsNames: uniforms,
  46882. uniformBuffersNames: uniformBuffers,
  46883. samplers: samplers,
  46884. defines: join,
  46885. fallbacks: fallbacks,
  46886. onCompiled: onCompiled,
  46887. onError: onError,
  46888. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  46889. }, engine);
  46890. };
  46891. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  46892. if (useInstances === void 0) { useInstances = null; }
  46893. if (useClipPlane === void 0) { useClipPlane = null; }
  46894. var scene = this.getScene();
  46895. var engine = scene.getEngine();
  46896. // Lights
  46897. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  46898. defines._needNormals = true;
  46899. // Textures
  46900. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  46901. if (defines._areTexturesDirty) {
  46902. defines._needUVs = false;
  46903. if (scene.texturesEnabled) {
  46904. if (scene.getEngine().getCaps().textureLOD) {
  46905. defines.LODBASEDMICROSFURACE = true;
  46906. }
  46907. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  46908. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  46909. }
  46910. else {
  46911. defines.ALBEDO = false;
  46912. }
  46913. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  46914. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  46915. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  46916. }
  46917. else {
  46918. defines.AMBIENT = false;
  46919. }
  46920. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  46921. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  46922. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  46923. }
  46924. else {
  46925. defines.OPACITY = false;
  46926. }
  46927. var reflectionTexture = this._getReflectionTexture();
  46928. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  46929. defines.REFLECTION = true;
  46930. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  46931. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  46932. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  46933. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  46934. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  46935. defines.INVERTCUBICMAP = true;
  46936. }
  46937. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  46938. defines.REFLECTIONMAP_CUBIC = false;
  46939. defines.REFLECTIONMAP_EXPLICIT = false;
  46940. defines.REFLECTIONMAP_PLANAR = false;
  46941. defines.REFLECTIONMAP_PROJECTION = false;
  46942. defines.REFLECTIONMAP_SKYBOX = false;
  46943. defines.REFLECTIONMAP_SPHERICAL = false;
  46944. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  46945. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  46946. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  46947. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  46948. switch (reflectionTexture.coordinatesMode) {
  46949. case BABYLON.Texture.EXPLICIT_MODE:
  46950. defines.REFLECTIONMAP_EXPLICIT = true;
  46951. break;
  46952. case BABYLON.Texture.PLANAR_MODE:
  46953. defines.REFLECTIONMAP_PLANAR = true;
  46954. break;
  46955. case BABYLON.Texture.PROJECTION_MODE:
  46956. defines.REFLECTIONMAP_PROJECTION = true;
  46957. break;
  46958. case BABYLON.Texture.SKYBOX_MODE:
  46959. defines.REFLECTIONMAP_SKYBOX = true;
  46960. break;
  46961. case BABYLON.Texture.SPHERICAL_MODE:
  46962. defines.REFLECTIONMAP_SPHERICAL = true;
  46963. break;
  46964. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  46965. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  46966. break;
  46967. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  46968. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  46969. break;
  46970. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  46971. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  46972. break;
  46973. case BABYLON.Texture.CUBIC_MODE:
  46974. case BABYLON.Texture.INVCUBIC_MODE:
  46975. default:
  46976. defines.REFLECTIONMAP_CUBIC = true;
  46977. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  46978. break;
  46979. }
  46980. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  46981. if (reflectionTexture.sphericalPolynomial) {
  46982. defines.USESPHERICALFROMREFLECTIONMAP = true;
  46983. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  46984. defines.USESPHERICALINVERTEX = false;
  46985. }
  46986. else {
  46987. defines.USESPHERICALINVERTEX = true;
  46988. }
  46989. }
  46990. }
  46991. else {
  46992. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !reflectionTexture.getReflectionTextureMatrix().isIdentity();
  46993. }
  46994. }
  46995. else {
  46996. defines.REFLECTION = false;
  46997. defines.REFLECTIONMAP_3D = false;
  46998. defines.REFLECTIONMAP_SPHERICAL = false;
  46999. defines.REFLECTIONMAP_PLANAR = false;
  47000. defines.REFLECTIONMAP_CUBIC = false;
  47001. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  47002. defines.REFLECTIONMAP_PROJECTION = false;
  47003. defines.REFLECTIONMAP_SKYBOX = false;
  47004. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  47005. defines.REFLECTIONMAP_EXPLICIT = false;
  47006. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  47007. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  47008. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  47009. defines.INVERTCUBICMAP = false;
  47010. defines.USESPHERICALFROMREFLECTIONMAP = false;
  47011. defines.USESPHERICALINVERTEX = false;
  47012. defines.REFLECTIONMAP_OPPOSITEZ = false;
  47013. defines.LODINREFLECTIONALPHA = false;
  47014. defines.GAMMAREFLECTION = false;
  47015. defines.RGBDREFLECTION = false;
  47016. }
  47017. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  47018. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  47019. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  47020. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  47021. }
  47022. else {
  47023. defines.LIGHTMAP = false;
  47024. }
  47025. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  47026. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  47027. }
  47028. else {
  47029. defines.EMISSIVE = false;
  47030. }
  47031. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  47032. if (this._metallicTexture) {
  47033. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  47034. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  47035. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  47036. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  47037. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  47038. }
  47039. else if (this._reflectivityTexture) {
  47040. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  47041. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  47042. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  47043. }
  47044. else {
  47045. defines.REFLECTIVITY = false;
  47046. }
  47047. if (this._microSurfaceTexture) {
  47048. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  47049. }
  47050. else {
  47051. defines.MICROSURFACEMAP = false;
  47052. }
  47053. }
  47054. else {
  47055. defines.REFLECTIVITY = false;
  47056. defines.MICROSURFACEMAP = false;
  47057. }
  47058. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  47059. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  47060. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  47061. defines.PARALLAX = true;
  47062. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  47063. }
  47064. else {
  47065. defines.PARALLAX = false;
  47066. }
  47067. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  47068. }
  47069. else {
  47070. defines.BUMP = false;
  47071. }
  47072. var refractionTexture = this._getRefractionTexture();
  47073. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  47074. defines.REFRACTION = true;
  47075. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  47076. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  47077. defines.RGBDREFRACTION = refractionTexture.isRGBD;
  47078. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  47079. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  47080. if (this._linkRefractionWithTransparency) {
  47081. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  47082. }
  47083. }
  47084. else {
  47085. defines.REFRACTION = false;
  47086. }
  47087. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  47088. defines.ENVIRONMENTBRDF = true;
  47089. }
  47090. else {
  47091. defines.ENVIRONMENTBRDF = false;
  47092. }
  47093. if (this._shouldUseAlphaFromAlbedoTexture()) {
  47094. defines.ALPHAFROMALBEDO = true;
  47095. }
  47096. else {
  47097. defines.ALPHAFROMALBEDO = false;
  47098. }
  47099. }
  47100. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  47101. if (this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_STANDARD) {
  47102. defines.USEPHYSICALLIGHTFALLOFF = false;
  47103. defines.USEGLTFLIGHTFALLOFF = false;
  47104. }
  47105. else if (this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_GLTF) {
  47106. defines.USEPHYSICALLIGHTFALLOFF = false;
  47107. defines.USEGLTFLIGHTFALLOFF = true;
  47108. }
  47109. else {
  47110. defines.USEPHYSICALLIGHTFALLOFF = true;
  47111. defines.USEGLTFLIGHTFALLOFF = false;
  47112. }
  47113. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  47114. if (!this.backFaceCulling && this._twoSidedLighting) {
  47115. defines.TWOSIDEDLIGHTING = true;
  47116. }
  47117. else {
  47118. defines.TWOSIDEDLIGHTING = false;
  47119. }
  47120. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  47121. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  47122. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  47123. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  47124. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  47125. defines.SPECULARAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  47126. }
  47127. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  47128. this._imageProcessingConfiguration.prepareDefines(defines);
  47129. }
  47130. defines.FORCENORMALFORWARD = this._forceNormalForward;
  47131. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  47132. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  47133. // Misc.
  47134. if (defines._areMiscDirty) {
  47135. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  47136. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  47137. }
  47138. // Values that need to be evaluated on every frame
  47139. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  47140. // Attribs
  47141. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  47142. };
  47143. /**
  47144. * Force shader compilation
  47145. */
  47146. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  47147. var _this = this;
  47148. var localOptions = __assign({ clipPlane: false }, options);
  47149. var defines = new PBRMaterialDefines();
  47150. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  47151. if (effect.isReady()) {
  47152. if (onCompiled) {
  47153. onCompiled(this);
  47154. }
  47155. }
  47156. else {
  47157. effect.onCompileObservable.add(function () {
  47158. if (onCompiled) {
  47159. onCompiled(_this);
  47160. }
  47161. });
  47162. }
  47163. };
  47164. /**
  47165. * Initializes the uniform buffer layout for the shader.
  47166. */
  47167. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  47168. // Order is important !
  47169. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  47170. this._uniformBuffer.addUniform("vAmbientInfos", 4);
  47171. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  47172. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  47173. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  47174. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  47175. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  47176. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  47177. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  47178. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  47179. this._uniformBuffer.addUniform("vReflectionSize", 3);
  47180. this._uniformBuffer.addUniform("vBumpInfos", 3);
  47181. this._uniformBuffer.addUniform("albedoMatrix", 16);
  47182. this._uniformBuffer.addUniform("ambientMatrix", 16);
  47183. this._uniformBuffer.addUniform("opacityMatrix", 16);
  47184. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  47185. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  47186. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  47187. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  47188. this._uniformBuffer.addUniform("bumpMatrix", 16);
  47189. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  47190. this._uniformBuffer.addUniform("refractionMatrix", 16);
  47191. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  47192. this._uniformBuffer.addUniform("vReflectionColor", 3);
  47193. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  47194. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  47195. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  47196. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  47197. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  47198. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  47199. this._uniformBuffer.addUniform("pointSize", 1);
  47200. this._uniformBuffer.create();
  47201. };
  47202. /**
  47203. * Unbinds the textures.
  47204. */
  47205. PBRBaseMaterial.prototype.unbind = function () {
  47206. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  47207. this._uniformBuffer.setTexture("reflectionSampler", null);
  47208. }
  47209. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  47210. this._uniformBuffer.setTexture("refractionSampler", null);
  47211. }
  47212. _super.prototype.unbind.call(this);
  47213. };
  47214. /**
  47215. * Binds the submesh data.
  47216. * @param world - The world matrix.
  47217. * @param mesh - The BJS mesh.
  47218. * @param subMesh - A submesh of the BJS mesh.
  47219. */
  47220. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  47221. var scene = this.getScene();
  47222. var defines = subMesh._materialDefines;
  47223. if (!defines) {
  47224. return;
  47225. }
  47226. var effect = subMesh.effect;
  47227. if (!effect) {
  47228. return;
  47229. }
  47230. this._activeEffect = effect;
  47231. // Matrices
  47232. this.bindOnlyWorldMatrix(world);
  47233. // Normal Matrix
  47234. if (defines.OBJECTSPACE_NORMALMAP) {
  47235. world.toNormalMatrix(this._normalMatrix);
  47236. this.bindOnlyNormalMatrix(this._normalMatrix);
  47237. }
  47238. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  47239. // Bones
  47240. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  47241. var reflectionTexture = null;
  47242. if (mustRebind) {
  47243. this._uniformBuffer.bindToEffect(effect, "Material");
  47244. this.bindViewProjection(effect);
  47245. reflectionTexture = this._getReflectionTexture();
  47246. var refractionTexture = this._getRefractionTexture();
  47247. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  47248. // Texture uniforms
  47249. if (scene.texturesEnabled) {
  47250. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  47251. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  47252. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  47253. }
  47254. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  47255. this._uniformBuffer.updateFloat4("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength, this._ambientTextureImpactOnAnalyticalLights);
  47256. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  47257. }
  47258. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  47259. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  47260. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  47261. }
  47262. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  47263. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  47264. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  47265. if (reflectionTexture.boundingBoxSize) {
  47266. var cubeTexture = reflectionTexture;
  47267. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  47268. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  47269. }
  47270. var polynomials = reflectionTexture.sphericalPolynomial;
  47271. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  47272. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  47273. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  47274. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  47275. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  47276. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  47277. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  47278. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  47279. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  47280. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  47281. }
  47282. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  47283. }
  47284. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  47285. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  47286. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  47287. }
  47288. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  47289. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  47290. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  47291. }
  47292. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  47293. if (this._metallicTexture) {
  47294. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  47295. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  47296. }
  47297. else if (this._reflectivityTexture) {
  47298. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  47299. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  47300. }
  47301. if (this._microSurfaceTexture) {
  47302. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  47303. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  47304. }
  47305. }
  47306. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  47307. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  47308. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  47309. if (scene._mirroredCameraPosition) {
  47310. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  47311. }
  47312. else {
  47313. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  47314. }
  47315. }
  47316. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  47317. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  47318. var depth = 1.0;
  47319. if (!refractionTexture.isCube) {
  47320. if (refractionTexture.depth) {
  47321. depth = refractionTexture.depth;
  47322. }
  47323. }
  47324. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  47325. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  47326. }
  47327. }
  47328. // Point size
  47329. if (this.pointsCloud) {
  47330. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  47331. }
  47332. // Colors
  47333. if (defines.METALLICWORKFLOW) {
  47334. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  47335. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  47336. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  47337. }
  47338. else {
  47339. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  47340. }
  47341. this._uniformBuffer.updateColor3("vEmissiveColor", BABYLON.StandardMaterial.EmissiveTextureEnabled ? this._emissiveColor : BABYLON.Color3.BlackReadOnly);
  47342. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  47343. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  47344. // Misc
  47345. this._lightingInfos.x = this._directIntensity;
  47346. this._lightingInfos.y = this._emissiveIntensity;
  47347. this._lightingInfos.z = this._environmentIntensity;
  47348. this._lightingInfos.w = this._specularIntensity;
  47349. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  47350. }
  47351. // Textures
  47352. if (scene.texturesEnabled) {
  47353. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  47354. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  47355. }
  47356. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  47357. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  47358. }
  47359. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  47360. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  47361. }
  47362. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  47363. if (defines.LODBASEDMICROSFURACE) {
  47364. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  47365. }
  47366. else {
  47367. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  47368. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  47369. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  47370. }
  47371. }
  47372. if (defines.ENVIRONMENTBRDF) {
  47373. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  47374. }
  47375. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  47376. if (defines.LODBASEDMICROSFURACE) {
  47377. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  47378. }
  47379. else {
  47380. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  47381. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  47382. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  47383. }
  47384. }
  47385. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  47386. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  47387. }
  47388. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  47389. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  47390. }
  47391. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  47392. if (this._metallicTexture) {
  47393. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  47394. }
  47395. else if (this._reflectivityTexture) {
  47396. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  47397. }
  47398. if (this._microSurfaceTexture) {
  47399. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  47400. }
  47401. }
  47402. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  47403. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  47404. }
  47405. }
  47406. // Clip plane
  47407. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  47408. // Colors
  47409. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  47410. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  47411. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  47412. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  47413. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  47414. }
  47415. if (mustRebind || !this.isFrozen) {
  47416. // Lights
  47417. if (scene.lightsEnabled && !this._disableLighting) {
  47418. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._lightFalloff !== PBRBaseMaterial.LIGHTFALLOFF_STANDARD);
  47419. }
  47420. // View
  47421. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  47422. this.bindView(effect);
  47423. }
  47424. // Fog
  47425. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect, true);
  47426. // Morph targets
  47427. if (defines.NUM_MORPH_INFLUENCERS) {
  47428. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  47429. }
  47430. // image processing
  47431. this._imageProcessingConfiguration.bind(this._activeEffect);
  47432. // Log. depth
  47433. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  47434. }
  47435. this._uniformBuffer.update();
  47436. this._afterBind(mesh, this._activeEffect);
  47437. };
  47438. /**
  47439. * Returns the animatable textures.
  47440. * @returns - Array of animatable textures.
  47441. */
  47442. PBRBaseMaterial.prototype.getAnimatables = function () {
  47443. var results = [];
  47444. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  47445. results.push(this._albedoTexture);
  47446. }
  47447. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  47448. results.push(this._ambientTexture);
  47449. }
  47450. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  47451. results.push(this._opacityTexture);
  47452. }
  47453. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  47454. results.push(this._reflectionTexture);
  47455. }
  47456. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  47457. results.push(this._emissiveTexture);
  47458. }
  47459. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  47460. results.push(this._metallicTexture);
  47461. }
  47462. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  47463. results.push(this._reflectivityTexture);
  47464. }
  47465. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  47466. results.push(this._bumpTexture);
  47467. }
  47468. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  47469. results.push(this._lightmapTexture);
  47470. }
  47471. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  47472. results.push(this._refractionTexture);
  47473. }
  47474. return results;
  47475. };
  47476. /**
  47477. * Returns the texture used for reflections.
  47478. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  47479. */
  47480. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  47481. if (this._reflectionTexture) {
  47482. return this._reflectionTexture;
  47483. }
  47484. return this.getScene().environmentTexture;
  47485. };
  47486. /**
  47487. * Returns the texture used for refraction or null if none is used.
  47488. * @returns - Refection texture if present. If no refraction texture and refraction
  47489. * is linked with transparency, returns environment texture. Otherwise, returns null.
  47490. */
  47491. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  47492. if (this._refractionTexture) {
  47493. return this._refractionTexture;
  47494. }
  47495. if (this._linkRefractionWithTransparency) {
  47496. return this.getScene().environmentTexture;
  47497. }
  47498. return null;
  47499. };
  47500. /**
  47501. * Disposes the resources of the material.
  47502. * @param forceDisposeEffect - Forces the disposal of effects.
  47503. * @param forceDisposeTextures - Forces the disposal of all textures.
  47504. */
  47505. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  47506. if (forceDisposeTextures) {
  47507. if (this._albedoTexture) {
  47508. this._albedoTexture.dispose();
  47509. }
  47510. if (this._ambientTexture) {
  47511. this._ambientTexture.dispose();
  47512. }
  47513. if (this._opacityTexture) {
  47514. this._opacityTexture.dispose();
  47515. }
  47516. if (this._reflectionTexture) {
  47517. this._reflectionTexture.dispose();
  47518. }
  47519. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  47520. this._environmentBRDFTexture.dispose();
  47521. }
  47522. if (this._emissiveTexture) {
  47523. this._emissiveTexture.dispose();
  47524. }
  47525. if (this._metallicTexture) {
  47526. this._metallicTexture.dispose();
  47527. }
  47528. if (this._reflectivityTexture) {
  47529. this._reflectivityTexture.dispose();
  47530. }
  47531. if (this._bumpTexture) {
  47532. this._bumpTexture.dispose();
  47533. }
  47534. if (this._lightmapTexture) {
  47535. this._lightmapTexture.dispose();
  47536. }
  47537. if (this._refractionTexture) {
  47538. this._refractionTexture.dispose();
  47539. }
  47540. }
  47541. this._renderTargets.dispose();
  47542. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  47543. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  47544. }
  47545. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  47546. };
  47547. /**
  47548. * PBRMaterialLightFalloff Physical: light is falling off following the inverse squared distance law.
  47549. */
  47550. PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL = 0;
  47551. /**
  47552. * PBRMaterialLightFalloff gltf: light is falling off as described in the gltf moving to PBR document
  47553. * to enhance interoperability with other engines.
  47554. */
  47555. PBRBaseMaterial.LIGHTFALLOFF_GLTF = 1;
  47556. /**
  47557. * PBRMaterialLightFalloff Standard: light is falling off like in the standard material
  47558. * to enhance interoperability with other materials.
  47559. */
  47560. PBRBaseMaterial.LIGHTFALLOFF_STANDARD = 2;
  47561. /**
  47562. * Stores the reflectivity values based on metallic roughness workflow.
  47563. */
  47564. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  47565. __decorate([
  47566. BABYLON.serializeAsImageProcessingConfiguration()
  47567. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  47568. __decorate([
  47569. BABYLON.serialize()
  47570. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  47571. __decorate([
  47572. BABYLON.serialize()
  47573. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  47574. return PBRBaseMaterial;
  47575. }(BABYLON.PushMaterial));
  47576. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  47577. })(BABYLON || (BABYLON = {}));
  47578. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  47579. var BABYLON;
  47580. (function (BABYLON) {
  47581. /**
  47582. * The Physically based simple base material of BJS.
  47583. *
  47584. * This enables better naming and convention enforcements on top of the pbrMaterial.
  47585. * It is used as the base class for both the specGloss and metalRough conventions.
  47586. */
  47587. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  47588. __extends(PBRBaseSimpleMaterial, _super);
  47589. /**
  47590. * Instantiates a new PBRMaterial instance.
  47591. *
  47592. * @param name The material name
  47593. * @param scene The scene the material will be use in.
  47594. */
  47595. function PBRBaseSimpleMaterial(name, scene) {
  47596. var _this = _super.call(this, name, scene) || this;
  47597. /**
  47598. * Number of Simultaneous lights allowed on the material.
  47599. */
  47600. _this.maxSimultaneousLights = 4;
  47601. /**
  47602. * If sets to true, disables all the lights affecting the material.
  47603. */
  47604. _this.disableLighting = false;
  47605. /**
  47606. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  47607. */
  47608. _this.invertNormalMapX = false;
  47609. /**
  47610. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  47611. */
  47612. _this.invertNormalMapY = false;
  47613. /**
  47614. * Emissivie color used to self-illuminate the model.
  47615. */
  47616. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  47617. /**
  47618. * Occlusion Channel Strenght.
  47619. */
  47620. _this.occlusionStrength = 1.0;
  47621. /**
  47622. * If true, the light map contains occlusion information instead of lighting info.
  47623. */
  47624. _this.useLightmapAsShadowmap = false;
  47625. _this._useAlphaFromAlbedoTexture = true;
  47626. _this._useAmbientInGrayScale = true;
  47627. return _this;
  47628. }
  47629. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  47630. /**
  47631. * Gets the current double sided mode.
  47632. */
  47633. get: function () {
  47634. return this._twoSidedLighting;
  47635. },
  47636. /**
  47637. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  47638. */
  47639. set: function (value) {
  47640. if (this._twoSidedLighting === value) {
  47641. return;
  47642. }
  47643. this._twoSidedLighting = value;
  47644. this.backFaceCulling = !value;
  47645. this._markAllSubMeshesAsTexturesDirty();
  47646. },
  47647. enumerable: true,
  47648. configurable: true
  47649. });
  47650. /**
  47651. * Return the active textures of the material.
  47652. */
  47653. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  47654. var activeTextures = _super.prototype.getActiveTextures.call(this);
  47655. if (this.environmentTexture) {
  47656. activeTextures.push(this.environmentTexture);
  47657. }
  47658. if (this.normalTexture) {
  47659. activeTextures.push(this.normalTexture);
  47660. }
  47661. if (this.emissiveTexture) {
  47662. activeTextures.push(this.emissiveTexture);
  47663. }
  47664. if (this.occlusionTexture) {
  47665. activeTextures.push(this.occlusionTexture);
  47666. }
  47667. if (this.lightmapTexture) {
  47668. activeTextures.push(this.lightmapTexture);
  47669. }
  47670. return activeTextures;
  47671. };
  47672. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  47673. if (_super.prototype.hasTexture.call(this, texture)) {
  47674. return true;
  47675. }
  47676. if (this.lightmapTexture === texture) {
  47677. return true;
  47678. }
  47679. return false;
  47680. };
  47681. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  47682. return "PBRBaseSimpleMaterial";
  47683. };
  47684. __decorate([
  47685. BABYLON.serialize(),
  47686. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  47687. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  47688. __decorate([
  47689. BABYLON.serialize(),
  47690. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  47691. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  47692. __decorate([
  47693. BABYLON.serializeAsTexture(),
  47694. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  47695. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  47696. __decorate([
  47697. BABYLON.serialize(),
  47698. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47699. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  47700. __decorate([
  47701. BABYLON.serialize(),
  47702. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47703. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  47704. __decorate([
  47705. BABYLON.serializeAsTexture(),
  47706. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  47707. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  47708. __decorate([
  47709. BABYLON.serializeAsColor3("emissive"),
  47710. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47711. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  47712. __decorate([
  47713. BABYLON.serializeAsTexture(),
  47714. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47715. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  47716. __decorate([
  47717. BABYLON.serialize(),
  47718. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  47719. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  47720. __decorate([
  47721. BABYLON.serializeAsTexture(),
  47722. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  47723. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  47724. __decorate([
  47725. BABYLON.serialize(),
  47726. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  47727. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  47728. __decorate([
  47729. BABYLON.serialize()
  47730. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  47731. __decorate([
  47732. BABYLON.serializeAsTexture(),
  47733. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  47734. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  47735. __decorate([
  47736. BABYLON.serialize(),
  47737. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47738. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  47739. return PBRBaseSimpleMaterial;
  47740. }(BABYLON.PBRBaseMaterial));
  47741. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  47742. })(BABYLON || (BABYLON = {}));
  47743. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  47744. var BABYLON;
  47745. (function (BABYLON) {
  47746. /**
  47747. * The Physically based material of BJS.
  47748. *
  47749. * This offers the main features of a standard PBR material.
  47750. * For more information, please refer to the documentation :
  47751. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  47752. */
  47753. var PBRMaterial = /** @class */ (function (_super) {
  47754. __extends(PBRMaterial, _super);
  47755. /**
  47756. * Instantiates a new PBRMaterial instance.
  47757. *
  47758. * @param name The material name
  47759. * @param scene The scene the material will be use in.
  47760. */
  47761. function PBRMaterial(name, scene) {
  47762. var _this = _super.call(this, name, scene) || this;
  47763. /**
  47764. * Intensity of the direct lights e.g. the four lights available in your scene.
  47765. * This impacts both the direct diffuse and specular highlights.
  47766. */
  47767. _this.directIntensity = 1.0;
  47768. /**
  47769. * Intensity of the emissive part of the material.
  47770. * This helps controlling the emissive effect without modifying the emissive color.
  47771. */
  47772. _this.emissiveIntensity = 1.0;
  47773. /**
  47774. * Intensity of the environment e.g. how much the environment will light the object
  47775. * either through harmonics for rough material or through the refelction for shiny ones.
  47776. */
  47777. _this.environmentIntensity = 1.0;
  47778. /**
  47779. * This is a special control allowing the reduction of the specular highlights coming from the
  47780. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  47781. */
  47782. _this.specularIntensity = 1.0;
  47783. /**
  47784. * Debug Control allowing disabling the bump map on this material.
  47785. */
  47786. _this.disableBumpMap = false;
  47787. /**
  47788. * AKA Occlusion Texture Intensity in other nomenclature.
  47789. */
  47790. _this.ambientTextureStrength = 1.0;
  47791. /**
  47792. * Defines how much the AO map is occluding the analytical lights (point spot...).
  47793. * 1 means it completely occludes it
  47794. * 0 mean it has no impact
  47795. */
  47796. _this.ambientTextureImpactOnAnalyticalLights = PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS;
  47797. /**
  47798. * The color of a material in ambient lighting.
  47799. */
  47800. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  47801. /**
  47802. * AKA Diffuse Color in other nomenclature.
  47803. */
  47804. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  47805. /**
  47806. * AKA Specular Color in other nomenclature.
  47807. */
  47808. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  47809. /**
  47810. * The color reflected from the material.
  47811. */
  47812. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  47813. /**
  47814. * The color emitted from the material.
  47815. */
  47816. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  47817. /**
  47818. * AKA Glossiness in other nomenclature.
  47819. */
  47820. _this.microSurface = 1.0;
  47821. /**
  47822. * source material index of refraction (IOR)' / 'destination material IOR.
  47823. */
  47824. _this.indexOfRefraction = 0.66;
  47825. /**
  47826. * Controls if refraction needs to be inverted on Y. This could be useful for procedural texture.
  47827. */
  47828. _this.invertRefractionY = false;
  47829. /**
  47830. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  47831. * Materials half opaque for instance using refraction could benefit from this control.
  47832. */
  47833. _this.linkRefractionWithTransparency = false;
  47834. /**
  47835. * If true, the light map contains occlusion information instead of lighting info.
  47836. */
  47837. _this.useLightmapAsShadowmap = false;
  47838. /**
  47839. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  47840. */
  47841. _this.useAlphaFromAlbedoTexture = false;
  47842. /**
  47843. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  47844. */
  47845. _this.forceAlphaTest = false;
  47846. /**
  47847. * Defines the alpha limits in alpha test mode.
  47848. */
  47849. _this.alphaCutOff = 0.4;
  47850. /**
  47851. * Specifies that the material will keep the specular highlights over a transparent surface (only the most limunous ones).
  47852. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  47853. */
  47854. _this.useSpecularOverAlpha = true;
  47855. /**
  47856. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  47857. */
  47858. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  47859. /**
  47860. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  47861. */
  47862. _this.useRoughnessFromMetallicTextureAlpha = true;
  47863. /**
  47864. * Specifies if the metallic texture contains the roughness information in its green channel.
  47865. */
  47866. _this.useRoughnessFromMetallicTextureGreen = false;
  47867. /**
  47868. * Specifies if the metallic texture contains the metallness information in its blue channel.
  47869. */
  47870. _this.useMetallnessFromMetallicTextureBlue = false;
  47871. /**
  47872. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  47873. */
  47874. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  47875. /**
  47876. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  47877. */
  47878. _this.useAmbientInGrayScale = false;
  47879. /**
  47880. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  47881. * The material will try to infer what glossiness each pixel should be.
  47882. */
  47883. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  47884. /**
  47885. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  47886. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  47887. */
  47888. _this.useRadianceOverAlpha = true;
  47889. /**
  47890. * Allows using an object space normal map (instead of tangent space).
  47891. */
  47892. _this.useObjectSpaceNormalMap = false;
  47893. /**
  47894. * Allows using the bump map in parallax mode.
  47895. */
  47896. _this.useParallax = false;
  47897. /**
  47898. * Allows using the bump map in parallax occlusion mode.
  47899. */
  47900. _this.useParallaxOcclusion = false;
  47901. /**
  47902. * Controls the scale bias of the parallax mode.
  47903. */
  47904. _this.parallaxScaleBias = 0.05;
  47905. /**
  47906. * If sets to true, disables all the lights affecting the material.
  47907. */
  47908. _this.disableLighting = false;
  47909. /**
  47910. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  47911. */
  47912. _this.forceIrradianceInFragment = false;
  47913. /**
  47914. * Number of Simultaneous lights allowed on the material.
  47915. */
  47916. _this.maxSimultaneousLights = 4;
  47917. /**
  47918. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  47919. */
  47920. _this.invertNormalMapX = false;
  47921. /**
  47922. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  47923. */
  47924. _this.invertNormalMapY = false;
  47925. /**
  47926. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  47927. */
  47928. _this.twoSidedLighting = false;
  47929. /**
  47930. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  47931. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  47932. */
  47933. _this.useAlphaFresnel = false;
  47934. /**
  47935. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  47936. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  47937. */
  47938. _this.useLinearAlphaFresnel = false;
  47939. /**
  47940. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  47941. * And/Or occlude the blended part.
  47942. */
  47943. _this.environmentBRDFTexture = null;
  47944. /**
  47945. * Force normal to face away from face.
  47946. */
  47947. _this.forceNormalForward = false;
  47948. /**
  47949. * Enables specular anti aliasing in the PBR shader.
  47950. * It will both interacts on the Geometry for analytical and IBL lighting.
  47951. * It also prefilter the roughness map based on the bump values.
  47952. */
  47953. _this.enableSpecularAntiAliasing = false;
  47954. /**
  47955. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  47956. * makes the reflect vector face the model (under horizon).
  47957. */
  47958. _this.useHorizonOcclusion = true;
  47959. /**
  47960. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  47961. * too much the area relying on ambient texture to define their ambient occlusion.
  47962. */
  47963. _this.useRadianceOcclusion = true;
  47964. /**
  47965. * If set to true, no lighting calculations will be applied.
  47966. */
  47967. _this.unlit = false;
  47968. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  47969. return _this;
  47970. }
  47971. Object.defineProperty(PBRMaterial.prototype, "usePhysicalLightFalloff", {
  47972. /**
  47973. * BJS is using an harcoded light falloff based on a manually sets up range.
  47974. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  47975. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  47976. */
  47977. get: function () {
  47978. return this._lightFalloff === BABYLON.PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  47979. },
  47980. /**
  47981. * BJS is using an harcoded light falloff based on a manually sets up range.
  47982. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  47983. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  47984. */
  47985. set: function (value) {
  47986. if (value !== this.usePhysicalLightFalloff) {
  47987. // Ensure the effect will be rebuilt.
  47988. this._markAllSubMeshesAsTexturesDirty();
  47989. if (value) {
  47990. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  47991. }
  47992. else {
  47993. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_STANDARD;
  47994. }
  47995. }
  47996. },
  47997. enumerable: true,
  47998. configurable: true
  47999. });
  48000. Object.defineProperty(PBRMaterial.prototype, "useGLTFLightFalloff", {
  48001. /**
  48002. * In order to support the falloff compatibility with gltf, a special mode has been added
  48003. * to reproduce the gltf light falloff.
  48004. */
  48005. get: function () {
  48006. return this._lightFalloff === BABYLON.PBRBaseMaterial.LIGHTFALLOFF_GLTF;
  48007. },
  48008. /**
  48009. * In order to support the falloff compatibility with gltf, a special mode has been added
  48010. * to reproduce the gltf light falloff.
  48011. */
  48012. set: function (value) {
  48013. if (value !== this.useGLTFLightFalloff) {
  48014. // Ensure the effect will be rebuilt.
  48015. this._markAllSubMeshesAsTexturesDirty();
  48016. if (value) {
  48017. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_GLTF;
  48018. }
  48019. else {
  48020. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_STANDARD;
  48021. }
  48022. }
  48023. },
  48024. enumerable: true,
  48025. configurable: true
  48026. });
  48027. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  48028. /**
  48029. * Gets the image processing configuration used either in this material.
  48030. */
  48031. get: function () {
  48032. return this._imageProcessingConfiguration;
  48033. },
  48034. /**
  48035. * Sets the Default image processing configuration used either in the this material.
  48036. *
  48037. * If sets to null, the scene one is in use.
  48038. */
  48039. set: function (value) {
  48040. this._attachImageProcessingConfiguration(value);
  48041. // Ensure the effect will be rebuilt.
  48042. this._markAllSubMeshesAsTexturesDirty();
  48043. },
  48044. enumerable: true,
  48045. configurable: true
  48046. });
  48047. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  48048. /**
  48049. * Gets wether the color curves effect is enabled.
  48050. */
  48051. get: function () {
  48052. return this.imageProcessingConfiguration.colorCurvesEnabled;
  48053. },
  48054. /**
  48055. * Sets wether the color curves effect is enabled.
  48056. */
  48057. set: function (value) {
  48058. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  48059. },
  48060. enumerable: true,
  48061. configurable: true
  48062. });
  48063. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  48064. /**
  48065. * Gets wether the color grading effect is enabled.
  48066. */
  48067. get: function () {
  48068. return this.imageProcessingConfiguration.colorGradingEnabled;
  48069. },
  48070. /**
  48071. * Gets wether the color grading effect is enabled.
  48072. */
  48073. set: function (value) {
  48074. this.imageProcessingConfiguration.colorGradingEnabled = value;
  48075. },
  48076. enumerable: true,
  48077. configurable: true
  48078. });
  48079. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  48080. /**
  48081. * Gets wether tonemapping is enabled or not.
  48082. */
  48083. get: function () {
  48084. return this._imageProcessingConfiguration.toneMappingEnabled;
  48085. },
  48086. /**
  48087. * Sets wether tonemapping is enabled or not
  48088. */
  48089. set: function (value) {
  48090. this._imageProcessingConfiguration.toneMappingEnabled = value;
  48091. },
  48092. enumerable: true,
  48093. configurable: true
  48094. });
  48095. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  48096. /**
  48097. * The camera exposure used on this material.
  48098. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  48099. * This corresponds to a photographic exposure.
  48100. */
  48101. get: function () {
  48102. return this._imageProcessingConfiguration.exposure;
  48103. },
  48104. /**
  48105. * The camera exposure used on this material.
  48106. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  48107. * This corresponds to a photographic exposure.
  48108. */
  48109. set: function (value) {
  48110. this._imageProcessingConfiguration.exposure = value;
  48111. },
  48112. enumerable: true,
  48113. configurable: true
  48114. });
  48115. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  48116. /**
  48117. * Gets The camera contrast used on this material.
  48118. */
  48119. get: function () {
  48120. return this._imageProcessingConfiguration.contrast;
  48121. },
  48122. /**
  48123. * Sets The camera contrast used on this material.
  48124. */
  48125. set: function (value) {
  48126. this._imageProcessingConfiguration.contrast = value;
  48127. },
  48128. enumerable: true,
  48129. configurable: true
  48130. });
  48131. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  48132. /**
  48133. * Gets the Color Grading 2D Lookup Texture.
  48134. */
  48135. get: function () {
  48136. return this._imageProcessingConfiguration.colorGradingTexture;
  48137. },
  48138. /**
  48139. * Sets the Color Grading 2D Lookup Texture.
  48140. */
  48141. set: function (value) {
  48142. this._imageProcessingConfiguration.colorGradingTexture = value;
  48143. },
  48144. enumerable: true,
  48145. configurable: true
  48146. });
  48147. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  48148. /**
  48149. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  48150. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  48151. * 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;
  48152. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  48153. */
  48154. get: function () {
  48155. return this._imageProcessingConfiguration.colorCurves;
  48156. },
  48157. /**
  48158. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  48159. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  48160. * 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;
  48161. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  48162. */
  48163. set: function (value) {
  48164. this._imageProcessingConfiguration.colorCurves = value;
  48165. },
  48166. enumerable: true,
  48167. configurable: true
  48168. });
  48169. /**
  48170. * Returns the name of this material class.
  48171. */
  48172. PBRMaterial.prototype.getClassName = function () {
  48173. return "PBRMaterial";
  48174. };
  48175. /**
  48176. * Returns an array of the actively used textures.
  48177. * @returns - Array of BaseTextures
  48178. */
  48179. PBRMaterial.prototype.getActiveTextures = function () {
  48180. var activeTextures = _super.prototype.getActiveTextures.call(this);
  48181. if (this._albedoTexture) {
  48182. activeTextures.push(this._albedoTexture);
  48183. }
  48184. if (this._ambientTexture) {
  48185. activeTextures.push(this._ambientTexture);
  48186. }
  48187. if (this._opacityTexture) {
  48188. activeTextures.push(this._opacityTexture);
  48189. }
  48190. if (this._reflectionTexture) {
  48191. activeTextures.push(this._reflectionTexture);
  48192. }
  48193. if (this._emissiveTexture) {
  48194. activeTextures.push(this._emissiveTexture);
  48195. }
  48196. if (this._reflectivityTexture) {
  48197. activeTextures.push(this._reflectivityTexture);
  48198. }
  48199. if (this._metallicTexture) {
  48200. activeTextures.push(this._metallicTexture);
  48201. }
  48202. if (this._microSurfaceTexture) {
  48203. activeTextures.push(this._microSurfaceTexture);
  48204. }
  48205. if (this._bumpTexture) {
  48206. activeTextures.push(this._bumpTexture);
  48207. }
  48208. if (this._lightmapTexture) {
  48209. activeTextures.push(this._lightmapTexture);
  48210. }
  48211. if (this._refractionTexture) {
  48212. activeTextures.push(this._refractionTexture);
  48213. }
  48214. return activeTextures;
  48215. };
  48216. /**
  48217. * Checks to see if a texture is used in the material.
  48218. * @param texture - Base texture to use.
  48219. * @returns - Boolean specifying if a texture is used in the material.
  48220. */
  48221. PBRMaterial.prototype.hasTexture = function (texture) {
  48222. if (_super.prototype.hasTexture.call(this, texture)) {
  48223. return true;
  48224. }
  48225. if (this._albedoTexture === texture) {
  48226. return true;
  48227. }
  48228. if (this._ambientTexture === texture) {
  48229. return true;
  48230. }
  48231. if (this._opacityTexture === texture) {
  48232. return true;
  48233. }
  48234. if (this._reflectionTexture === texture) {
  48235. return true;
  48236. }
  48237. if (this._reflectivityTexture === texture) {
  48238. return true;
  48239. }
  48240. if (this._metallicTexture === texture) {
  48241. return true;
  48242. }
  48243. if (this._microSurfaceTexture === texture) {
  48244. return true;
  48245. }
  48246. if (this._bumpTexture === texture) {
  48247. return true;
  48248. }
  48249. if (this._lightmapTexture === texture) {
  48250. return true;
  48251. }
  48252. if (this._refractionTexture === texture) {
  48253. return true;
  48254. }
  48255. return false;
  48256. };
  48257. /**
  48258. * Makes a duplicate of the current material.
  48259. * @param name - name to use for the new material.
  48260. */
  48261. PBRMaterial.prototype.clone = function (name) {
  48262. var _this = this;
  48263. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  48264. clone.id = name;
  48265. clone.name = name;
  48266. return clone;
  48267. };
  48268. /**
  48269. * Serializes this PBR Material.
  48270. * @returns - An object with the serialized material.
  48271. */
  48272. PBRMaterial.prototype.serialize = function () {
  48273. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  48274. serializationObject.customType = "BABYLON.PBRMaterial";
  48275. return serializationObject;
  48276. };
  48277. // Statics
  48278. /**
  48279. * Parses a PBR Material from a serialized object.
  48280. * @param source - Serialized object.
  48281. * @param scene - BJS scene instance.
  48282. * @param rootUrl - url for the scene object
  48283. * @returns - PBRMaterial
  48284. */
  48285. PBRMaterial.Parse = function (source, scene, rootUrl) {
  48286. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  48287. };
  48288. /**
  48289. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  48290. */
  48291. PBRMaterial.PBRMATERIAL_OPAQUE = 0;
  48292. /**
  48293. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  48294. */
  48295. PBRMaterial.PBRMATERIAL_ALPHATEST = 1;
  48296. /**
  48297. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  48298. */
  48299. PBRMaterial.PBRMATERIAL_ALPHABLEND = 2;
  48300. /**
  48301. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  48302. * They are also discarded below the alpha cutoff threshold to improve performances.
  48303. */
  48304. PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND = 3;
  48305. /**
  48306. * Defines the default value of how much AO map is occluding the analytical lights
  48307. * (point spot...).
  48308. */
  48309. PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS = 1;
  48310. __decorate([
  48311. BABYLON.serialize(),
  48312. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  48313. ], PBRMaterial.prototype, "directIntensity", void 0);
  48314. __decorate([
  48315. BABYLON.serialize(),
  48316. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  48317. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  48318. __decorate([
  48319. BABYLON.serialize(),
  48320. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  48321. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  48322. __decorate([
  48323. BABYLON.serialize(),
  48324. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  48325. ], PBRMaterial.prototype, "specularIntensity", void 0);
  48326. __decorate([
  48327. BABYLON.serialize(),
  48328. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  48329. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  48330. __decorate([
  48331. BABYLON.serializeAsTexture(),
  48332. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  48333. ], PBRMaterial.prototype, "albedoTexture", void 0);
  48334. __decorate([
  48335. BABYLON.serializeAsTexture(),
  48336. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  48337. ], PBRMaterial.prototype, "ambientTexture", void 0);
  48338. __decorate([
  48339. BABYLON.serialize(),
  48340. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  48341. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  48342. __decorate([
  48343. BABYLON.serialize(),
  48344. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  48345. ], PBRMaterial.prototype, "ambientTextureImpactOnAnalyticalLights", void 0);
  48346. __decorate([
  48347. BABYLON.serializeAsTexture(),
  48348. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  48349. ], PBRMaterial.prototype, "opacityTexture", void 0);
  48350. __decorate([
  48351. BABYLON.serializeAsTexture(),
  48352. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  48353. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  48354. __decorate([
  48355. BABYLON.serializeAsTexture(),
  48356. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  48357. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  48358. __decorate([
  48359. BABYLON.serializeAsTexture(),
  48360. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  48361. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  48362. __decorate([
  48363. BABYLON.serializeAsTexture(),
  48364. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  48365. ], PBRMaterial.prototype, "metallicTexture", void 0);
  48366. __decorate([
  48367. BABYLON.serialize(),
  48368. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  48369. ], PBRMaterial.prototype, "metallic", void 0);
  48370. __decorate([
  48371. BABYLON.serialize(),
  48372. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  48373. ], PBRMaterial.prototype, "roughness", void 0);
  48374. __decorate([
  48375. BABYLON.serializeAsTexture(),
  48376. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  48377. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  48378. __decorate([
  48379. BABYLON.serializeAsTexture(),
  48380. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  48381. ], PBRMaterial.prototype, "bumpTexture", void 0);
  48382. __decorate([
  48383. BABYLON.serializeAsTexture(),
  48384. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  48385. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  48386. __decorate([
  48387. BABYLON.serializeAsTexture(),
  48388. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  48389. ], PBRMaterial.prototype, "refractionTexture", void 0);
  48390. __decorate([
  48391. BABYLON.serializeAsColor3("ambient"),
  48392. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  48393. ], PBRMaterial.prototype, "ambientColor", void 0);
  48394. __decorate([
  48395. BABYLON.serializeAsColor3("albedo"),
  48396. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  48397. ], PBRMaterial.prototype, "albedoColor", void 0);
  48398. __decorate([
  48399. BABYLON.serializeAsColor3("reflectivity"),
  48400. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  48401. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  48402. __decorate([
  48403. BABYLON.serializeAsColor3("reflection"),
  48404. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  48405. ], PBRMaterial.prototype, "reflectionColor", void 0);
  48406. __decorate([
  48407. BABYLON.serializeAsColor3("emissive"),
  48408. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  48409. ], PBRMaterial.prototype, "emissiveColor", void 0);
  48410. __decorate([
  48411. BABYLON.serialize(),
  48412. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  48413. ], PBRMaterial.prototype, "microSurface", void 0);
  48414. __decorate([
  48415. BABYLON.serialize(),
  48416. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  48417. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  48418. __decorate([
  48419. BABYLON.serialize(),
  48420. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  48421. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  48422. __decorate([
  48423. BABYLON.serialize(),
  48424. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  48425. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  48426. __decorate([
  48427. BABYLON.serialize(),
  48428. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  48429. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  48430. __decorate([
  48431. BABYLON.serialize(),
  48432. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  48433. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  48434. __decorate([
  48435. BABYLON.serialize(),
  48436. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  48437. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  48438. __decorate([
  48439. BABYLON.serialize(),
  48440. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  48441. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  48442. __decorate([
  48443. BABYLON.serialize(),
  48444. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  48445. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  48446. __decorate([
  48447. BABYLON.serialize(),
  48448. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  48449. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  48450. __decorate([
  48451. BABYLON.serialize(),
  48452. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  48453. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  48454. __decorate([
  48455. BABYLON.serialize(),
  48456. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  48457. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  48458. __decorate([
  48459. BABYLON.serialize(),
  48460. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  48461. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  48462. __decorate([
  48463. BABYLON.serialize(),
  48464. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  48465. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  48466. __decorate([
  48467. BABYLON.serialize(),
  48468. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  48469. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  48470. __decorate([
  48471. BABYLON.serialize(),
  48472. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  48473. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  48474. __decorate([
  48475. BABYLON.serialize()
  48476. ], PBRMaterial.prototype, "usePhysicalLightFalloff", null);
  48477. __decorate([
  48478. BABYLON.serialize()
  48479. ], PBRMaterial.prototype, "useGLTFLightFalloff", null);
  48480. __decorate([
  48481. BABYLON.serialize(),
  48482. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  48483. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  48484. __decorate([
  48485. BABYLON.serialize(),
  48486. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  48487. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  48488. __decorate([
  48489. BABYLON.serialize(),
  48490. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  48491. ], PBRMaterial.prototype, "useParallax", void 0);
  48492. __decorate([
  48493. BABYLON.serialize(),
  48494. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  48495. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  48496. __decorate([
  48497. BABYLON.serialize(),
  48498. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  48499. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  48500. __decorate([
  48501. BABYLON.serialize(),
  48502. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  48503. ], PBRMaterial.prototype, "disableLighting", void 0);
  48504. __decorate([
  48505. BABYLON.serialize(),
  48506. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  48507. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  48508. __decorate([
  48509. BABYLON.serialize(),
  48510. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  48511. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  48512. __decorate([
  48513. BABYLON.serialize(),
  48514. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  48515. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  48516. __decorate([
  48517. BABYLON.serialize(),
  48518. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  48519. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  48520. __decorate([
  48521. BABYLON.serialize(),
  48522. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  48523. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  48524. __decorate([
  48525. BABYLON.serialize(),
  48526. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  48527. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  48528. __decorate([
  48529. BABYLON.serialize(),
  48530. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  48531. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  48532. __decorate([
  48533. BABYLON.serializeAsTexture(),
  48534. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  48535. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  48536. __decorate([
  48537. BABYLON.serialize(),
  48538. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  48539. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  48540. __decorate([
  48541. BABYLON.serialize(),
  48542. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  48543. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  48544. __decorate([
  48545. BABYLON.serialize(),
  48546. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  48547. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  48548. __decorate([
  48549. BABYLON.serialize(),
  48550. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  48551. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  48552. __decorate([
  48553. BABYLON.serialize(),
  48554. BABYLON.expandToProperty("_markAllSubMeshesAsMiscDirty")
  48555. ], PBRMaterial.prototype, "unlit", void 0);
  48556. return PBRMaterial;
  48557. }(BABYLON.PBRBaseMaterial));
  48558. BABYLON.PBRMaterial = PBRMaterial;
  48559. })(BABYLON || (BABYLON = {}));
  48560. //# sourceMappingURL=babylon.pbrMaterial.js.map
  48561. var BABYLON;
  48562. (function (BABYLON) {
  48563. /**
  48564. * The PBR material of BJS following the metal roughness convention.
  48565. *
  48566. * This fits to the PBR convention in the GLTF definition:
  48567. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  48568. */
  48569. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  48570. __extends(PBRMetallicRoughnessMaterial, _super);
  48571. /**
  48572. * Instantiates a new PBRMetalRoughnessMaterial instance.
  48573. *
  48574. * @param name The material name
  48575. * @param scene The scene the material will be use in.
  48576. */
  48577. function PBRMetallicRoughnessMaterial(name, scene) {
  48578. var _this = _super.call(this, name, scene) || this;
  48579. _this._useRoughnessFromMetallicTextureAlpha = false;
  48580. _this._useRoughnessFromMetallicTextureGreen = true;
  48581. _this._useMetallnessFromMetallicTextureBlue = true;
  48582. _this.metallic = 1.0;
  48583. _this.roughness = 1.0;
  48584. return _this;
  48585. }
  48586. /**
  48587. * Return the currrent class name of the material.
  48588. */
  48589. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  48590. return "PBRMetallicRoughnessMaterial";
  48591. };
  48592. /**
  48593. * Return the active textures of the material.
  48594. */
  48595. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  48596. var activeTextures = _super.prototype.getActiveTextures.call(this);
  48597. if (this.baseTexture) {
  48598. activeTextures.push(this.baseTexture);
  48599. }
  48600. if (this.metallicRoughnessTexture) {
  48601. activeTextures.push(this.metallicRoughnessTexture);
  48602. }
  48603. return activeTextures;
  48604. };
  48605. /**
  48606. * Checks to see if a texture is used in the material.
  48607. * @param texture - Base texture to use.
  48608. * @returns - Boolean specifying if a texture is used in the material.
  48609. */
  48610. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  48611. if (_super.prototype.hasTexture.call(this, texture)) {
  48612. return true;
  48613. }
  48614. if (this.baseTexture === texture) {
  48615. return true;
  48616. }
  48617. if (this.metallicRoughnessTexture === texture) {
  48618. return true;
  48619. }
  48620. return false;
  48621. };
  48622. /**
  48623. * Makes a duplicate of the current material.
  48624. * @param name - name to use for the new material.
  48625. */
  48626. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  48627. var _this = this;
  48628. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  48629. clone.id = name;
  48630. clone.name = name;
  48631. return clone;
  48632. };
  48633. /**
  48634. * Serialize the material to a parsable JSON object.
  48635. */
  48636. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  48637. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  48638. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  48639. return serializationObject;
  48640. };
  48641. /**
  48642. * Parses a JSON object correponding to the serialize function.
  48643. */
  48644. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  48645. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  48646. };
  48647. __decorate([
  48648. BABYLON.serializeAsColor3(),
  48649. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  48650. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  48651. __decorate([
  48652. BABYLON.serializeAsTexture(),
  48653. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  48654. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  48655. __decorate([
  48656. BABYLON.serialize(),
  48657. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  48658. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  48659. __decorate([
  48660. BABYLON.serialize(),
  48661. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  48662. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  48663. __decorate([
  48664. BABYLON.serializeAsTexture(),
  48665. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  48666. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  48667. return PBRMetallicRoughnessMaterial;
  48668. }(BABYLON.PBRBaseSimpleMaterial));
  48669. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  48670. })(BABYLON || (BABYLON = {}));
  48671. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  48672. var BABYLON;
  48673. (function (BABYLON) {
  48674. /**
  48675. * The PBR material of BJS following the specular glossiness convention.
  48676. *
  48677. * This fits to the PBR convention in the GLTF definition:
  48678. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  48679. */
  48680. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  48681. __extends(PBRSpecularGlossinessMaterial, _super);
  48682. /**
  48683. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  48684. *
  48685. * @param name The material name
  48686. * @param scene The scene the material will be use in.
  48687. */
  48688. function PBRSpecularGlossinessMaterial(name, scene) {
  48689. var _this = _super.call(this, name, scene) || this;
  48690. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  48691. return _this;
  48692. }
  48693. /**
  48694. * Return the currrent class name of the material.
  48695. */
  48696. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  48697. return "PBRSpecularGlossinessMaterial";
  48698. };
  48699. /**
  48700. * Return the active textures of the material.
  48701. */
  48702. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  48703. var activeTextures = _super.prototype.getActiveTextures.call(this);
  48704. if (this.diffuseTexture) {
  48705. activeTextures.push(this.diffuseTexture);
  48706. }
  48707. if (this.specularGlossinessTexture) {
  48708. activeTextures.push(this.specularGlossinessTexture);
  48709. }
  48710. return activeTextures;
  48711. };
  48712. /**
  48713. * Checks to see if a texture is used in the material.
  48714. * @param texture - Base texture to use.
  48715. * @returns - Boolean specifying if a texture is used in the material.
  48716. */
  48717. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  48718. if (_super.prototype.hasTexture.call(this, texture)) {
  48719. return true;
  48720. }
  48721. if (this.diffuseTexture === texture) {
  48722. return true;
  48723. }
  48724. if (this.specularGlossinessTexture === texture) {
  48725. return true;
  48726. }
  48727. return false;
  48728. };
  48729. /**
  48730. * Makes a duplicate of the current material.
  48731. * @param name - name to use for the new material.
  48732. */
  48733. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  48734. var _this = this;
  48735. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  48736. clone.id = name;
  48737. clone.name = name;
  48738. return clone;
  48739. };
  48740. /**
  48741. * Serialize the material to a parsable JSON object.
  48742. */
  48743. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  48744. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  48745. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  48746. return serializationObject;
  48747. };
  48748. /**
  48749. * Parses a JSON object correponding to the serialize function.
  48750. */
  48751. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  48752. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  48753. };
  48754. __decorate([
  48755. BABYLON.serializeAsColor3("diffuse"),
  48756. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  48757. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  48758. __decorate([
  48759. BABYLON.serializeAsTexture(),
  48760. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  48761. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  48762. __decorate([
  48763. BABYLON.serializeAsColor3("specular"),
  48764. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  48765. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  48766. __decorate([
  48767. BABYLON.serialize(),
  48768. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  48769. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  48770. __decorate([
  48771. BABYLON.serializeAsTexture(),
  48772. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  48773. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  48774. return PBRSpecularGlossinessMaterial;
  48775. }(BABYLON.PBRBaseSimpleMaterial));
  48776. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  48777. })(BABYLON || (BABYLON = {}));
  48778. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  48779. var BABYLON;
  48780. (function (BABYLON) {
  48781. /**
  48782. * @ignore
  48783. * This is a list of all the different input types that are available in the application.
  48784. * Fo instance: ArcRotateCameraGamepadInput...
  48785. */
  48786. BABYLON.CameraInputTypes = {};
  48787. /**
  48788. * This represents the input manager used within a camera.
  48789. * It helps dealing with all the different kind of input attached to a camera.
  48790. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  48791. */
  48792. var CameraInputsManager = /** @class */ (function () {
  48793. /**
  48794. * Instantiate a new Camera Input Manager.
  48795. * @param camera Defines the camera the input manager blongs to
  48796. */
  48797. function CameraInputsManager(camera) {
  48798. this.attached = {};
  48799. this.camera = camera;
  48800. this.checkInputs = function () { };
  48801. }
  48802. /**
  48803. * Add an input method to a camera
  48804. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  48805. * @param input camera input method
  48806. */
  48807. CameraInputsManager.prototype.add = function (input) {
  48808. var type = input.getSimpleName();
  48809. if (this.attached[type]) {
  48810. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  48811. return;
  48812. }
  48813. this.attached[type] = input;
  48814. input.camera = this.camera;
  48815. //for checkInputs, we are dynamically creating a function
  48816. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  48817. if (input.checkInputs) {
  48818. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  48819. }
  48820. if (this.attachedElement) {
  48821. input.attachControl(this.attachedElement);
  48822. }
  48823. };
  48824. /**
  48825. * Remove a specific input method from a camera
  48826. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  48827. * @param inputToRemove camera input method
  48828. */
  48829. CameraInputsManager.prototype.remove = function (inputToRemove) {
  48830. for (var cam in this.attached) {
  48831. var input = this.attached[cam];
  48832. if (input === inputToRemove) {
  48833. input.detachControl(this.attachedElement);
  48834. input.camera = null;
  48835. delete this.attached[cam];
  48836. this.rebuildInputCheck();
  48837. }
  48838. }
  48839. };
  48840. /**
  48841. * Remove a specific input type from a camera
  48842. * example: camera.inputs.remove("ArcRotateCameraGamepadInput");
  48843. * @param inputType the type of the input to remove
  48844. */
  48845. CameraInputsManager.prototype.removeByType = function (inputType) {
  48846. for (var cam in this.attached) {
  48847. var input = this.attached[cam];
  48848. if (input.getClassName() === inputType) {
  48849. input.detachControl(this.attachedElement);
  48850. input.camera = null;
  48851. delete this.attached[cam];
  48852. this.rebuildInputCheck();
  48853. }
  48854. }
  48855. };
  48856. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  48857. var current = this.checkInputs;
  48858. return function () {
  48859. current();
  48860. fn();
  48861. };
  48862. };
  48863. /**
  48864. * Attach the input controls to the currently attached dom element to listen the events from.
  48865. * @param input Defines the input to attach
  48866. */
  48867. CameraInputsManager.prototype.attachInput = function (input) {
  48868. if (this.attachedElement) {
  48869. input.attachControl(this.attachedElement, this.noPreventDefault);
  48870. }
  48871. };
  48872. /**
  48873. * Attach the current manager inputs controls to a specific dom element to listen the events from.
  48874. * @param element Defines the dom element to collect the events from
  48875. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  48876. */
  48877. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  48878. if (noPreventDefault === void 0) { noPreventDefault = false; }
  48879. if (this.attachedElement) {
  48880. return;
  48881. }
  48882. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  48883. this.attachedElement = element;
  48884. this.noPreventDefault = noPreventDefault;
  48885. for (var cam in this.attached) {
  48886. this.attached[cam].attachControl(element, noPreventDefault);
  48887. }
  48888. };
  48889. /**
  48890. * Detach the current manager inputs controls from a specific dom element.
  48891. * @param element Defines the dom element to collect the events from
  48892. * @param disconnect Defines whether the input should be removed from the current list of attached inputs
  48893. */
  48894. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  48895. if (disconnect === void 0) { disconnect = false; }
  48896. if (this.attachedElement !== element) {
  48897. return;
  48898. }
  48899. for (var cam in this.attached) {
  48900. this.attached[cam].detachControl(element);
  48901. if (disconnect) {
  48902. this.attached[cam].camera = null;
  48903. }
  48904. }
  48905. this.attachedElement = null;
  48906. };
  48907. /**
  48908. * Rebuild the dynamic inputCheck function from the current list of
  48909. * defined inputs in the manager.
  48910. */
  48911. CameraInputsManager.prototype.rebuildInputCheck = function () {
  48912. this.checkInputs = function () { };
  48913. for (var cam in this.attached) {
  48914. var input = this.attached[cam];
  48915. if (input.checkInputs) {
  48916. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  48917. }
  48918. }
  48919. };
  48920. /**
  48921. * Remove all attached input methods from a camera
  48922. */
  48923. CameraInputsManager.prototype.clear = function () {
  48924. if (this.attachedElement) {
  48925. this.detachElement(this.attachedElement, true);
  48926. }
  48927. this.attached = {};
  48928. this.attachedElement = null;
  48929. this.checkInputs = function () { };
  48930. };
  48931. /**
  48932. * Serialize the current input manager attached to a camera.
  48933. * This ensures than once parsed,
  48934. * the input associated to the camera will be identical to the current ones
  48935. * @param serializedCamera Defines the camera serialization JSON the input serialization should write to
  48936. */
  48937. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  48938. var inputs = {};
  48939. for (var cam in this.attached) {
  48940. var input = this.attached[cam];
  48941. var res = BABYLON.SerializationHelper.Serialize(input);
  48942. inputs[input.getClassName()] = res;
  48943. }
  48944. serializedCamera.inputsmgr = inputs;
  48945. };
  48946. /**
  48947. * Parses an input manager serialized JSON to restore the previous list of inputs
  48948. * and states associated to a camera.
  48949. * @param parsedCamera Defines the JSON to parse
  48950. */
  48951. CameraInputsManager.prototype.parse = function (parsedCamera) {
  48952. var parsedInputs = parsedCamera.inputsmgr;
  48953. if (parsedInputs) {
  48954. this.clear();
  48955. for (var n in parsedInputs) {
  48956. var construct = BABYLON.CameraInputTypes[n];
  48957. if (construct) {
  48958. var parsedinput = parsedInputs[n];
  48959. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  48960. this.add(input);
  48961. }
  48962. }
  48963. }
  48964. else {
  48965. //2016-03-08 this part is for managing backward compatibility
  48966. for (var n in this.attached) {
  48967. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  48968. if (construct) {
  48969. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  48970. this.remove(this.attached[n]);
  48971. this.add(input);
  48972. }
  48973. }
  48974. }
  48975. };
  48976. return CameraInputsManager;
  48977. }());
  48978. BABYLON.CameraInputsManager = CameraInputsManager;
  48979. })(BABYLON || (BABYLON = {}));
  48980. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  48981. var BABYLON;
  48982. (function (BABYLON) {
  48983. /**
  48984. * A target camera takes a mesh or position as a target and continues to look at it while it moves.
  48985. * This is the base of the follow, arc rotate cameras and Free camera
  48986. * @see http://doc.babylonjs.com/features/cameras
  48987. */
  48988. var TargetCamera = /** @class */ (function (_super) {
  48989. __extends(TargetCamera, _super);
  48990. /**
  48991. * Instantiates a target camera that takes a meshor position as a target and continues to look at it while it moves.
  48992. * This is the base of the follow, arc rotate cameras and Free camera
  48993. * @see http://doc.babylonjs.com/features/cameras
  48994. * @param name Defines the name of the camera in the scene
  48995. * @param position Defines the start position of the camera in the scene
  48996. * @param scene Defines the scene the camera belongs to
  48997. * @param setActiveOnSceneIfNoneActive Defines wheter the camera should be marked as active if not other active cameras have been defined
  48998. */
  48999. function TargetCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  49000. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  49001. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  49002. /**
  49003. * Define the current direction the camera is moving to
  49004. */
  49005. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  49006. /**
  49007. * Define the current rotation the camera is rotating to
  49008. */
  49009. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  49010. /**
  49011. * When set, the up vector of the camera will be updated by the rotation of the camera
  49012. */
  49013. _this.updateUpVectorFromRotation = false;
  49014. _this._tmpQuaternion = new BABYLON.Quaternion();
  49015. /**
  49016. * Define the current rotation of the camera
  49017. */
  49018. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  49019. /**
  49020. * Define the current speed of the camera
  49021. */
  49022. _this.speed = 2.0;
  49023. /**
  49024. * Add cconstraint to the camera to prevent it to move freely in all directions and
  49025. * around all axis.
  49026. */
  49027. _this.noRotationConstraint = false;
  49028. /**
  49029. * Define the current target of the camera as an object or a position.
  49030. */
  49031. _this.lockedTarget = null;
  49032. /** @hidden */
  49033. _this._currentTarget = BABYLON.Vector3.Zero();
  49034. /** @hidden */
  49035. _this._initialFocalDistance = 1;
  49036. /** @hidden */
  49037. _this._viewMatrix = BABYLON.Matrix.Zero();
  49038. /** @hidden */
  49039. _this._camMatrix = BABYLON.Matrix.Zero();
  49040. /** @hidden */
  49041. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  49042. /** @hidden */
  49043. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  49044. /** @hidden */
  49045. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  49046. /** @hidden */
  49047. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  49048. _this._globalCurrentTarget = BABYLON.Vector3.Zero();
  49049. _this._globalCurrentUpVector = BABYLON.Vector3.Zero();
  49050. _this._defaultUp = BABYLON.Vector3.Up();
  49051. _this._cachedRotationZ = 0;
  49052. _this._cachedQuaternionRotationZ = 0;
  49053. return _this;
  49054. }
  49055. /**
  49056. * Gets the position in front of the camera at a given distance.
  49057. * @param distance The distance from the camera we want the position to be
  49058. * @returns the position
  49059. */
  49060. TargetCamera.prototype.getFrontPosition = function (distance) {
  49061. this.getWorldMatrix();
  49062. var direction = this.getTarget().subtract(this.position);
  49063. direction.normalize();
  49064. direction.scaleInPlace(distance);
  49065. return this.globalPosition.add(direction);
  49066. };
  49067. /** @hidden */
  49068. TargetCamera.prototype._getLockedTargetPosition = function () {
  49069. if (!this.lockedTarget) {
  49070. return null;
  49071. }
  49072. if (this.lockedTarget.absolutePosition) {
  49073. this.lockedTarget.computeWorldMatrix();
  49074. }
  49075. return this.lockedTarget.absolutePosition || this.lockedTarget;
  49076. };
  49077. /**
  49078. * Store current camera state of the camera (fov, position, rotation, etc..)
  49079. * @returns the camera
  49080. */
  49081. TargetCamera.prototype.storeState = function () {
  49082. this._storedPosition = this.position.clone();
  49083. this._storedRotation = this.rotation.clone();
  49084. if (this.rotationQuaternion) {
  49085. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  49086. }
  49087. return _super.prototype.storeState.call(this);
  49088. };
  49089. /**
  49090. * Restored camera state. You must call storeState() first
  49091. * @returns whether it was successful or not
  49092. * @hidden
  49093. */
  49094. TargetCamera.prototype._restoreStateValues = function () {
  49095. if (!_super.prototype._restoreStateValues.call(this)) {
  49096. return false;
  49097. }
  49098. this.position = this._storedPosition.clone();
  49099. this.rotation = this._storedRotation.clone();
  49100. if (this.rotationQuaternion) {
  49101. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  49102. }
  49103. this.cameraDirection.copyFromFloats(0, 0, 0);
  49104. this.cameraRotation.copyFromFloats(0, 0);
  49105. return true;
  49106. };
  49107. /** @hidden */
  49108. TargetCamera.prototype._initCache = function () {
  49109. _super.prototype._initCache.call(this);
  49110. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  49111. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  49112. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  49113. };
  49114. /** @hidden */
  49115. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  49116. if (!ignoreParentClass) {
  49117. _super.prototype._updateCache.call(this);
  49118. }
  49119. var lockedTargetPosition = this._getLockedTargetPosition();
  49120. if (!lockedTargetPosition) {
  49121. this._cache.lockedTarget = null;
  49122. }
  49123. else {
  49124. if (!this._cache.lockedTarget) {
  49125. this._cache.lockedTarget = lockedTargetPosition.clone();
  49126. }
  49127. else {
  49128. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  49129. }
  49130. }
  49131. this._cache.rotation.copyFrom(this.rotation);
  49132. if (this.rotationQuaternion) {
  49133. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  49134. }
  49135. };
  49136. // Synchronized
  49137. /** @hidden */
  49138. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  49139. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  49140. return false;
  49141. }
  49142. var lockedTargetPosition = this._getLockedTargetPosition();
  49143. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  49144. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  49145. };
  49146. // Methods
  49147. /** @hidden */
  49148. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  49149. var engine = this.getEngine();
  49150. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  49151. };
  49152. // Target
  49153. /** @hidden */
  49154. TargetCamera.prototype.setTarget = function (target) {
  49155. this.upVector.normalize();
  49156. this._initialFocalDistance = target.subtract(this.position).length();
  49157. if (this.position.z === target.z) {
  49158. this.position.z += BABYLON.Epsilon;
  49159. }
  49160. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUp, this._camMatrix);
  49161. this._camMatrix.invert();
  49162. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  49163. var vDir = target.subtract(this.position);
  49164. if (vDir.x >= 0.0) {
  49165. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  49166. }
  49167. else {
  49168. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  49169. }
  49170. this.rotation.z = 0;
  49171. if (isNaN(this.rotation.x)) {
  49172. this.rotation.x = 0;
  49173. }
  49174. if (isNaN(this.rotation.y)) {
  49175. this.rotation.y = 0;
  49176. }
  49177. if (isNaN(this.rotation.z)) {
  49178. this.rotation.z = 0;
  49179. }
  49180. if (this.rotationQuaternion) {
  49181. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  49182. }
  49183. };
  49184. /**
  49185. * Return the current target position of the camera. This value is expressed in local space.
  49186. * @returns the target position
  49187. */
  49188. TargetCamera.prototype.getTarget = function () {
  49189. return this._currentTarget;
  49190. };
  49191. /** @hidden */
  49192. TargetCamera.prototype._decideIfNeedsToMove = function () {
  49193. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  49194. };
  49195. /** @hidden */
  49196. TargetCamera.prototype._updatePosition = function () {
  49197. if (this.parent) {
  49198. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  49199. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  49200. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  49201. return;
  49202. }
  49203. this.position.addInPlace(this.cameraDirection);
  49204. };
  49205. /** @hidden */
  49206. TargetCamera.prototype._checkInputs = function () {
  49207. var needToMove = this._decideIfNeedsToMove();
  49208. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  49209. // Move
  49210. if (needToMove) {
  49211. this._updatePosition();
  49212. }
  49213. // Rotate
  49214. if (needToRotate) {
  49215. this.rotation.x += this.cameraRotation.x;
  49216. this.rotation.y += this.cameraRotation.y;
  49217. //rotate, if quaternion is set and rotation was used
  49218. if (this.rotationQuaternion) {
  49219. var len = this.rotation.lengthSquared();
  49220. if (len) {
  49221. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  49222. }
  49223. }
  49224. if (!this.noRotationConstraint) {
  49225. var limit = (Math.PI / 2) * 0.95;
  49226. if (this.rotation.x > limit) {
  49227. this.rotation.x = limit;
  49228. }
  49229. if (this.rotation.x < -limit) {
  49230. this.rotation.x = -limit;
  49231. }
  49232. }
  49233. }
  49234. // Inertia
  49235. if (needToMove) {
  49236. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  49237. this.cameraDirection.x = 0;
  49238. }
  49239. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  49240. this.cameraDirection.y = 0;
  49241. }
  49242. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  49243. this.cameraDirection.z = 0;
  49244. }
  49245. this.cameraDirection.scaleInPlace(this.inertia);
  49246. }
  49247. if (needToRotate) {
  49248. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  49249. this.cameraRotation.x = 0;
  49250. }
  49251. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  49252. this.cameraRotation.y = 0;
  49253. }
  49254. this.cameraRotation.scaleInPlace(this.inertia);
  49255. }
  49256. _super.prototype._checkInputs.call(this);
  49257. };
  49258. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  49259. if (this.rotationQuaternion) {
  49260. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  49261. }
  49262. else {
  49263. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  49264. }
  49265. };
  49266. /**
  49267. * 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)
  49268. * @returns the current camera
  49269. */
  49270. TargetCamera.prototype._rotateUpVectorWithCameraRotationMatrix = function () {
  49271. BABYLON.Vector3.TransformNormalToRef(this._defaultUp, this._cameraRotationMatrix, this.upVector);
  49272. return this;
  49273. };
  49274. /** @hidden */
  49275. TargetCamera.prototype._getViewMatrix = function () {
  49276. if (this.lockedTarget) {
  49277. this.setTarget(this._getLockedTargetPosition());
  49278. }
  49279. // Compute
  49280. this._updateCameraRotationMatrix();
  49281. // Apply the changed rotation to the upVector
  49282. if (this.rotationQuaternion && this._cachedQuaternionRotationZ != this.rotationQuaternion.z) {
  49283. this._rotateUpVectorWithCameraRotationMatrix();
  49284. this._cachedQuaternionRotationZ = this.rotationQuaternion.z;
  49285. }
  49286. else if (this._cachedRotationZ != this.rotation.z) {
  49287. this._rotateUpVectorWithCameraRotationMatrix();
  49288. this._cachedRotationZ = this.rotation.z;
  49289. }
  49290. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  49291. // Computing target and final matrix
  49292. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  49293. if (this.updateUpVectorFromRotation) {
  49294. if (this.rotationQuaternion) {
  49295. BABYLON.Axis.Y.rotateByQuaternionToRef(this.rotationQuaternion, this.upVector);
  49296. }
  49297. else {
  49298. BABYLON.Quaternion.FromEulerVectorToRef(this.rotation, this._tmpQuaternion);
  49299. BABYLON.Axis.Y.rotateByQuaternionToRef(this._tmpQuaternion, this.upVector);
  49300. }
  49301. }
  49302. this._computeViewMatrix(this.position, this._currentTarget, this.upVector);
  49303. return this._viewMatrix;
  49304. };
  49305. TargetCamera.prototype._computeViewMatrix = function (position, target, up) {
  49306. if (this.parent) {
  49307. var parentWorldMatrix = this.parent.getWorldMatrix();
  49308. BABYLON.Vector3.TransformCoordinatesToRef(position, parentWorldMatrix, this._globalPosition);
  49309. BABYLON.Vector3.TransformCoordinatesToRef(target, parentWorldMatrix, this._globalCurrentTarget);
  49310. BABYLON.Vector3.TransformNormalToRef(up, parentWorldMatrix, this._globalCurrentUpVector);
  49311. this._markSyncedWithParent();
  49312. }
  49313. else {
  49314. this._globalPosition.copyFrom(position);
  49315. this._globalCurrentTarget.copyFrom(target);
  49316. this._globalCurrentUpVector.copyFrom(up);
  49317. }
  49318. if (this.getScene().useRightHandedSystem) {
  49319. BABYLON.Matrix.LookAtRHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  49320. }
  49321. else {
  49322. BABYLON.Matrix.LookAtLHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  49323. }
  49324. };
  49325. /**
  49326. * @hidden
  49327. */
  49328. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  49329. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  49330. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  49331. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  49332. if (!this.rotationQuaternion) {
  49333. this.rotationQuaternion = new BABYLON.Quaternion();
  49334. }
  49335. rigCamera._cameraRigParams = {};
  49336. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  49337. }
  49338. return rigCamera;
  49339. }
  49340. return null;
  49341. };
  49342. /**
  49343. * @hidden
  49344. */
  49345. TargetCamera.prototype._updateRigCameras = function () {
  49346. var camLeft = this._rigCameras[0];
  49347. var camRight = this._rigCameras[1];
  49348. this.computeWorldMatrix();
  49349. switch (this.cameraRigMode) {
  49350. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  49351. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  49352. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  49353. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  49354. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  49355. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  49356. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  49357. this._getRigCamPositionAndTarget(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft);
  49358. this._getRigCamPositionAndTarget(this._cameraRigParams.stereoHalfAngle * rightSign, camRight);
  49359. break;
  49360. case BABYLON.Camera.RIG_MODE_VR:
  49361. if (camLeft.rotationQuaternion) {
  49362. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  49363. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  49364. }
  49365. else {
  49366. camLeft.rotation.copyFrom(this.rotation);
  49367. camRight.rotation.copyFrom(this.rotation);
  49368. }
  49369. camLeft.position.copyFrom(this.position);
  49370. camRight.position.copyFrom(this.position);
  49371. break;
  49372. }
  49373. _super.prototype._updateRigCameras.call(this);
  49374. };
  49375. TargetCamera.prototype._getRigCamPositionAndTarget = function (halfSpace, rigCamera) {
  49376. var target = this.getTarget();
  49377. target.subtractToRef(this.position, TargetCamera._TargetFocalPoint);
  49378. TargetCamera._TargetFocalPoint.normalize().scaleInPlace(this._initialFocalDistance);
  49379. var newFocalTarget = TargetCamera._TargetFocalPoint.addInPlace(this.position);
  49380. BABYLON.Matrix.TranslationToRef(-newFocalTarget.x, -newFocalTarget.y, -newFocalTarget.z, TargetCamera._TargetTransformMatrix);
  49381. TargetCamera._TargetTransformMatrix.multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), TargetCamera._RigCamTransformMatrix);
  49382. BABYLON.Matrix.TranslationToRef(newFocalTarget.x, newFocalTarget.y, newFocalTarget.z, TargetCamera._TargetTransformMatrix);
  49383. TargetCamera._RigCamTransformMatrix.multiplyToRef(TargetCamera._TargetTransformMatrix, TargetCamera._RigCamTransformMatrix);
  49384. BABYLON.Vector3.TransformCoordinatesToRef(this.position, TargetCamera._RigCamTransformMatrix, rigCamera.position);
  49385. rigCamera.setTarget(newFocalTarget);
  49386. };
  49387. /**
  49388. * Gets the current object class name.
  49389. * @return the class name
  49390. */
  49391. TargetCamera.prototype.getClassName = function () {
  49392. return "TargetCamera";
  49393. };
  49394. TargetCamera._RigCamTransformMatrix = new BABYLON.Matrix();
  49395. TargetCamera._TargetTransformMatrix = new BABYLON.Matrix();
  49396. TargetCamera._TargetFocalPoint = new BABYLON.Vector3();
  49397. __decorate([
  49398. BABYLON.serializeAsVector3()
  49399. ], TargetCamera.prototype, "rotation", void 0);
  49400. __decorate([
  49401. BABYLON.serialize()
  49402. ], TargetCamera.prototype, "speed", void 0);
  49403. __decorate([
  49404. BABYLON.serializeAsMeshReference("lockedTargetId")
  49405. ], TargetCamera.prototype, "lockedTarget", void 0);
  49406. return TargetCamera;
  49407. }(BABYLON.Camera));
  49408. BABYLON.TargetCamera = TargetCamera;
  49409. })(BABYLON || (BABYLON = {}));
  49410. //# sourceMappingURL=babylon.targetCamera.js.map
  49411. var BABYLON;
  49412. (function (BABYLON) {
  49413. /**
  49414. * Manage the mouse inputs to control the movement of a free camera.
  49415. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  49416. */
  49417. var FreeCameraMouseInput = /** @class */ (function () {
  49418. /**
  49419. * Manage the mouse inputs to control the movement of a free camera.
  49420. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  49421. * @param touchEnabled Defines if touch is enabled or not
  49422. */
  49423. function FreeCameraMouseInput(
  49424. /**
  49425. * Define if touch is enabled in the mouse input
  49426. */
  49427. touchEnabled) {
  49428. if (touchEnabled === void 0) { touchEnabled = true; }
  49429. this.touchEnabled = touchEnabled;
  49430. /**
  49431. * Defines the buttons associated with the input to handle camera move.
  49432. */
  49433. this.buttons = [0, 1, 2];
  49434. /**
  49435. * Defines the pointer angular sensibility along the X and Y axis or how fast is the camera rotating.
  49436. */
  49437. this.angularSensibility = 2000.0;
  49438. this.previousPosition = null;
  49439. }
  49440. /**
  49441. * Attach the input controls to a specific dom element to get the input from.
  49442. * @param element Defines the element the controls should be listened from
  49443. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  49444. */
  49445. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  49446. var _this = this;
  49447. var engine = this.camera.getEngine();
  49448. if (!this._pointerInput) {
  49449. this._pointerInput = function (p, s) {
  49450. var evt = p.event;
  49451. if (engine.isInVRExclusivePointerMode) {
  49452. return;
  49453. }
  49454. if (!_this.touchEnabled && evt.pointerType === "touch") {
  49455. return;
  49456. }
  49457. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  49458. return;
  49459. }
  49460. var srcElement = (evt.srcElement || evt.target);
  49461. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  49462. try {
  49463. srcElement.setPointerCapture(evt.pointerId);
  49464. }
  49465. catch (e) {
  49466. //Nothing to do with the error. Execution will continue.
  49467. }
  49468. _this.previousPosition = {
  49469. x: evt.clientX,
  49470. y: evt.clientY
  49471. };
  49472. if (!noPreventDefault) {
  49473. evt.preventDefault();
  49474. element.focus();
  49475. }
  49476. }
  49477. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  49478. try {
  49479. srcElement.releasePointerCapture(evt.pointerId);
  49480. }
  49481. catch (e) {
  49482. //Nothing to do with the error.
  49483. }
  49484. _this.previousPosition = null;
  49485. if (!noPreventDefault) {
  49486. evt.preventDefault();
  49487. }
  49488. }
  49489. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  49490. if (!_this.previousPosition || engine.isPointerLock) {
  49491. return;
  49492. }
  49493. var offsetX = evt.clientX - _this.previousPosition.x;
  49494. if (_this.camera.getScene().useRightHandedSystem) {
  49495. offsetX *= -1;
  49496. }
  49497. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0) {
  49498. offsetX *= -1;
  49499. }
  49500. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  49501. var offsetY = evt.clientY - _this.previousPosition.y;
  49502. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  49503. _this.previousPosition = {
  49504. x: evt.clientX,
  49505. y: evt.clientY
  49506. };
  49507. if (!noPreventDefault) {
  49508. evt.preventDefault();
  49509. }
  49510. }
  49511. };
  49512. }
  49513. this._onMouseMove = function (evt) {
  49514. if (!engine.isPointerLock) {
  49515. return;
  49516. }
  49517. if (engine.isInVRExclusivePointerMode) {
  49518. return;
  49519. }
  49520. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  49521. if (_this.camera.getScene().useRightHandedSystem) {
  49522. offsetX *= -1;
  49523. }
  49524. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0) {
  49525. offsetX *= -1;
  49526. }
  49527. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  49528. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  49529. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  49530. _this.previousPosition = null;
  49531. if (!noPreventDefault) {
  49532. evt.preventDefault();
  49533. }
  49534. };
  49535. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  49536. element.addEventListener("mousemove", this._onMouseMove, false);
  49537. };
  49538. /**
  49539. * Detach the current controls from the specified dom element.
  49540. * @param element Defines the element to stop listening the inputs from
  49541. */
  49542. FreeCameraMouseInput.prototype.detachControl = function (element) {
  49543. if (this._observer && element) {
  49544. this.camera.getScene().onPointerObservable.remove(this._observer);
  49545. if (this._onMouseMove) {
  49546. element.removeEventListener("mousemove", this._onMouseMove);
  49547. }
  49548. this._observer = null;
  49549. this._onMouseMove = null;
  49550. this.previousPosition = null;
  49551. }
  49552. };
  49553. /**
  49554. * Gets the class name of the current intput.
  49555. * @returns the class name
  49556. */
  49557. FreeCameraMouseInput.prototype.getClassName = function () {
  49558. return "FreeCameraMouseInput";
  49559. };
  49560. /**
  49561. * Get the friendly name associated with the input class.
  49562. * @returns the input friendly name
  49563. */
  49564. FreeCameraMouseInput.prototype.getSimpleName = function () {
  49565. return "mouse";
  49566. };
  49567. __decorate([
  49568. BABYLON.serialize()
  49569. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  49570. __decorate([
  49571. BABYLON.serialize()
  49572. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  49573. return FreeCameraMouseInput;
  49574. }());
  49575. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  49576. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  49577. })(BABYLON || (BABYLON = {}));
  49578. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  49579. var BABYLON;
  49580. (function (BABYLON) {
  49581. /**
  49582. * Manage the keyboard inputs to control the movement of a free camera.
  49583. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  49584. */
  49585. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  49586. function FreeCameraKeyboardMoveInput() {
  49587. /**
  49588. * Gets or Set the list of keyboard keys used to control the forward move of the camera.
  49589. */
  49590. this.keysUp = [38];
  49591. /**
  49592. * Gets or Set the list of keyboard keys used to control the backward move of the camera.
  49593. */
  49594. this.keysDown = [40];
  49595. /**
  49596. * Gets or Set the list of keyboard keys used to control the left strafe move of the camera.
  49597. */
  49598. this.keysLeft = [37];
  49599. /**
  49600. * Gets or Set the list of keyboard keys used to control the right strafe move of the camera.
  49601. */
  49602. this.keysRight = [39];
  49603. this._keys = new Array();
  49604. }
  49605. /**
  49606. * Attach the input controls to a specific dom element to get the input from.
  49607. * @param element Defines the element the controls should be listened from
  49608. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  49609. */
  49610. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  49611. var _this = this;
  49612. if (this._onCanvasBlurObserver) {
  49613. return;
  49614. }
  49615. this._scene = this.camera.getScene();
  49616. this._engine = this._scene.getEngine();
  49617. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  49618. _this._keys = [];
  49619. });
  49620. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  49621. var evt = info.event;
  49622. if (!evt.metaKey) {
  49623. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  49624. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  49625. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  49626. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  49627. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  49628. var index = _this._keys.indexOf(evt.keyCode);
  49629. if (index === -1) {
  49630. _this._keys.push(evt.keyCode);
  49631. }
  49632. if (!noPreventDefault) {
  49633. evt.preventDefault();
  49634. }
  49635. }
  49636. }
  49637. else {
  49638. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  49639. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  49640. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  49641. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  49642. var index = _this._keys.indexOf(evt.keyCode);
  49643. if (index >= 0) {
  49644. _this._keys.splice(index, 1);
  49645. }
  49646. if (!noPreventDefault) {
  49647. evt.preventDefault();
  49648. }
  49649. }
  49650. }
  49651. }
  49652. });
  49653. };
  49654. /**
  49655. * Detach the current controls from the specified dom element.
  49656. * @param element Defines the element to stop listening the inputs from
  49657. */
  49658. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  49659. if (this._scene) {
  49660. if (this._onKeyboardObserver) {
  49661. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  49662. }
  49663. if (this._onCanvasBlurObserver) {
  49664. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  49665. }
  49666. this._onKeyboardObserver = null;
  49667. this._onCanvasBlurObserver = null;
  49668. }
  49669. this._keys = [];
  49670. };
  49671. /**
  49672. * Update the current camera state depending on the inputs that have been used this frame.
  49673. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  49674. */
  49675. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  49676. if (this._onKeyboardObserver) {
  49677. var camera = this.camera;
  49678. // Keyboard
  49679. for (var index = 0; index < this._keys.length; index++) {
  49680. var keyCode = this._keys[index];
  49681. var speed = camera._computeLocalCameraSpeed();
  49682. if (this.keysLeft.indexOf(keyCode) !== -1) {
  49683. camera._localDirection.copyFromFloats(-speed, 0, 0);
  49684. }
  49685. else if (this.keysUp.indexOf(keyCode) !== -1) {
  49686. camera._localDirection.copyFromFloats(0, 0, speed);
  49687. }
  49688. else if (this.keysRight.indexOf(keyCode) !== -1) {
  49689. camera._localDirection.copyFromFloats(speed, 0, 0);
  49690. }
  49691. else if (this.keysDown.indexOf(keyCode) !== -1) {
  49692. camera._localDirection.copyFromFloats(0, 0, -speed);
  49693. }
  49694. if (camera.getScene().useRightHandedSystem) {
  49695. camera._localDirection.z *= -1;
  49696. }
  49697. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  49698. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  49699. camera.cameraDirection.addInPlace(camera._transformedDirection);
  49700. }
  49701. }
  49702. };
  49703. /**
  49704. * Gets the class name of the current intput.
  49705. * @returns the class name
  49706. */
  49707. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  49708. return "FreeCameraKeyboardMoveInput";
  49709. };
  49710. /** @hidden */
  49711. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  49712. this._keys = [];
  49713. };
  49714. /**
  49715. * Get the friendly name associated with the input class.
  49716. * @returns the input friendly name
  49717. */
  49718. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  49719. return "keyboard";
  49720. };
  49721. __decorate([
  49722. BABYLON.serialize()
  49723. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  49724. __decorate([
  49725. BABYLON.serialize()
  49726. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  49727. __decorate([
  49728. BABYLON.serialize()
  49729. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  49730. __decorate([
  49731. BABYLON.serialize()
  49732. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  49733. return FreeCameraKeyboardMoveInput;
  49734. }());
  49735. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  49736. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  49737. })(BABYLON || (BABYLON = {}));
  49738. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  49739. var BABYLON;
  49740. (function (BABYLON) {
  49741. /**
  49742. * Default Inputs manager for the FreeCamera.
  49743. * It groups all the default supported inputs for ease of use.
  49744. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  49745. */
  49746. var FreeCameraInputsManager = /** @class */ (function (_super) {
  49747. __extends(FreeCameraInputsManager, _super);
  49748. /**
  49749. * Instantiates a new FreeCameraInputsManager.
  49750. * @param camera Defines the camera the inputs belong to
  49751. */
  49752. function FreeCameraInputsManager(camera) {
  49753. return _super.call(this, camera) || this;
  49754. }
  49755. /**
  49756. * Add keyboard input support to the input manager.
  49757. * @returns the current input manager
  49758. */
  49759. FreeCameraInputsManager.prototype.addKeyboard = function () {
  49760. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  49761. return this;
  49762. };
  49763. /**
  49764. * Add mouse input support to the input manager.
  49765. * @param touchEnabled if the FreeCameraMouseInput should support touch (default: true)
  49766. * @returns the current input manager
  49767. */
  49768. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  49769. if (touchEnabled === void 0) { touchEnabled = true; }
  49770. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  49771. return this;
  49772. };
  49773. /**
  49774. * Add orientation input support to the input manager.
  49775. * @returns the current input manager
  49776. */
  49777. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  49778. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  49779. return this;
  49780. };
  49781. /**
  49782. * Add touch input support to the input manager.
  49783. * @returns the current input manager
  49784. */
  49785. FreeCameraInputsManager.prototype.addTouch = function () {
  49786. this.add(new BABYLON.FreeCameraTouchInput());
  49787. return this;
  49788. };
  49789. /**
  49790. * Add virtual joystick input support to the input manager.
  49791. * @returns the current input manager
  49792. */
  49793. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  49794. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  49795. return this;
  49796. };
  49797. return FreeCameraInputsManager;
  49798. }(BABYLON.CameraInputsManager));
  49799. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  49800. })(BABYLON || (BABYLON = {}));
  49801. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  49802. var BABYLON;
  49803. (function (BABYLON) {
  49804. BABYLON.Node.AddNodeConstructor("FreeCamera", function (name, scene) {
  49805. // Forcing to use the Universal camera
  49806. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  49807. });
  49808. /**
  49809. * This represents a free type of camera. It can be useful in First Person Shooter game for instance.
  49810. * Please consider using the new UniversalCamera instead as it adds more functionality like the gamepad.
  49811. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  49812. */
  49813. var FreeCamera = /** @class */ (function (_super) {
  49814. __extends(FreeCamera, _super);
  49815. /**
  49816. * Instantiates a Free Camera.
  49817. * This represents a free type of camera. It can be useful in First Person Shooter game for instance.
  49818. * Please consider using the new UniversalCamera instead as it adds more functionality like touch to this camera.
  49819. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  49820. * @param name Define the name of the camera in the scene
  49821. * @param position Define the start position of the camera in the scene
  49822. * @param scene Define the scene the camera belongs to
  49823. * @param setActiveOnSceneIfNoneActive Defines wheter the camera should be marked as active if not other active cameras have been defined
  49824. */
  49825. function FreeCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  49826. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  49827. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  49828. /**
  49829. * Define the collision ellipsoid of the camera.
  49830. * This is helpful to simulate a camera body like the player body around the camera
  49831. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#arcrotatecamera
  49832. */
  49833. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  49834. /**
  49835. * Define an offset for the position of the ellipsoid around the camera.
  49836. * This can be helpful to determine the center of the body near the gravity center of the body
  49837. * instead of its head.
  49838. */
  49839. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  49840. /**
  49841. * Enable or disable collisions of the camera with the rest of the scene objects.
  49842. */
  49843. _this.checkCollisions = false;
  49844. /**
  49845. * Enable or disable gravity on the camera.
  49846. */
  49847. _this.applyGravity = false;
  49848. _this._needMoveForGravity = false;
  49849. _this._oldPosition = BABYLON.Vector3.Zero();
  49850. _this._diffPosition = BABYLON.Vector3.Zero();
  49851. _this._newPosition = BABYLON.Vector3.Zero();
  49852. // Collisions
  49853. _this._collisionMask = -1;
  49854. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  49855. if (collidedMesh === void 0) { collidedMesh = null; }
  49856. //TODO move this to the collision coordinator!
  49857. if (_this.getScene().workerCollisions) {
  49858. newPosition.multiplyInPlace(_this._collider._radius);
  49859. }
  49860. var updatePosition = function (newPos) {
  49861. _this._newPosition.copyFrom(newPos);
  49862. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  49863. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  49864. _this.position.addInPlace(_this._diffPosition);
  49865. if (_this.onCollide && collidedMesh) {
  49866. _this.onCollide(collidedMesh);
  49867. }
  49868. }
  49869. };
  49870. updatePosition(newPosition);
  49871. };
  49872. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  49873. _this.inputs.addKeyboard().addMouse();
  49874. return _this;
  49875. }
  49876. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  49877. /**
  49878. * Gets the input sensibility for a mouse input. (default is 2000.0)
  49879. * Higher values reduce sensitivity.
  49880. */
  49881. get: function () {
  49882. var mouse = this.inputs.attached["mouse"];
  49883. if (mouse) {
  49884. return mouse.angularSensibility;
  49885. }
  49886. return 0;
  49887. },
  49888. /**
  49889. * Sets the input sensibility for a mouse input. (default is 2000.0)
  49890. * Higher values reduce sensitivity.
  49891. */
  49892. set: function (value) {
  49893. var mouse = this.inputs.attached["mouse"];
  49894. if (mouse) {
  49895. mouse.angularSensibility = value;
  49896. }
  49897. },
  49898. enumerable: true,
  49899. configurable: true
  49900. });
  49901. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  49902. /**
  49903. * Gets or Set the list of keyboard keys used to control the forward move of the camera.
  49904. */
  49905. get: function () {
  49906. var keyboard = this.inputs.attached["keyboard"];
  49907. if (keyboard) {
  49908. return keyboard.keysUp;
  49909. }
  49910. return [];
  49911. },
  49912. set: function (value) {
  49913. var keyboard = this.inputs.attached["keyboard"];
  49914. if (keyboard) {
  49915. keyboard.keysUp = value;
  49916. }
  49917. },
  49918. enumerable: true,
  49919. configurable: true
  49920. });
  49921. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  49922. /**
  49923. * Gets or Set the list of keyboard keys used to control the backward move of the camera.
  49924. */
  49925. get: function () {
  49926. var keyboard = this.inputs.attached["keyboard"];
  49927. if (keyboard) {
  49928. return keyboard.keysDown;
  49929. }
  49930. return [];
  49931. },
  49932. set: function (value) {
  49933. var keyboard = this.inputs.attached["keyboard"];
  49934. if (keyboard) {
  49935. keyboard.keysDown = value;
  49936. }
  49937. },
  49938. enumerable: true,
  49939. configurable: true
  49940. });
  49941. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  49942. /**
  49943. * Gets or Set the list of keyboard keys used to control the left strafe move of the camera.
  49944. */
  49945. get: function () {
  49946. var keyboard = this.inputs.attached["keyboard"];
  49947. if (keyboard) {
  49948. return keyboard.keysLeft;
  49949. }
  49950. return [];
  49951. },
  49952. set: function (value) {
  49953. var keyboard = this.inputs.attached["keyboard"];
  49954. if (keyboard) {
  49955. keyboard.keysLeft = value;
  49956. }
  49957. },
  49958. enumerable: true,
  49959. configurable: true
  49960. });
  49961. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  49962. /**
  49963. * Gets or Set the list of keyboard keys used to control the right strafe move of the camera.
  49964. */
  49965. get: function () {
  49966. var keyboard = this.inputs.attached["keyboard"];
  49967. if (keyboard) {
  49968. return keyboard.keysRight;
  49969. }
  49970. return [];
  49971. },
  49972. set: function (value) {
  49973. var keyboard = this.inputs.attached["keyboard"];
  49974. if (keyboard) {
  49975. keyboard.keysRight = value;
  49976. }
  49977. },
  49978. enumerable: true,
  49979. configurable: true
  49980. });
  49981. /**
  49982. * Attached controls to the current camera.
  49983. * @param element Defines the element the controls should be listened from
  49984. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  49985. */
  49986. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  49987. this.inputs.attachElement(element, noPreventDefault);
  49988. };
  49989. /**
  49990. * Detach the current controls from the camera.
  49991. * The camera will stop reacting to inputs.
  49992. * @param element Defines the element to stop listening the inputs from
  49993. */
  49994. FreeCamera.prototype.detachControl = function (element) {
  49995. this.inputs.detachElement(element);
  49996. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  49997. this.cameraRotation = new BABYLON.Vector2(0, 0);
  49998. };
  49999. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  50000. /**
  50001. * Define a collision mask to limit the list of object the camera can collide with
  50002. */
  50003. get: function () {
  50004. return this._collisionMask;
  50005. },
  50006. set: function (mask) {
  50007. this._collisionMask = !isNaN(mask) ? mask : -1;
  50008. },
  50009. enumerable: true,
  50010. configurable: true
  50011. });
  50012. /** @hidden */
  50013. FreeCamera.prototype._collideWithWorld = function (displacement) {
  50014. var globalPosition;
  50015. if (this.parent) {
  50016. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  50017. }
  50018. else {
  50019. globalPosition = this.position;
  50020. }
  50021. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  50022. this._oldPosition.addInPlace(this.ellipsoidOffset);
  50023. if (!this._collider) {
  50024. this._collider = new BABYLON.Collider();
  50025. }
  50026. this._collider._radius = this.ellipsoid;
  50027. this._collider.collisionMask = this._collisionMask;
  50028. //no need for clone, as long as gravity is not on.
  50029. var actualDisplacement = displacement;
  50030. //add gravity to the direction to prevent the dual-collision checking
  50031. if (this.applyGravity) {
  50032. //this prevents mending with cameraDirection, a global variable of the free camera class.
  50033. actualDisplacement = displacement.add(this.getScene().gravity);
  50034. }
  50035. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  50036. };
  50037. /** @hidden */
  50038. FreeCamera.prototype._checkInputs = function () {
  50039. if (!this._localDirection) {
  50040. this._localDirection = BABYLON.Vector3.Zero();
  50041. this._transformedDirection = BABYLON.Vector3.Zero();
  50042. }
  50043. this.inputs.checkInputs();
  50044. _super.prototype._checkInputs.call(this);
  50045. };
  50046. /** @hidden */
  50047. FreeCamera.prototype._decideIfNeedsToMove = function () {
  50048. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  50049. };
  50050. /** @hidden */
  50051. FreeCamera.prototype._updatePosition = function () {
  50052. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  50053. this._collideWithWorld(this.cameraDirection);
  50054. }
  50055. else {
  50056. _super.prototype._updatePosition.call(this);
  50057. }
  50058. };
  50059. /**
  50060. * Destroy the camera and release the current resources hold by it.
  50061. */
  50062. FreeCamera.prototype.dispose = function () {
  50063. this.inputs.clear();
  50064. _super.prototype.dispose.call(this);
  50065. };
  50066. /**
  50067. * Gets the current object class name.
  50068. * @return the class name
  50069. */
  50070. FreeCamera.prototype.getClassName = function () {
  50071. return "FreeCamera";
  50072. };
  50073. __decorate([
  50074. BABYLON.serializeAsVector3()
  50075. ], FreeCamera.prototype, "ellipsoid", void 0);
  50076. __decorate([
  50077. BABYLON.serializeAsVector3()
  50078. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  50079. __decorate([
  50080. BABYLON.serialize()
  50081. ], FreeCamera.prototype, "checkCollisions", void 0);
  50082. __decorate([
  50083. BABYLON.serialize()
  50084. ], FreeCamera.prototype, "applyGravity", void 0);
  50085. return FreeCamera;
  50086. }(BABYLON.TargetCamera));
  50087. BABYLON.FreeCamera = FreeCamera;
  50088. })(BABYLON || (BABYLON = {}));
  50089. //# sourceMappingURL=babylon.freeCamera.js.map
  50090. var BABYLON;
  50091. (function (BABYLON) {
  50092. /**
  50093. * Listen to mouse events to control the camera.
  50094. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  50095. */
  50096. var FlyCameraMouseInput = /** @class */ (function () {
  50097. /**
  50098. * Listen to mouse events to control the camera.
  50099. * @param touchEnabled Define if touch is enabled. (Default is true.)
  50100. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  50101. */
  50102. function FlyCameraMouseInput(touchEnabled) {
  50103. if (touchEnabled === void 0) { touchEnabled = true; }
  50104. /**
  50105. * Defines the buttons associated with the input to handle camera rotation.
  50106. */
  50107. this.buttons = [0, 1, 2];
  50108. /**
  50109. * Assign buttons for Yaw control.
  50110. */
  50111. this.buttonsYaw = [-1, 0, 1];
  50112. /**
  50113. * Assign buttons for Pitch control.
  50114. */
  50115. this.buttonsPitch = [-1, 0, 1];
  50116. /**
  50117. * Assign buttons for Roll control.
  50118. */
  50119. this.buttonsRoll = [2];
  50120. /**
  50121. * Detect if any button is being pressed while mouse is moved.
  50122. * -1 = Mouse locked.
  50123. * 0 = Left button.
  50124. * 1 = Middle Button.
  50125. * 2 = Right Button.
  50126. */
  50127. this.activeButton = -1;
  50128. /**
  50129. * Defines the pointer's angular sensibility, to control the camera rotation speed.
  50130. * Higher values reduce its sensitivity.
  50131. */
  50132. this.angularSensibility = 1000.0;
  50133. this.previousPosition = null;
  50134. }
  50135. /**
  50136. * Attach the mouse control to the HTML DOM element.
  50137. * @param element Defines the element that listens to the input events.
  50138. * @param noPreventDefault Defines whether events caught by the controls should call preventdefault().
  50139. */
  50140. FlyCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  50141. var _this = this;
  50142. this.element = element;
  50143. this.noPreventDefault = noPreventDefault;
  50144. this._observer = this.camera.getScene().onPointerObservable.add(function (p, s) {
  50145. _this._pointerInput(p, s);
  50146. }, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  50147. // Correct Roll by rate, if enabled.
  50148. this._rollObserver = this.camera.getScene().onBeforeRenderObservable.add(function () {
  50149. if (_this.camera.rollCorrect) {
  50150. _this.camera.restoreRoll(_this.camera.rollCorrect);
  50151. }
  50152. });
  50153. // Helper function to keep 'this'.
  50154. this._mousemoveCallback = function (e) {
  50155. _this._onMouseMove(e);
  50156. };
  50157. element.addEventListener("mousemove", this._mousemoveCallback, false);
  50158. };
  50159. /**
  50160. * Detach the current controls from the specified dom element.
  50161. * @param element Defines the element to stop listening the inputs from
  50162. */
  50163. FlyCameraMouseInput.prototype.detachControl = function (element) {
  50164. if (this._observer && element) {
  50165. this.camera.getScene().onPointerObservable.remove(this._observer);
  50166. this.camera.getScene().onBeforeRenderObservable.remove(this._rollObserver);
  50167. if (this._mousemoveCallback) {
  50168. element.removeEventListener("mousemove", this._mousemoveCallback);
  50169. }
  50170. this._observer = null;
  50171. this._rollObserver = null;
  50172. this.previousPosition = null;
  50173. this.noPreventDefault = undefined;
  50174. }
  50175. };
  50176. /**
  50177. * Gets the class name of the current input.
  50178. * @returns the class name.
  50179. */
  50180. FlyCameraMouseInput.prototype.getClassName = function () {
  50181. return "FlyCameraMouseInput";
  50182. };
  50183. /**
  50184. * Get the friendly name associated with the input class.
  50185. * @returns the input's friendly name.
  50186. */
  50187. FlyCameraMouseInput.prototype.getSimpleName = function () {
  50188. return "mouse";
  50189. };
  50190. // Track mouse movement, when the pointer is not locked.
  50191. FlyCameraMouseInput.prototype._pointerInput = function (p, s) {
  50192. var e = p.event;
  50193. var camera = this.camera;
  50194. var engine = camera.getEngine();
  50195. if (engine.isInVRExclusivePointerMode) {
  50196. return;
  50197. }
  50198. if (!this.touchEnabled && e.pointerType === "touch") {
  50199. return;
  50200. }
  50201. // Mouse is moved but an unknown mouse button is pressed.
  50202. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && this.buttons.indexOf(e.button) === -1) {
  50203. return;
  50204. }
  50205. var srcElement = (e.srcElement || e.target);
  50206. // Mouse down.
  50207. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  50208. try {
  50209. srcElement.setPointerCapture(e.pointerId);
  50210. }
  50211. catch (e) {
  50212. // Nothing to do with the error. Execution continues.
  50213. }
  50214. this.previousPosition = {
  50215. x: e.clientX,
  50216. y: e.clientY
  50217. };
  50218. this.activeButton = e.button;
  50219. if (!this.noPreventDefault) {
  50220. e.preventDefault();
  50221. this.element.focus();
  50222. }
  50223. }
  50224. else
  50225. // Mouse up.
  50226. if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  50227. try {
  50228. srcElement.releasePointerCapture(e.pointerId);
  50229. }
  50230. catch (e) {
  50231. // Nothing to do with the error. Execution continues.
  50232. }
  50233. this.activeButton = -1;
  50234. this.previousPosition = null;
  50235. if (!this.noPreventDefault) {
  50236. e.preventDefault();
  50237. }
  50238. }
  50239. else
  50240. // Mouse move.
  50241. if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  50242. if (!this.previousPosition || engine.isPointerLock) {
  50243. return;
  50244. }
  50245. var offsetX = e.clientX - this.previousPosition.x;
  50246. var offsetY = e.clientY - this.previousPosition.y;
  50247. this.rotateCamera(offsetX, offsetY);
  50248. this.previousPosition = {
  50249. x: e.clientX,
  50250. y: e.clientY
  50251. };
  50252. if (!this.noPreventDefault) {
  50253. e.preventDefault();
  50254. }
  50255. }
  50256. };
  50257. // Track mouse movement, when pointer is locked.
  50258. FlyCameraMouseInput.prototype._onMouseMove = function (e) {
  50259. var camera = this.camera;
  50260. var engine = camera.getEngine();
  50261. if (!engine.isPointerLock || engine.isInVRExclusivePointerMode) {
  50262. return;
  50263. }
  50264. var offsetX = e.movementX || e.mozMovementX || e.webkitMovementX || e.msMovementX || 0;
  50265. var offsetY = e.movementY || e.mozMovementY || e.webkitMovementY || e.msMovementY || 0;
  50266. this.rotateCamera(offsetX, offsetY);
  50267. this.previousPosition = null;
  50268. if (!this.noPreventDefault) {
  50269. e.preventDefault();
  50270. }
  50271. };
  50272. /**
  50273. * Rotate camera by mouse offset.
  50274. */
  50275. FlyCameraMouseInput.prototype.rotateCamera = function (offsetX, offsetY) {
  50276. var _this = this;
  50277. var camera = this.camera;
  50278. var scene = this.camera.getScene();
  50279. if (scene.useRightHandedSystem) {
  50280. offsetX *= -1;
  50281. }
  50282. if (camera.parent && camera.parent._getWorldMatrixDeterminant() < 0) {
  50283. offsetX *= -1;
  50284. }
  50285. var x = offsetX / this.angularSensibility;
  50286. var y = offsetY / this.angularSensibility;
  50287. // Initialize to current rotation.
  50288. var currentRotation = BABYLON.Quaternion.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, camera.rotation.z);
  50289. var rotationChange;
  50290. // Pitch.
  50291. if (this.buttonsPitch.some(function (v) { return v === _this.activeButton; })) {
  50292. // Apply change in Radians to vector Angle.
  50293. rotationChange = BABYLON.Quaternion.RotationAxis(BABYLON.Axis.X, y);
  50294. // Apply Pitch to quaternion.
  50295. currentRotation.multiplyInPlace(rotationChange);
  50296. }
  50297. // Yaw.
  50298. if (this.buttonsYaw.some(function (v) { return v === _this.activeButton; })) {
  50299. // Apply change in Radians to vector Angle.
  50300. rotationChange = BABYLON.Quaternion.RotationAxis(BABYLON.Axis.Y, x);
  50301. // Apply Yaw to quaternion.
  50302. currentRotation.multiplyInPlace(rotationChange);
  50303. // Add Roll, if banked turning is enabled, within Roll limit.
  50304. var limit = (camera.bankedTurnLimit) + camera._trackRoll; // Defaults to 90° plus manual roll.
  50305. if (camera.bankedTurn && -limit < camera.rotation.z && camera.rotation.z < limit) {
  50306. var bankingDelta = camera.bankedTurnMultiplier * -x;
  50307. // Apply change in Radians to vector Angle.
  50308. rotationChange = BABYLON.Quaternion.RotationAxis(BABYLON.Axis.Z, bankingDelta);
  50309. // Apply Yaw to quaternion.
  50310. currentRotation.multiplyInPlace(rotationChange);
  50311. }
  50312. }
  50313. // Roll.
  50314. if (this.buttonsRoll.some(function (v) { return v === _this.activeButton; })) {
  50315. // Apply change in Radians to vector Angle.
  50316. rotationChange = BABYLON.Quaternion.RotationAxis(BABYLON.Axis.Z, -x);
  50317. // Track Rolling.
  50318. camera._trackRoll -= x;
  50319. // Apply Pitch to quaternion.
  50320. currentRotation.multiplyInPlace(rotationChange);
  50321. }
  50322. // Apply rotationQuaternion to Euler camera.rotation.
  50323. currentRotation.toEulerAnglesToRef(camera.rotation);
  50324. };
  50325. __decorate([
  50326. BABYLON.serialize()
  50327. ], FlyCameraMouseInput.prototype, "buttons", void 0);
  50328. __decorate([
  50329. BABYLON.serialize()
  50330. ], FlyCameraMouseInput.prototype, "angularSensibility", void 0);
  50331. return FlyCameraMouseInput;
  50332. }());
  50333. BABYLON.FlyCameraMouseInput = FlyCameraMouseInput;
  50334. BABYLON.CameraInputTypes["FlyCameraMouseInput"] = FlyCameraMouseInput;
  50335. })(BABYLON || (BABYLON = {}));
  50336. //# sourceMappingURL=babylon.flyCameraMouseInput.js.map
  50337. var BABYLON;
  50338. (function (BABYLON) {
  50339. /**
  50340. * Listen to keyboard events to control the camera.
  50341. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  50342. */
  50343. var FlyCameraKeyboardInput = /** @class */ (function () {
  50344. function FlyCameraKeyboardInput() {
  50345. /**
  50346. * The list of keyboard keys used to control the forward move of the camera.
  50347. */
  50348. this.keysForward = [87];
  50349. /**
  50350. * The list of keyboard keys used to control the backward move of the camera.
  50351. */
  50352. this.keysBackward = [83];
  50353. /**
  50354. * The list of keyboard keys used to control the forward move of the camera.
  50355. */
  50356. this.keysUp = [69];
  50357. /**
  50358. * The list of keyboard keys used to control the backward move of the camera.
  50359. */
  50360. this.keysDown = [81];
  50361. /**
  50362. * The list of keyboard keys used to control the right strafe move of the camera.
  50363. */
  50364. this.keysRight = [68];
  50365. /**
  50366. * The list of keyboard keys used to control the left strafe move of the camera.
  50367. */
  50368. this.keysLeft = [65];
  50369. this._keys = new Array();
  50370. }
  50371. /**
  50372. * Attach the input controls to a specific dom element to get the input from.
  50373. * @param element Defines the element the controls should be listened from
  50374. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  50375. */
  50376. FlyCameraKeyboardInput.prototype.attachControl = function (element, noPreventDefault) {
  50377. var _this = this;
  50378. if (this._onCanvasBlurObserver) {
  50379. return;
  50380. }
  50381. this._scene = this.camera.getScene();
  50382. this._engine = this._scene.getEngine();
  50383. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  50384. _this._keys = [];
  50385. });
  50386. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  50387. var evt = info.event;
  50388. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  50389. if (_this.keysForward.indexOf(evt.keyCode) !== -1 ||
  50390. _this.keysBackward.indexOf(evt.keyCode) !== -1 ||
  50391. _this.keysUp.indexOf(evt.keyCode) !== -1 ||
  50392. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  50393. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  50394. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  50395. var index = _this._keys.indexOf(evt.keyCode);
  50396. if (index === -1) {
  50397. _this._keys.push(evt.keyCode);
  50398. }
  50399. if (!noPreventDefault) {
  50400. evt.preventDefault();
  50401. }
  50402. }
  50403. }
  50404. else {
  50405. if (_this.keysForward.indexOf(evt.keyCode) !== -1 ||
  50406. _this.keysBackward.indexOf(evt.keyCode) !== -1 ||
  50407. _this.keysUp.indexOf(evt.keyCode) !== -1 ||
  50408. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  50409. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  50410. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  50411. var index = _this._keys.indexOf(evt.keyCode);
  50412. if (index >= 0) {
  50413. _this._keys.splice(index, 1);
  50414. }
  50415. if (!noPreventDefault) {
  50416. evt.preventDefault();
  50417. }
  50418. }
  50419. }
  50420. });
  50421. };
  50422. /**
  50423. * Detach the current controls from the specified dom element.
  50424. * @param element Defines the element to stop listening the inputs from
  50425. */
  50426. FlyCameraKeyboardInput.prototype.detachControl = function (element) {
  50427. if (this._scene) {
  50428. if (this._onKeyboardObserver) {
  50429. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  50430. }
  50431. if (this._onCanvasBlurObserver) {
  50432. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  50433. }
  50434. this._onKeyboardObserver = null;
  50435. this._onCanvasBlurObserver = null;
  50436. }
  50437. this._keys = [];
  50438. };
  50439. /**
  50440. * Gets the class name of the current intput.
  50441. * @returns the class name
  50442. */
  50443. FlyCameraKeyboardInput.prototype.getClassName = function () {
  50444. return "FlyCameraKeyboardInput";
  50445. };
  50446. /** @hidden */
  50447. FlyCameraKeyboardInput.prototype._onLostFocus = function (e) {
  50448. this._keys = [];
  50449. };
  50450. /**
  50451. * Get the friendly name associated with the input class.
  50452. * @returns the input friendly name
  50453. */
  50454. FlyCameraKeyboardInput.prototype.getSimpleName = function () {
  50455. return "keyboard";
  50456. };
  50457. /**
  50458. * Update the current camera state depending on the inputs that have been used this frame.
  50459. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  50460. */
  50461. FlyCameraKeyboardInput.prototype.checkInputs = function () {
  50462. if (this._onKeyboardObserver) {
  50463. var camera = this.camera;
  50464. // Keyboard
  50465. for (var index = 0; index < this._keys.length; index++) {
  50466. var keyCode = this._keys[index];
  50467. var speed = camera._computeLocalCameraSpeed();
  50468. if (this.keysForward.indexOf(keyCode) !== -1) {
  50469. camera._localDirection.copyFromFloats(0, 0, speed);
  50470. }
  50471. else if (this.keysBackward.indexOf(keyCode) !== -1) {
  50472. camera._localDirection.copyFromFloats(0, 0, -speed);
  50473. }
  50474. else if (this.keysUp.indexOf(keyCode) !== -1) {
  50475. camera._localDirection.copyFromFloats(0, speed, 0);
  50476. }
  50477. else if (this.keysDown.indexOf(keyCode) !== -1) {
  50478. camera._localDirection.copyFromFloats(0, -speed, 0);
  50479. }
  50480. else if (this.keysRight.indexOf(keyCode) !== -1) {
  50481. camera._localDirection.copyFromFloats(speed, 0, 0);
  50482. }
  50483. else if (this.keysLeft.indexOf(keyCode) !== -1) {
  50484. camera._localDirection.copyFromFloats(-speed, 0, 0);
  50485. }
  50486. if (camera.getScene().useRightHandedSystem) {
  50487. camera._localDirection.z *= -1;
  50488. }
  50489. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  50490. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  50491. camera.cameraDirection.addInPlace(camera._transformedDirection);
  50492. }
  50493. }
  50494. };
  50495. __decorate([
  50496. BABYLON.serialize()
  50497. ], FlyCameraKeyboardInput.prototype, "keysForward", void 0);
  50498. __decorate([
  50499. BABYLON.serialize()
  50500. ], FlyCameraKeyboardInput.prototype, "keysBackward", void 0);
  50501. __decorate([
  50502. BABYLON.serialize()
  50503. ], FlyCameraKeyboardInput.prototype, "keysUp", void 0);
  50504. __decorate([
  50505. BABYLON.serialize()
  50506. ], FlyCameraKeyboardInput.prototype, "keysDown", void 0);
  50507. __decorate([
  50508. BABYLON.serialize()
  50509. ], FlyCameraKeyboardInput.prototype, "keysRight", void 0);
  50510. __decorate([
  50511. BABYLON.serialize()
  50512. ], FlyCameraKeyboardInput.prototype, "keysLeft", void 0);
  50513. return FlyCameraKeyboardInput;
  50514. }());
  50515. BABYLON.FlyCameraKeyboardInput = FlyCameraKeyboardInput;
  50516. BABYLON.CameraInputTypes["FlyCameraKeyboardInput"] = FlyCameraKeyboardInput;
  50517. })(BABYLON || (BABYLON = {}));
  50518. //# sourceMappingURL=babylon.flyCameraKeyboardInput.js.map
  50519. var BABYLON;
  50520. (function (BABYLON) {
  50521. /**
  50522. * Default Inputs manager for the FlyCamera.
  50523. * It groups all the default supported inputs for ease of use.
  50524. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  50525. */
  50526. var FlyCameraInputsManager = /** @class */ (function (_super) {
  50527. __extends(FlyCameraInputsManager, _super);
  50528. /**
  50529. * Instantiates a new FlyCameraInputsManager.
  50530. * @param camera Defines the camera the inputs belong to.
  50531. */
  50532. function FlyCameraInputsManager(camera) {
  50533. return _super.call(this, camera) || this;
  50534. }
  50535. /**
  50536. * Add keyboard input support to the input manager.
  50537. * @returns the new FlyCameraKeyboardMoveInput().
  50538. */
  50539. FlyCameraInputsManager.prototype.addKeyboard = function () {
  50540. this.add(new BABYLON.FlyCameraKeyboardInput());
  50541. return this;
  50542. };
  50543. /**
  50544. * Add mouse input support to the input manager.
  50545. * @param touchEnabled Enable touch screen support.
  50546. * @returns the new FlyCameraMouseInput().
  50547. */
  50548. FlyCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  50549. if (touchEnabled === void 0) { touchEnabled = true; }
  50550. this.add(new BABYLON.FlyCameraMouseInput(touchEnabled));
  50551. return this;
  50552. };
  50553. return FlyCameraInputsManager;
  50554. }(BABYLON.CameraInputsManager));
  50555. BABYLON.FlyCameraInputsManager = FlyCameraInputsManager;
  50556. })(BABYLON || (BABYLON = {}));
  50557. //# sourceMappingURL=babylon.flyCameraInputsManager.js.map
  50558. var BABYLON;
  50559. (function (BABYLON) {
  50560. /**
  50561. * This is a flying camera, designed for 3D movement and rotation in all directions,
  50562. * such as in a 3D Space Shooter or a Flight Simulator.
  50563. */
  50564. var FlyCamera = /** @class */ (function (_super) {
  50565. __extends(FlyCamera, _super);
  50566. /**
  50567. * Instantiates a FlyCamera.
  50568. * This is a flying camera, designed for 3D movement and rotation in all directions,
  50569. * such as in a 3D Space Shooter or a Flight Simulator.
  50570. * @param name Define the name of the camera in the scene.
  50571. * @param position Define the starting position of the camera in the scene.
  50572. * @param scene Define the scene the camera belongs to.
  50573. * @param setActiveOnSceneIfNoneActive Defines wheter the camera should be marked as active, if no other camera has been defined as active.
  50574. */
  50575. function FlyCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  50576. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  50577. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  50578. /**
  50579. * Define the collision ellipsoid of the camera.
  50580. * This is helpful for simulating a camera body, like a player's body.
  50581. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#arcrotatecamera
  50582. */
  50583. _this.ellipsoid = new BABYLON.Vector3(1, 1, 1);
  50584. /**
  50585. * Define an offset for the position of the ellipsoid around the camera.
  50586. * This can be helpful if the camera is attached away from the player's body center,
  50587. * such as at its head.
  50588. */
  50589. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  50590. /**
  50591. * Enable or disable collisions of the camera with the rest of the scene objects.
  50592. */
  50593. _this.checkCollisions = false;
  50594. /**
  50595. * Enable or disable gravity on the camera.
  50596. */
  50597. _this.applyGravity = false;
  50598. /**
  50599. * Define the current direction the camera is moving to.
  50600. */
  50601. _this.cameraDirection = BABYLON.Vector3.Zero();
  50602. /**
  50603. * Track Roll to maintain the wanted Rolling when looking around.
  50604. */
  50605. _this._trackRoll = 0;
  50606. /**
  50607. * Slowly correct the Roll to its original value after a Pitch+Yaw rotation.
  50608. */
  50609. _this.rollCorrect = 100;
  50610. /**
  50611. * Mimic a banked turn, Rolling the camera when Yawing.
  50612. * It's recommended to use rollCorrect = 10 for faster banking correction.
  50613. */
  50614. _this.bankedTurn = false;
  50615. /**
  50616. * Limit in radians for how much Roll banking will add. (Default: 90°)
  50617. */
  50618. _this.bankedTurnLimit = Math.PI / 2;
  50619. /**
  50620. * Value of 0 disables the banked Roll.
  50621. * Value of 1 is equal to the Yaw angle in radians.
  50622. */
  50623. _this.bankedTurnMultiplier = 1;
  50624. _this._needMoveForGravity = false;
  50625. _this._oldPosition = BABYLON.Vector3.Zero();
  50626. _this._diffPosition = BABYLON.Vector3.Zero();
  50627. _this._newPosition = BABYLON.Vector3.Zero();
  50628. // Collisions.
  50629. _this._collisionMask = -1;
  50630. /** @hidden */
  50631. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  50632. if (collidedMesh === void 0) { collidedMesh = null; }
  50633. // TODO Move this to the collision coordinator!
  50634. if (_this.getScene().workerCollisions) {
  50635. newPosition.multiplyInPlace(_this._collider._radius);
  50636. }
  50637. var updatePosition = function (newPos) {
  50638. _this._newPosition.copyFrom(newPos);
  50639. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  50640. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  50641. _this.position.addInPlace(_this._diffPosition);
  50642. if (_this.onCollide && collidedMesh) {
  50643. _this.onCollide(collidedMesh);
  50644. }
  50645. }
  50646. };
  50647. updatePosition(newPosition);
  50648. };
  50649. _this.inputs = new BABYLON.FlyCameraInputsManager(_this);
  50650. _this.inputs.addKeyboard().addMouse();
  50651. return _this;
  50652. }
  50653. Object.defineProperty(FlyCamera.prototype, "angularSensibility", {
  50654. /**
  50655. * Gets the input sensibility for mouse input.
  50656. * Higher values reduce sensitivity.
  50657. */
  50658. get: function () {
  50659. var mouse = this.inputs.attached["mouse"];
  50660. if (mouse) {
  50661. return mouse.angularSensibility;
  50662. }
  50663. return 0;
  50664. },
  50665. /**
  50666. * Sets the input sensibility for a mouse input.
  50667. * Higher values reduce sensitivity.
  50668. */
  50669. set: function (value) {
  50670. var mouse = this.inputs.attached["mouse"];
  50671. if (mouse) {
  50672. mouse.angularSensibility = value;
  50673. }
  50674. },
  50675. enumerable: true,
  50676. configurable: true
  50677. });
  50678. Object.defineProperty(FlyCamera.prototype, "keysForward", {
  50679. /**
  50680. * Get the keys for camera movement forward.
  50681. */
  50682. get: function () {
  50683. var keyboard = this.inputs.attached["keyboard"];
  50684. if (keyboard) {
  50685. return keyboard.keysForward;
  50686. }
  50687. return [];
  50688. },
  50689. /**
  50690. * Set the keys for camera movement forward.
  50691. */
  50692. set: function (value) {
  50693. var keyboard = this.inputs.attached["keyboard"];
  50694. if (keyboard) {
  50695. keyboard.keysForward = value;
  50696. }
  50697. },
  50698. enumerable: true,
  50699. configurable: true
  50700. });
  50701. Object.defineProperty(FlyCamera.prototype, "keysBackward", {
  50702. /**
  50703. * Get the keys for camera movement backward.
  50704. */
  50705. get: function () {
  50706. var keyboard = this.inputs.attached["keyboard"];
  50707. if (keyboard) {
  50708. return keyboard.keysBackward;
  50709. }
  50710. return [];
  50711. },
  50712. set: function (value) {
  50713. var keyboard = this.inputs.attached["keyboard"];
  50714. if (keyboard) {
  50715. keyboard.keysBackward = value;
  50716. }
  50717. },
  50718. enumerable: true,
  50719. configurable: true
  50720. });
  50721. Object.defineProperty(FlyCamera.prototype, "keysUp", {
  50722. /**
  50723. * Get the keys for camera movement up.
  50724. */
  50725. get: function () {
  50726. var keyboard = this.inputs.attached["keyboard"];
  50727. if (keyboard) {
  50728. return keyboard.keysUp;
  50729. }
  50730. return [];
  50731. },
  50732. /**
  50733. * Set the keys for camera movement up.
  50734. */
  50735. set: function (value) {
  50736. var keyboard = this.inputs.attached["keyboard"];
  50737. if (keyboard) {
  50738. keyboard.keysUp = value;
  50739. }
  50740. },
  50741. enumerable: true,
  50742. configurable: true
  50743. });
  50744. Object.defineProperty(FlyCamera.prototype, "keysDown", {
  50745. /**
  50746. * Get the keys for camera movement down.
  50747. */
  50748. get: function () {
  50749. var keyboard = this.inputs.attached["keyboard"];
  50750. if (keyboard) {
  50751. return keyboard.keysDown;
  50752. }
  50753. return [];
  50754. },
  50755. /**
  50756. * Set the keys for camera movement down.
  50757. */
  50758. set: function (value) {
  50759. var keyboard = this.inputs.attached["keyboard"];
  50760. if (keyboard) {
  50761. keyboard.keysDown = value;
  50762. }
  50763. },
  50764. enumerable: true,
  50765. configurable: true
  50766. });
  50767. Object.defineProperty(FlyCamera.prototype, "keysLeft", {
  50768. /**
  50769. * Get the keys for camera movement left.
  50770. */
  50771. get: function () {
  50772. var keyboard = this.inputs.attached["keyboard"];
  50773. if (keyboard) {
  50774. return keyboard.keysLeft;
  50775. }
  50776. return [];
  50777. },
  50778. /**
  50779. * Set the keys for camera movement left.
  50780. */
  50781. set: function (value) {
  50782. var keyboard = this.inputs.attached["keyboard"];
  50783. if (keyboard) {
  50784. keyboard.keysLeft = value;
  50785. }
  50786. },
  50787. enumerable: true,
  50788. configurable: true
  50789. });
  50790. Object.defineProperty(FlyCamera.prototype, "keysRight", {
  50791. /**
  50792. * Set the keys for camera movement right.
  50793. */
  50794. get: function () {
  50795. var keyboard = this.inputs.attached["keyboard"];
  50796. if (keyboard) {
  50797. return keyboard.keysRight;
  50798. }
  50799. return [];
  50800. },
  50801. /**
  50802. * Set the keys for camera movement right.
  50803. */
  50804. set: function (value) {
  50805. var keyboard = this.inputs.attached["keyboard"];
  50806. if (keyboard) {
  50807. keyboard.keysRight = value;
  50808. }
  50809. },
  50810. enumerable: true,
  50811. configurable: true
  50812. });
  50813. /**
  50814. * Attach a control to the HTML DOM element.
  50815. * @param element Defines the element that listens to the input events.
  50816. * @param noPreventDefault Defines whether events caught by the controls should call preventdefault(). https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault
  50817. */
  50818. FlyCamera.prototype.attachControl = function (element, noPreventDefault) {
  50819. this.inputs.attachElement(element, noPreventDefault);
  50820. };
  50821. /**
  50822. * Detach a control from the HTML DOM element.
  50823. * The camera will stop reacting to that input.
  50824. * @param element Defines the element that listens to the input events.
  50825. */
  50826. FlyCamera.prototype.detachControl = function (element) {
  50827. this.inputs.detachElement(element);
  50828. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  50829. };
  50830. Object.defineProperty(FlyCamera.prototype, "collisionMask", {
  50831. /**
  50832. * Get the mask that the camera ignores in collision events.
  50833. */
  50834. get: function () {
  50835. return this._collisionMask;
  50836. },
  50837. /**
  50838. * Set the mask that the camera ignores in collision events.
  50839. */
  50840. set: function (mask) {
  50841. this._collisionMask = !isNaN(mask) ? mask : -1;
  50842. },
  50843. enumerable: true,
  50844. configurable: true
  50845. });
  50846. /** @hidden */
  50847. FlyCamera.prototype._collideWithWorld = function (displacement) {
  50848. var globalPosition;
  50849. if (this.parent) {
  50850. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  50851. }
  50852. else {
  50853. globalPosition = this.position;
  50854. }
  50855. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  50856. this._oldPosition.addInPlace(this.ellipsoidOffset);
  50857. if (!this._collider) {
  50858. this._collider = new BABYLON.Collider();
  50859. }
  50860. this._collider._radius = this.ellipsoid;
  50861. this._collider.collisionMask = this._collisionMask;
  50862. // No need for clone, as long as gravity is not on.
  50863. var actualDisplacement = displacement;
  50864. // Add gravity to direction to prevent dual-collision checking.
  50865. if (this.applyGravity) {
  50866. // This prevents mending with cameraDirection, a global variable of the fly camera class.
  50867. actualDisplacement = displacement.add(this.getScene().gravity);
  50868. }
  50869. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  50870. };
  50871. /** @hidden */
  50872. FlyCamera.prototype._checkInputs = function () {
  50873. if (!this._localDirection) {
  50874. this._localDirection = BABYLON.Vector3.Zero();
  50875. this._transformedDirection = BABYLON.Vector3.Zero();
  50876. }
  50877. this.inputs.checkInputs();
  50878. _super.prototype._checkInputs.call(this);
  50879. };
  50880. /** @hidden */
  50881. FlyCamera.prototype._decideIfNeedsToMove = function () {
  50882. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  50883. };
  50884. /** @hidden */
  50885. FlyCamera.prototype._updatePosition = function () {
  50886. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  50887. this._collideWithWorld(this.cameraDirection);
  50888. }
  50889. else {
  50890. _super.prototype._updatePosition.call(this);
  50891. }
  50892. };
  50893. /**
  50894. * Restore the Roll to its target value at the rate specified.
  50895. * @param rate - Higher means slower restoring.
  50896. * @hidden
  50897. */
  50898. FlyCamera.prototype.restoreRoll = function (rate) {
  50899. var limit = this._trackRoll; // Target Roll.
  50900. var z = this.rotation.z; // Current Roll.
  50901. var delta = limit - z; // Difference in Roll.
  50902. var minRad = 0.001; // Tenth of a radian is a barely noticable difference.
  50903. // If the difference is noticable, restore the Roll.
  50904. if (Math.abs(delta) >= minRad) {
  50905. // Change Z rotation towards the target Roll.
  50906. this.rotation.z += delta / rate;
  50907. // Match when near enough.
  50908. if (Math.abs(limit - this.rotation.z) <= minRad) {
  50909. this.rotation.z = limit;
  50910. }
  50911. }
  50912. };
  50913. /**
  50914. * Destroy the camera and release the current resources held by it.
  50915. */
  50916. FlyCamera.prototype.dispose = function () {
  50917. this.inputs.clear();
  50918. _super.prototype.dispose.call(this);
  50919. };
  50920. /**
  50921. * Get the current object class name.
  50922. * @returns the class name.
  50923. */
  50924. FlyCamera.prototype.getClassName = function () {
  50925. return "FlyCamera";
  50926. };
  50927. __decorate([
  50928. BABYLON.serializeAsVector3()
  50929. ], FlyCamera.prototype, "ellipsoid", void 0);
  50930. __decorate([
  50931. BABYLON.serializeAsVector3()
  50932. ], FlyCamera.prototype, "ellipsoidOffset", void 0);
  50933. __decorate([
  50934. BABYLON.serialize()
  50935. ], FlyCamera.prototype, "checkCollisions", void 0);
  50936. __decorate([
  50937. BABYLON.serialize()
  50938. ], FlyCamera.prototype, "applyGravity", void 0);
  50939. return FlyCamera;
  50940. }(BABYLON.TargetCamera));
  50941. BABYLON.FlyCamera = FlyCamera;
  50942. })(BABYLON || (BABYLON = {}));
  50943. //# sourceMappingURL=babylon.flyCamera.js.map
  50944. var BABYLON;
  50945. (function (BABYLON) {
  50946. /**
  50947. * Manage the keyboard inputs to control the movement of an arc rotate camera.
  50948. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  50949. */
  50950. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  50951. function ArcRotateCameraKeyboardMoveInput() {
  50952. /**
  50953. * Defines the list of key codes associated with the up action (increase alpha)
  50954. */
  50955. this.keysUp = [38];
  50956. /**
  50957. * Defines the list of key codes associated with the down action (decrease alpha)
  50958. */
  50959. this.keysDown = [40];
  50960. /**
  50961. * Defines the list of key codes associated with the left action (increase beta)
  50962. */
  50963. this.keysLeft = [37];
  50964. /**
  50965. * Defines the list of key codes associated with the right action (decrease beta)
  50966. */
  50967. this.keysRight = [39];
  50968. /**
  50969. * Defines the list of key codes associated with the reset action.
  50970. * Those keys reset the camera to its last stored state (with the method camera.storeState())
  50971. */
  50972. this.keysReset = [220];
  50973. /**
  50974. * Defines the panning sensibility of the inputs.
  50975. * (How fast is the camera paning)
  50976. */
  50977. this.panningSensibility = 50.0;
  50978. /**
  50979. * Defines the zooming sensibility of the inputs.
  50980. * (How fast is the camera zooming)
  50981. */
  50982. this.zoomingSensibility = 25.0;
  50983. /**
  50984. * Defines wether maintaining the alt key down switch the movement mode from
  50985. * orientation to zoom.
  50986. */
  50987. this.useAltToZoom = true;
  50988. /**
  50989. * Rotation speed of the camera
  50990. */
  50991. this.angularSpeed = 0.01;
  50992. this._keys = new Array();
  50993. }
  50994. /**
  50995. * Attach the input controls to a specific dom element to get the input from.
  50996. * @param element Defines the element the controls should be listened from
  50997. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  50998. */
  50999. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  51000. var _this = this;
  51001. if (this._onCanvasBlurObserver) {
  51002. return;
  51003. }
  51004. this._scene = this.camera.getScene();
  51005. this._engine = this._scene.getEngine();
  51006. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  51007. _this._keys = [];
  51008. });
  51009. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  51010. var evt = info.event;
  51011. if (!evt.metaKey) {
  51012. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  51013. _this._ctrlPressed = evt.ctrlKey;
  51014. _this._altPressed = evt.altKey;
  51015. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  51016. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  51017. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  51018. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  51019. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  51020. var index = _this._keys.indexOf(evt.keyCode);
  51021. if (index === -1) {
  51022. _this._keys.push(evt.keyCode);
  51023. }
  51024. if (evt.preventDefault) {
  51025. if (!noPreventDefault) {
  51026. evt.preventDefault();
  51027. }
  51028. }
  51029. }
  51030. }
  51031. else {
  51032. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  51033. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  51034. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  51035. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  51036. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  51037. var index = _this._keys.indexOf(evt.keyCode);
  51038. if (index >= 0) {
  51039. _this._keys.splice(index, 1);
  51040. }
  51041. if (evt.preventDefault) {
  51042. if (!noPreventDefault) {
  51043. evt.preventDefault();
  51044. }
  51045. }
  51046. }
  51047. }
  51048. }
  51049. });
  51050. };
  51051. /**
  51052. * Detach the current controls from the specified dom element.
  51053. * @param element Defines the element to stop listening the inputs from
  51054. */
  51055. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  51056. if (this._scene) {
  51057. if (this._onKeyboardObserver) {
  51058. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  51059. }
  51060. if (this._onCanvasBlurObserver) {
  51061. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  51062. }
  51063. this._onKeyboardObserver = null;
  51064. this._onCanvasBlurObserver = null;
  51065. }
  51066. this._keys = [];
  51067. };
  51068. /**
  51069. * Update the current camera state depending on the inputs that have been used this frame.
  51070. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  51071. */
  51072. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  51073. if (this._onKeyboardObserver) {
  51074. var camera = this.camera;
  51075. for (var index = 0; index < this._keys.length; index++) {
  51076. var keyCode = this._keys[index];
  51077. if (this.keysLeft.indexOf(keyCode) !== -1) {
  51078. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  51079. camera.inertialPanningX -= 1 / this.panningSensibility;
  51080. }
  51081. else {
  51082. camera.inertialAlphaOffset -= this.angularSpeed;
  51083. }
  51084. }
  51085. else if (this.keysUp.indexOf(keyCode) !== -1) {
  51086. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  51087. camera.inertialPanningY += 1 / this.panningSensibility;
  51088. }
  51089. else if (this._altPressed && this.useAltToZoom) {
  51090. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  51091. }
  51092. else {
  51093. camera.inertialBetaOffset -= this.angularSpeed;
  51094. }
  51095. }
  51096. else if (this.keysRight.indexOf(keyCode) !== -1) {
  51097. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  51098. camera.inertialPanningX += 1 / this.panningSensibility;
  51099. }
  51100. else {
  51101. camera.inertialAlphaOffset += this.angularSpeed;
  51102. }
  51103. }
  51104. else if (this.keysDown.indexOf(keyCode) !== -1) {
  51105. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  51106. camera.inertialPanningY -= 1 / this.panningSensibility;
  51107. }
  51108. else if (this._altPressed && this.useAltToZoom) {
  51109. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  51110. }
  51111. else {
  51112. camera.inertialBetaOffset += this.angularSpeed;
  51113. }
  51114. }
  51115. else if (this.keysReset.indexOf(keyCode) !== -1) {
  51116. if (camera.useInputToRestoreState) {
  51117. camera.restoreState();
  51118. }
  51119. }
  51120. }
  51121. }
  51122. };
  51123. /**
  51124. * Gets the class name of the current intput.
  51125. * @returns the class name
  51126. */
  51127. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  51128. return "ArcRotateCameraKeyboardMoveInput";
  51129. };
  51130. /**
  51131. * Get the friendly name associated with the input class.
  51132. * @returns the input friendly name
  51133. */
  51134. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  51135. return "keyboard";
  51136. };
  51137. __decorate([
  51138. BABYLON.serialize()
  51139. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  51140. __decorate([
  51141. BABYLON.serialize()
  51142. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  51143. __decorate([
  51144. BABYLON.serialize()
  51145. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  51146. __decorate([
  51147. BABYLON.serialize()
  51148. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  51149. __decorate([
  51150. BABYLON.serialize()
  51151. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  51152. __decorate([
  51153. BABYLON.serialize()
  51154. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  51155. __decorate([
  51156. BABYLON.serialize()
  51157. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  51158. __decorate([
  51159. BABYLON.serialize()
  51160. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  51161. __decorate([
  51162. BABYLON.serialize()
  51163. ], ArcRotateCameraKeyboardMoveInput.prototype, "angularSpeed", void 0);
  51164. return ArcRotateCameraKeyboardMoveInput;
  51165. }());
  51166. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  51167. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  51168. })(BABYLON || (BABYLON = {}));
  51169. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  51170. var BABYLON;
  51171. (function (BABYLON) {
  51172. /**
  51173. * Manage the mouse wheel inputs to control an arc rotate camera.
  51174. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  51175. */
  51176. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  51177. function ArcRotateCameraMouseWheelInput() {
  51178. /**
  51179. * Gets or Set the mouse wheel precision or how fast is the camera zooming.
  51180. */
  51181. this.wheelPrecision = 3.0;
  51182. /**
  51183. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  51184. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  51185. */
  51186. this.wheelDeltaPercentage = 0;
  51187. }
  51188. /**
  51189. * Attach the input controls to a specific dom element to get the input from.
  51190. * @param element Defines the element the controls should be listened from
  51191. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  51192. */
  51193. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  51194. var _this = this;
  51195. this._wheel = function (p, s) {
  51196. //sanity check - this should be a PointerWheel event.
  51197. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL) {
  51198. return;
  51199. }
  51200. var event = p.event;
  51201. var delta = 0;
  51202. if (event.wheelDelta) {
  51203. if (_this.wheelDeltaPercentage) {
  51204. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  51205. if (event.wheelDelta > 0) {
  51206. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  51207. }
  51208. else {
  51209. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  51210. }
  51211. }
  51212. else {
  51213. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  51214. }
  51215. }
  51216. else {
  51217. var deltaValue = event.deltaY || event.detail;
  51218. delta = -deltaValue / _this.wheelPrecision;
  51219. }
  51220. if (delta) {
  51221. _this.camera.inertialRadiusOffset += delta;
  51222. }
  51223. if (event.preventDefault) {
  51224. if (!noPreventDefault) {
  51225. event.preventDefault();
  51226. }
  51227. }
  51228. };
  51229. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  51230. };
  51231. /**
  51232. * Detach the current controls from the specified dom element.
  51233. * @param element Defines the element to stop listening the inputs from
  51234. */
  51235. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  51236. if (this._observer && element) {
  51237. this.camera.getScene().onPointerObservable.remove(this._observer);
  51238. this._observer = null;
  51239. this._wheel = null;
  51240. }
  51241. };
  51242. /**
  51243. * Gets the class name of the current intput.
  51244. * @returns the class name
  51245. */
  51246. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  51247. return "ArcRotateCameraMouseWheelInput";
  51248. };
  51249. /**
  51250. * Get the friendly name associated with the input class.
  51251. * @returns the input friendly name
  51252. */
  51253. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  51254. return "mousewheel";
  51255. };
  51256. __decorate([
  51257. BABYLON.serialize()
  51258. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  51259. __decorate([
  51260. BABYLON.serialize()
  51261. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  51262. return ArcRotateCameraMouseWheelInput;
  51263. }());
  51264. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  51265. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  51266. })(BABYLON || (BABYLON = {}));
  51267. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  51268. var BABYLON;
  51269. (function (BABYLON) {
  51270. /**
  51271. * Manage the pointers inputs to control an arc rotate camera.
  51272. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  51273. */
  51274. var ArcRotateCameraPointersInput = /** @class */ (function () {
  51275. function ArcRotateCameraPointersInput() {
  51276. /**
  51277. * Defines the buttons associated with the input to handle camera move.
  51278. */
  51279. this.buttons = [0, 1, 2];
  51280. /**
  51281. * Defines the pointer angular sensibility along the X axis or how fast is the camera rotating.
  51282. */
  51283. this.angularSensibilityX = 1000.0;
  51284. /**
  51285. * Defines the pointer angular sensibility along the Y axis or how fast is the camera rotating.
  51286. */
  51287. this.angularSensibilityY = 1000.0;
  51288. /**
  51289. * Defines the pointer pinch precision or how fast is the camera zooming.
  51290. */
  51291. this.pinchPrecision = 12.0;
  51292. /**
  51293. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  51294. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  51295. */
  51296. this.pinchDeltaPercentage = 0;
  51297. /**
  51298. * Defines the pointer panning sensibility or how fast is the camera moving.
  51299. */
  51300. this.panningSensibility = 1000.0;
  51301. /**
  51302. * Defines whether panning (2 fingers swipe) is enabled through multitouch.
  51303. */
  51304. this.multiTouchPanning = true;
  51305. /**
  51306. * Defines whether panning is enabled for both pan (2 fingers swipe) and zoom (pinch) through multitouch.
  51307. */
  51308. this.multiTouchPanAndZoom = true;
  51309. /**
  51310. * Revers pinch action direction.
  51311. */
  51312. this.pinchInwards = true;
  51313. this._isPanClick = false;
  51314. }
  51315. /**
  51316. * Attach the input controls to a specific dom element to get the input from.
  51317. * @param element Defines the element the controls should be listened from
  51318. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  51319. */
  51320. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  51321. var _this = this;
  51322. var engine = this.camera.getEngine();
  51323. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  51324. var pointA = null;
  51325. var pointB = null;
  51326. var previousPinchSquaredDistance = 0;
  51327. var initialDistance = 0;
  51328. var twoFingerActivityCount = 0;
  51329. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  51330. this._pointerInput = function (p, s) {
  51331. var evt = p.event;
  51332. var isTouch = p.event.pointerType === "touch";
  51333. if (engine.isInVRExclusivePointerMode) {
  51334. return;
  51335. }
  51336. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  51337. return;
  51338. }
  51339. var srcElement = (evt.srcElement || evt.target);
  51340. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  51341. try {
  51342. srcElement.setPointerCapture(evt.pointerId);
  51343. }
  51344. catch (e) {
  51345. //Nothing to do with the error. Execution will continue.
  51346. }
  51347. // Manage panning with pan button click
  51348. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  51349. // manage pointers
  51350. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  51351. if (pointA === null) {
  51352. pointA = cacheSoloPointer;
  51353. }
  51354. else if (pointB === null) {
  51355. pointB = cacheSoloPointer;
  51356. }
  51357. if (!noPreventDefault) {
  51358. evt.preventDefault();
  51359. element.focus();
  51360. }
  51361. }
  51362. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  51363. if (_this.camera.useInputToRestoreState) {
  51364. _this.camera.restoreState();
  51365. }
  51366. }
  51367. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  51368. try {
  51369. srcElement.releasePointerCapture(evt.pointerId);
  51370. }
  51371. catch (e) {
  51372. //Nothing to do with the error.
  51373. }
  51374. cacheSoloPointer = null;
  51375. previousPinchSquaredDistance = 0;
  51376. previousMultiTouchPanPosition.isPaning = false;
  51377. previousMultiTouchPanPosition.isPinching = false;
  51378. twoFingerActivityCount = 0;
  51379. initialDistance = 0;
  51380. if (!isTouch) {
  51381. pointB = null; // Mouse and pen are mono pointer
  51382. }
  51383. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  51384. //but emptying completly pointers collection is required to fix a bug on iPhone :
  51385. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  51386. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  51387. if (engine._badOS) {
  51388. pointA = pointB = null;
  51389. }
  51390. else {
  51391. //only remove the impacted pointer in case of multitouch allowing on most
  51392. //platforms switching from rotate to zoom and pan seamlessly.
  51393. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  51394. pointA = pointB;
  51395. pointB = null;
  51396. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  51397. }
  51398. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  51399. pointB = null;
  51400. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  51401. }
  51402. else {
  51403. pointA = pointB = null;
  51404. }
  51405. }
  51406. if (!noPreventDefault) {
  51407. evt.preventDefault();
  51408. }
  51409. }
  51410. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  51411. if (!noPreventDefault) {
  51412. evt.preventDefault();
  51413. }
  51414. // One button down
  51415. if (pointA && pointB === null && cacheSoloPointer) {
  51416. if (_this.panningSensibility !== 0 &&
  51417. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  51418. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  51419. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  51420. }
  51421. else {
  51422. var offsetX = evt.clientX - cacheSoloPointer.x;
  51423. var offsetY = evt.clientY - cacheSoloPointer.y;
  51424. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  51425. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  51426. }
  51427. cacheSoloPointer.x = evt.clientX;
  51428. cacheSoloPointer.y = evt.clientY;
  51429. }
  51430. // Two buttons down: pinch/pan
  51431. else if (pointA && pointB) {
  51432. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  51433. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  51434. ed.x = evt.clientX;
  51435. ed.y = evt.clientY;
  51436. var direction = _this.pinchInwards ? 1 : -1;
  51437. var distX = pointA.x - pointB.x;
  51438. var distY = pointA.y - pointB.y;
  51439. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  51440. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  51441. if (previousPinchSquaredDistance === 0) {
  51442. initialDistance = pinchDistance;
  51443. previousPinchSquaredDistance = pinchSquaredDistance;
  51444. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  51445. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  51446. return;
  51447. }
  51448. if (_this.multiTouchPanAndZoom) {
  51449. if (_this.pinchDeltaPercentage) {
  51450. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  51451. }
  51452. else {
  51453. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  51454. (_this.pinchPrecision *
  51455. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  51456. direction);
  51457. }
  51458. if (_this.panningSensibility !== 0) {
  51459. var pointersCenterX = (pointA.x + pointB.x) / 2;
  51460. var pointersCenterY = (pointA.y + pointB.y) / 2;
  51461. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  51462. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  51463. previousMultiTouchPanPosition.x = pointersCenterX;
  51464. previousMultiTouchPanPosition.y = pointersCenterY;
  51465. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  51466. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  51467. }
  51468. }
  51469. else {
  51470. twoFingerActivityCount++;
  51471. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  51472. if (_this.pinchDeltaPercentage) {
  51473. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  51474. }
  51475. else {
  51476. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  51477. (_this.pinchPrecision *
  51478. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  51479. direction);
  51480. }
  51481. previousMultiTouchPanPosition.isPaning = false;
  51482. previousMultiTouchPanPosition.isPinching = true;
  51483. }
  51484. else {
  51485. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  51486. if (!previousMultiTouchPanPosition.isPaning) {
  51487. previousMultiTouchPanPosition.isPaning = true;
  51488. previousMultiTouchPanPosition.isPinching = false;
  51489. previousMultiTouchPanPosition.x = ed.x;
  51490. previousMultiTouchPanPosition.y = ed.y;
  51491. return;
  51492. }
  51493. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  51494. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  51495. }
  51496. }
  51497. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  51498. previousMultiTouchPanPosition.x = ed.x;
  51499. previousMultiTouchPanPosition.y = ed.y;
  51500. }
  51501. }
  51502. previousPinchSquaredDistance = pinchSquaredDistance;
  51503. }
  51504. }
  51505. };
  51506. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  51507. this._onContextMenu = function (evt) {
  51508. evt.preventDefault();
  51509. };
  51510. if (!this.camera._useCtrlForPanning) {
  51511. element.addEventListener("contextmenu", this._onContextMenu, false);
  51512. }
  51513. this._onLostFocus = function () {
  51514. //this._keys = [];
  51515. pointA = pointB = null;
  51516. previousPinchSquaredDistance = 0;
  51517. previousMultiTouchPanPosition.isPaning = false;
  51518. previousMultiTouchPanPosition.isPinching = false;
  51519. twoFingerActivityCount = 0;
  51520. cacheSoloPointer = null;
  51521. initialDistance = 0;
  51522. };
  51523. this._onMouseMove = function (evt) {
  51524. if (!engine.isPointerLock) {
  51525. return;
  51526. }
  51527. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  51528. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  51529. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  51530. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  51531. if (!noPreventDefault) {
  51532. evt.preventDefault();
  51533. }
  51534. };
  51535. this._onGestureStart = function (e) {
  51536. if (window.MSGesture === undefined) {
  51537. return;
  51538. }
  51539. if (!_this._MSGestureHandler) {
  51540. _this._MSGestureHandler = new MSGesture();
  51541. _this._MSGestureHandler.target = element;
  51542. }
  51543. _this._MSGestureHandler.addPointer(e.pointerId);
  51544. };
  51545. this._onGesture = function (e) {
  51546. _this.camera.radius *= e.scale;
  51547. if (e.preventDefault) {
  51548. if (!noPreventDefault) {
  51549. e.stopPropagation();
  51550. e.preventDefault();
  51551. }
  51552. }
  51553. };
  51554. element.addEventListener("mousemove", this._onMouseMove, false);
  51555. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  51556. element.addEventListener("MSGestureChange", this._onGesture, false);
  51557. BABYLON.Tools.RegisterTopRootEvents([
  51558. { name: "blur", handler: this._onLostFocus }
  51559. ]);
  51560. };
  51561. /**
  51562. * Detach the current controls from the specified dom element.
  51563. * @param element Defines the element to stop listening the inputs from
  51564. */
  51565. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  51566. if (this._onLostFocus) {
  51567. BABYLON.Tools.UnregisterTopRootEvents([
  51568. { name: "blur", handler: this._onLostFocus }
  51569. ]);
  51570. }
  51571. if (element && this._observer) {
  51572. this.camera.getScene().onPointerObservable.remove(this._observer);
  51573. this._observer = null;
  51574. if (this._onContextMenu) {
  51575. element.removeEventListener("contextmenu", this._onContextMenu);
  51576. }
  51577. if (this._onMouseMove) {
  51578. element.removeEventListener("mousemove", this._onMouseMove);
  51579. }
  51580. if (this._onGestureStart) {
  51581. element.removeEventListener("MSPointerDown", this._onGestureStart);
  51582. }
  51583. if (this._onGesture) {
  51584. element.removeEventListener("MSGestureChange", this._onGesture);
  51585. }
  51586. this._isPanClick = false;
  51587. this.pinchInwards = true;
  51588. this._onMouseMove = null;
  51589. this._onGestureStart = null;
  51590. this._onGesture = null;
  51591. this._MSGestureHandler = null;
  51592. this._onLostFocus = null;
  51593. this._onContextMenu = null;
  51594. }
  51595. };
  51596. /**
  51597. * Gets the class name of the current intput.
  51598. * @returns the class name
  51599. */
  51600. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  51601. return "ArcRotateCameraPointersInput";
  51602. };
  51603. /**
  51604. * Get the friendly name associated with the input class.
  51605. * @returns the input friendly name
  51606. */
  51607. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  51608. return "pointers";
  51609. };
  51610. __decorate([
  51611. BABYLON.serialize()
  51612. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  51613. __decorate([
  51614. BABYLON.serialize()
  51615. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  51616. __decorate([
  51617. BABYLON.serialize()
  51618. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  51619. __decorate([
  51620. BABYLON.serialize()
  51621. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  51622. __decorate([
  51623. BABYLON.serialize()
  51624. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  51625. __decorate([
  51626. BABYLON.serialize()
  51627. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  51628. __decorate([
  51629. BABYLON.serialize()
  51630. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  51631. __decorate([
  51632. BABYLON.serialize()
  51633. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  51634. return ArcRotateCameraPointersInput;
  51635. }());
  51636. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  51637. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  51638. })(BABYLON || (BABYLON = {}));
  51639. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  51640. var BABYLON;
  51641. (function (BABYLON) {
  51642. /**
  51643. * Default Inputs manager for the ArcRotateCamera.
  51644. * It groups all the default supported inputs for ease of use.
  51645. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  51646. */
  51647. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  51648. __extends(ArcRotateCameraInputsManager, _super);
  51649. /**
  51650. * Instantiates a new ArcRotateCameraInputsManager.
  51651. * @param camera Defines the camera the inputs belong to
  51652. */
  51653. function ArcRotateCameraInputsManager(camera) {
  51654. return _super.call(this, camera) || this;
  51655. }
  51656. /**
  51657. * Add mouse wheel input support to the input manager.
  51658. * @returns the current input manager
  51659. */
  51660. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  51661. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  51662. return this;
  51663. };
  51664. /**
  51665. * Add pointers input support to the input manager.
  51666. * @returns the current input manager
  51667. */
  51668. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  51669. this.add(new BABYLON.ArcRotateCameraPointersInput());
  51670. return this;
  51671. };
  51672. /**
  51673. * Add keyboard input support to the input manager.
  51674. * @returns the current input manager
  51675. */
  51676. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  51677. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  51678. return this;
  51679. };
  51680. /**
  51681. * Add orientation input support to the input manager.
  51682. * @returns the current input manager
  51683. */
  51684. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  51685. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  51686. return this;
  51687. };
  51688. return ArcRotateCameraInputsManager;
  51689. }(BABYLON.CameraInputsManager));
  51690. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  51691. })(BABYLON || (BABYLON = {}));
  51692. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  51693. var BABYLON;
  51694. (function (BABYLON) {
  51695. BABYLON.Node.AddNodeConstructor("ArcRotateCamera", function (name, scene) {
  51696. return function () { return new ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  51697. });
  51698. /**
  51699. * This represents an orbital type of camera.
  51700. *
  51701. * 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.
  51702. * 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.
  51703. * @see http://doc.babylonjs.com/babylon101/cameras#arc-rotate-camera
  51704. */
  51705. var ArcRotateCamera = /** @class */ (function (_super) {
  51706. __extends(ArcRotateCamera, _super);
  51707. /**
  51708. * Instantiates a new ArcRotateCamera in a given scene
  51709. * @param name Defines the name of the camera
  51710. * @param alpha Defines the camera rotation along the logitudinal axis
  51711. * @param beta Defines the camera rotation along the latitudinal axis
  51712. * @param radius Defines the camera distance from its target
  51713. * @param target Defines the camera target
  51714. * @param scene Defines the scene the camera belongs to
  51715. * @param setActiveOnSceneIfNoneActive Defines wheter the camera should be marked as active if not other active cameras have been defined
  51716. */
  51717. function ArcRotateCamera(name, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive) {
  51718. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  51719. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene, setActiveOnSceneIfNoneActive) || this;
  51720. /**
  51721. * Current inertia value on the longitudinal axis.
  51722. * The bigger this number the longer it will take for the camera to stop.
  51723. */
  51724. _this.inertialAlphaOffset = 0;
  51725. /**
  51726. * Current inertia value on the latitudinal axis.
  51727. * The bigger this number the longer it will take for the camera to stop.
  51728. */
  51729. _this.inertialBetaOffset = 0;
  51730. /**
  51731. * Current inertia value on the radius axis.
  51732. * The bigger this number the longer it will take for the camera to stop.
  51733. */
  51734. _this.inertialRadiusOffset = 0;
  51735. /**
  51736. * Minimum allowed angle on the longitudinal axis.
  51737. * This can help limiting how the Camera is able to move in the scene.
  51738. */
  51739. _this.lowerAlphaLimit = null;
  51740. /**
  51741. * Maximum allowed angle on the longitudinal axis.
  51742. * This can help limiting how the Camera is able to move in the scene.
  51743. */
  51744. _this.upperAlphaLimit = null;
  51745. /**
  51746. * Minimum allowed angle on the latitudinal axis.
  51747. * This can help limiting how the Camera is able to move in the scene.
  51748. */
  51749. _this.lowerBetaLimit = 0.01;
  51750. /**
  51751. * Maximum allowed angle on the latitudinal axis.
  51752. * This can help limiting how the Camera is able to move in the scene.
  51753. */
  51754. _this.upperBetaLimit = Math.PI;
  51755. /**
  51756. * Minimum allowed distance of the camera to the target (The camera can not get closer).
  51757. * This can help limiting how the Camera is able to move in the scene.
  51758. */
  51759. _this.lowerRadiusLimit = null;
  51760. /**
  51761. * Maximum allowed distance of the camera to the target (The camera can not get further).
  51762. * This can help limiting how the Camera is able to move in the scene.
  51763. */
  51764. _this.upperRadiusLimit = null;
  51765. /**
  51766. * Defines the current inertia value used during panning of the camera along the X axis.
  51767. */
  51768. _this.inertialPanningX = 0;
  51769. /**
  51770. * Defines the current inertia value used during panning of the camera along the Y axis.
  51771. */
  51772. _this.inertialPanningY = 0;
  51773. /**
  51774. * Defines the distance used to consider the camera in pan mode vs pinch/zoom.
  51775. * Basically if your fingers moves away from more than this distance you will be considered
  51776. * in pinch mode.
  51777. */
  51778. _this.pinchToPanMaxDistance = 20;
  51779. /**
  51780. * Defines the maximum distance the camera can pan.
  51781. * This could help keeping the cammera always in your scene.
  51782. */
  51783. _this.panningDistanceLimit = null;
  51784. /**
  51785. * Defines the target of the camera before paning.
  51786. */
  51787. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  51788. /**
  51789. * Defines the value of the inertia used during panning.
  51790. * 0 would mean stop inertia and one would mean no decelleration at all.
  51791. */
  51792. _this.panningInertia = 0.9;
  51793. //-- end properties for backward compatibility for inputs
  51794. /**
  51795. * Defines how much the radius should be scaled while zomming on a particular mesh (through the zoomOn function)
  51796. */
  51797. _this.zoomOnFactor = 1;
  51798. /**
  51799. * Defines a screen offset for the camera position.
  51800. */
  51801. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  51802. /**
  51803. * Allows the camera to be completely reversed.
  51804. * If false the camera can not arrive upside down.
  51805. */
  51806. _this.allowUpsideDown = true;
  51807. /**
  51808. * Define if double tap/click is used to restore the previously saved state of the camera.
  51809. */
  51810. _this.useInputToRestoreState = true;
  51811. /** @hidden */
  51812. _this._viewMatrix = new BABYLON.Matrix();
  51813. /**
  51814. * Defines the allowed panning axis.
  51815. */
  51816. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  51817. /**
  51818. * Observable triggered when the mesh target has been changed on the camera.
  51819. */
  51820. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  51821. /**
  51822. * Defines whether the camera should check collision with the objects oh the scene.
  51823. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#how-can-i-do-this
  51824. */
  51825. _this.checkCollisions = false;
  51826. /**
  51827. * Defines the collision radius of the camera.
  51828. * This simulates a sphere around the camera.
  51829. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#arcrotatecamera
  51830. */
  51831. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  51832. _this._previousPosition = BABYLON.Vector3.Zero();
  51833. _this._collisionVelocity = BABYLON.Vector3.Zero();
  51834. _this._newPosition = BABYLON.Vector3.Zero();
  51835. _this._computationVector = BABYLON.Vector3.Zero();
  51836. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  51837. if (collidedMesh === void 0) { collidedMesh = null; }
  51838. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  51839. newPosition.multiplyInPlace(_this._collider._radius);
  51840. }
  51841. if (!collidedMesh) {
  51842. _this._previousPosition.copyFrom(_this.position);
  51843. }
  51844. else {
  51845. _this.setPosition(newPosition);
  51846. if (_this.onCollide) {
  51847. _this.onCollide(collidedMesh);
  51848. }
  51849. }
  51850. // Recompute because of constraints
  51851. var cosa = Math.cos(_this.alpha);
  51852. var sina = Math.sin(_this.alpha);
  51853. var cosb = Math.cos(_this.beta);
  51854. var sinb = Math.sin(_this.beta);
  51855. if (sinb === 0) {
  51856. sinb = 0.0001;
  51857. }
  51858. var target = _this._getTargetPosition();
  51859. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  51860. target.addToRef(_this._computationVector, _this._newPosition);
  51861. _this.position.copyFrom(_this._newPosition);
  51862. var up = _this.upVector;
  51863. if (_this.allowUpsideDown && _this.beta < 0) {
  51864. up = up.clone();
  51865. up = up.negate();
  51866. }
  51867. _this._computeViewMatrix(_this.position, target, up);
  51868. _this._viewMatrix.addAtIndex(12, _this.targetScreenOffset.x);
  51869. _this._viewMatrix.addAtIndex(13, _this.targetScreenOffset.y);
  51870. _this._collisionTriggered = false;
  51871. };
  51872. _this._target = BABYLON.Vector3.Zero();
  51873. if (target) {
  51874. _this.setTarget(target);
  51875. }
  51876. _this.alpha = alpha;
  51877. _this.beta = beta;
  51878. _this.radius = radius;
  51879. _this.getViewMatrix();
  51880. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  51881. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  51882. return _this;
  51883. }
  51884. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  51885. /**
  51886. * Defines the target point of the camera.
  51887. * The camera looks towards it form the radius distance.
  51888. */
  51889. get: function () {
  51890. return this._target;
  51891. },
  51892. set: function (value) {
  51893. this.setTarget(value);
  51894. },
  51895. enumerable: true,
  51896. configurable: true
  51897. });
  51898. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  51899. //-- begin properties for backward compatibility for inputs
  51900. /**
  51901. * Gets or Set the pointer angular sensibility along the X axis or how fast is the camera rotating.
  51902. */
  51903. get: function () {
  51904. var pointers = this.inputs.attached["pointers"];
  51905. if (pointers) {
  51906. return pointers.angularSensibilityX;
  51907. }
  51908. return 0;
  51909. },
  51910. set: function (value) {
  51911. var pointers = this.inputs.attached["pointers"];
  51912. if (pointers) {
  51913. pointers.angularSensibilityX = value;
  51914. }
  51915. },
  51916. enumerable: true,
  51917. configurable: true
  51918. });
  51919. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  51920. /**
  51921. * Gets or Set the pointer angular sensibility along the Y axis or how fast is the camera rotating.
  51922. */
  51923. get: function () {
  51924. var pointers = this.inputs.attached["pointers"];
  51925. if (pointers) {
  51926. return pointers.angularSensibilityY;
  51927. }
  51928. return 0;
  51929. },
  51930. set: function (value) {
  51931. var pointers = this.inputs.attached["pointers"];
  51932. if (pointers) {
  51933. pointers.angularSensibilityY = value;
  51934. }
  51935. },
  51936. enumerable: true,
  51937. configurable: true
  51938. });
  51939. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  51940. /**
  51941. * Gets or Set the pointer pinch precision or how fast is the camera zooming.
  51942. */
  51943. get: function () {
  51944. var pointers = this.inputs.attached["pointers"];
  51945. if (pointers) {
  51946. return pointers.pinchPrecision;
  51947. }
  51948. return 0;
  51949. },
  51950. set: function (value) {
  51951. var pointers = this.inputs.attached["pointers"];
  51952. if (pointers) {
  51953. pointers.pinchPrecision = value;
  51954. }
  51955. },
  51956. enumerable: true,
  51957. configurable: true
  51958. });
  51959. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  51960. /**
  51961. * Gets or Set the pointer pinch delta percentage or how fast is the camera zooming.
  51962. * It will be used instead of pinchDeltaPrecision if different from 0.
  51963. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  51964. */
  51965. get: function () {
  51966. var pointers = this.inputs.attached["pointers"];
  51967. if (pointers) {
  51968. return pointers.pinchDeltaPercentage;
  51969. }
  51970. return 0;
  51971. },
  51972. set: function (value) {
  51973. var pointers = this.inputs.attached["pointers"];
  51974. if (pointers) {
  51975. pointers.pinchDeltaPercentage = value;
  51976. }
  51977. },
  51978. enumerable: true,
  51979. configurable: true
  51980. });
  51981. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  51982. /**
  51983. * Gets or Set the pointer panning sensibility or how fast is the camera moving.
  51984. */
  51985. get: function () {
  51986. var pointers = this.inputs.attached["pointers"];
  51987. if (pointers) {
  51988. return pointers.panningSensibility;
  51989. }
  51990. return 0;
  51991. },
  51992. set: function (value) {
  51993. var pointers = this.inputs.attached["pointers"];
  51994. if (pointers) {
  51995. pointers.panningSensibility = value;
  51996. }
  51997. },
  51998. enumerable: true,
  51999. configurable: true
  52000. });
  52001. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  52002. /**
  52003. * Gets or Set the list of keyboard keys used to control beta angle in a positive direction.
  52004. */
  52005. get: function () {
  52006. var keyboard = this.inputs.attached["keyboard"];
  52007. if (keyboard) {
  52008. return keyboard.keysUp;
  52009. }
  52010. return [];
  52011. },
  52012. set: function (value) {
  52013. var keyboard = this.inputs.attached["keyboard"];
  52014. if (keyboard) {
  52015. keyboard.keysUp = value;
  52016. }
  52017. },
  52018. enumerable: true,
  52019. configurable: true
  52020. });
  52021. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  52022. /**
  52023. * Gets or Set the list of keyboard keys used to control beta angle in a negative direction.
  52024. */
  52025. get: function () {
  52026. var keyboard = this.inputs.attached["keyboard"];
  52027. if (keyboard) {
  52028. return keyboard.keysDown;
  52029. }
  52030. return [];
  52031. },
  52032. set: function (value) {
  52033. var keyboard = this.inputs.attached["keyboard"];
  52034. if (keyboard) {
  52035. keyboard.keysDown = value;
  52036. }
  52037. },
  52038. enumerable: true,
  52039. configurable: true
  52040. });
  52041. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  52042. /**
  52043. * Gets or Set the list of keyboard keys used to control alpha angle in a negative direction.
  52044. */
  52045. get: function () {
  52046. var keyboard = this.inputs.attached["keyboard"];
  52047. if (keyboard) {
  52048. return keyboard.keysLeft;
  52049. }
  52050. return [];
  52051. },
  52052. set: function (value) {
  52053. var keyboard = this.inputs.attached["keyboard"];
  52054. if (keyboard) {
  52055. keyboard.keysLeft = value;
  52056. }
  52057. },
  52058. enumerable: true,
  52059. configurable: true
  52060. });
  52061. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  52062. /**
  52063. * Gets or Set the list of keyboard keys used to control alpha angle in a positive direction.
  52064. */
  52065. get: function () {
  52066. var keyboard = this.inputs.attached["keyboard"];
  52067. if (keyboard) {
  52068. return keyboard.keysRight;
  52069. }
  52070. return [];
  52071. },
  52072. set: function (value) {
  52073. var keyboard = this.inputs.attached["keyboard"];
  52074. if (keyboard) {
  52075. keyboard.keysRight = value;
  52076. }
  52077. },
  52078. enumerable: true,
  52079. configurable: true
  52080. });
  52081. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  52082. /**
  52083. * Gets or Set the mouse wheel precision or how fast is the camera zooming.
  52084. */
  52085. get: function () {
  52086. var mousewheel = this.inputs.attached["mousewheel"];
  52087. if (mousewheel) {
  52088. return mousewheel.wheelPrecision;
  52089. }
  52090. return 0;
  52091. },
  52092. set: function (value) {
  52093. var mousewheel = this.inputs.attached["mousewheel"];
  52094. if (mousewheel) {
  52095. mousewheel.wheelPrecision = value;
  52096. }
  52097. },
  52098. enumerable: true,
  52099. configurable: true
  52100. });
  52101. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  52102. /**
  52103. * Gets or Set the mouse wheel delta percentage or how fast is the camera zooming.
  52104. * It will be used instead of pinchDeltaPrecision if different from 0.
  52105. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  52106. */
  52107. get: function () {
  52108. var mousewheel = this.inputs.attached["mousewheel"];
  52109. if (mousewheel) {
  52110. return mousewheel.wheelDeltaPercentage;
  52111. }
  52112. return 0;
  52113. },
  52114. set: function (value) {
  52115. var mousewheel = this.inputs.attached["mousewheel"];
  52116. if (mousewheel) {
  52117. mousewheel.wheelDeltaPercentage = value;
  52118. }
  52119. },
  52120. enumerable: true,
  52121. configurable: true
  52122. });
  52123. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  52124. /**
  52125. * Gets the bouncing behavior of the camera if it has been enabled.
  52126. * @see http://doc.babylonjs.com/how_to/camera_behaviors#bouncing-behavior
  52127. */
  52128. get: function () {
  52129. return this._bouncingBehavior;
  52130. },
  52131. enumerable: true,
  52132. configurable: true
  52133. });
  52134. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  52135. /**
  52136. * Defines if the bouncing behavior of the camera is enabled on the camera.
  52137. * @see http://doc.babylonjs.com/how_to/camera_behaviors#bouncing-behavior
  52138. */
  52139. get: function () {
  52140. return this._bouncingBehavior != null;
  52141. },
  52142. set: function (value) {
  52143. if (value === this.useBouncingBehavior) {
  52144. return;
  52145. }
  52146. if (value) {
  52147. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  52148. this.addBehavior(this._bouncingBehavior);
  52149. }
  52150. else if (this._bouncingBehavior) {
  52151. this.removeBehavior(this._bouncingBehavior);
  52152. this._bouncingBehavior = null;
  52153. }
  52154. },
  52155. enumerable: true,
  52156. configurable: true
  52157. });
  52158. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  52159. /**
  52160. * Gets the framing behavior of the camera if it has been enabled.
  52161. * @see http://doc.babylonjs.com/how_to/camera_behaviors#framing-behavior
  52162. */
  52163. get: function () {
  52164. return this._framingBehavior;
  52165. },
  52166. enumerable: true,
  52167. configurable: true
  52168. });
  52169. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  52170. /**
  52171. * Defines if the framing behavior of the camera is enabled on the camera.
  52172. * @see http://doc.babylonjs.com/how_to/camera_behaviors#framing-behavior
  52173. */
  52174. get: function () {
  52175. return this._framingBehavior != null;
  52176. },
  52177. set: function (value) {
  52178. if (value === this.useFramingBehavior) {
  52179. return;
  52180. }
  52181. if (value) {
  52182. this._framingBehavior = new BABYLON.FramingBehavior();
  52183. this.addBehavior(this._framingBehavior);
  52184. }
  52185. else if (this._framingBehavior) {
  52186. this.removeBehavior(this._framingBehavior);
  52187. this._framingBehavior = null;
  52188. }
  52189. },
  52190. enumerable: true,
  52191. configurable: true
  52192. });
  52193. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  52194. /**
  52195. * Gets the auto rotation behavior of the camera if it has been enabled.
  52196. * @see http://doc.babylonjs.com/how_to/camera_behaviors#autorotation-behavior
  52197. */
  52198. get: function () {
  52199. return this._autoRotationBehavior;
  52200. },
  52201. enumerable: true,
  52202. configurable: true
  52203. });
  52204. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  52205. /**
  52206. * Defines if the auto rotation behavior of the camera is enabled on the camera.
  52207. * @see http://doc.babylonjs.com/how_to/camera_behaviors#autorotation-behavior
  52208. */
  52209. get: function () {
  52210. return this._autoRotationBehavior != null;
  52211. },
  52212. set: function (value) {
  52213. if (value === this.useAutoRotationBehavior) {
  52214. return;
  52215. }
  52216. if (value) {
  52217. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  52218. this.addBehavior(this._autoRotationBehavior);
  52219. }
  52220. else if (this._autoRotationBehavior) {
  52221. this.removeBehavior(this._autoRotationBehavior);
  52222. this._autoRotationBehavior = null;
  52223. }
  52224. },
  52225. enumerable: true,
  52226. configurable: true
  52227. });
  52228. // Cache
  52229. /** @hidden */
  52230. ArcRotateCamera.prototype._initCache = function () {
  52231. _super.prototype._initCache.call(this);
  52232. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  52233. this._cache.alpha = undefined;
  52234. this._cache.beta = undefined;
  52235. this._cache.radius = undefined;
  52236. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  52237. };
  52238. /** @hidden */
  52239. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  52240. if (!ignoreParentClass) {
  52241. _super.prototype._updateCache.call(this);
  52242. }
  52243. this._cache._target.copyFrom(this._getTargetPosition());
  52244. this._cache.alpha = this.alpha;
  52245. this._cache.beta = this.beta;
  52246. this._cache.radius = this.radius;
  52247. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  52248. };
  52249. ArcRotateCamera.prototype._getTargetPosition = function () {
  52250. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  52251. var pos = this._targetHost.absolutePosition;
  52252. if (this._targetBoundingCenter) {
  52253. pos.addToRef(this._targetBoundingCenter, this._target);
  52254. }
  52255. else {
  52256. this._target.copyFrom(pos);
  52257. }
  52258. }
  52259. var lockedTargetPosition = this._getLockedTargetPosition();
  52260. if (lockedTargetPosition) {
  52261. return lockedTargetPosition;
  52262. }
  52263. return this._target;
  52264. };
  52265. /**
  52266. * Stores the current state of the camera (alpha, beta, radius and target)
  52267. * @returns the camera itself
  52268. */
  52269. ArcRotateCamera.prototype.storeState = function () {
  52270. this._storedAlpha = this.alpha;
  52271. this._storedBeta = this.beta;
  52272. this._storedRadius = this.radius;
  52273. this._storedTarget = this._getTargetPosition().clone();
  52274. return _super.prototype.storeState.call(this);
  52275. };
  52276. /**
  52277. * @hidden
  52278. * Restored camera state. You must call storeState() first
  52279. */
  52280. ArcRotateCamera.prototype._restoreStateValues = function () {
  52281. if (!_super.prototype._restoreStateValues.call(this)) {
  52282. return false;
  52283. }
  52284. this.alpha = this._storedAlpha;
  52285. this.beta = this._storedBeta;
  52286. this.radius = this._storedRadius;
  52287. this.setTarget(this._storedTarget.clone());
  52288. this.inertialAlphaOffset = 0;
  52289. this.inertialBetaOffset = 0;
  52290. this.inertialRadiusOffset = 0;
  52291. this.inertialPanningX = 0;
  52292. this.inertialPanningY = 0;
  52293. return true;
  52294. };
  52295. // Synchronized
  52296. /** @hidden */
  52297. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  52298. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  52299. return false;
  52300. }
  52301. return this._cache._target.equals(this._getTargetPosition())
  52302. && this._cache.alpha === this.alpha
  52303. && this._cache.beta === this.beta
  52304. && this._cache.radius === this.radius
  52305. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  52306. };
  52307. /**
  52308. * Attached controls to the current camera.
  52309. * @param element Defines the element the controls should be listened from
  52310. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  52311. * @param useCtrlForPanning Defines whether ctrl is used for paning within the controls
  52312. * @param panningMouseButton Defines whether panning is allowed through mouse click button
  52313. */
  52314. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  52315. var _this = this;
  52316. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  52317. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  52318. this._useCtrlForPanning = useCtrlForPanning;
  52319. this._panningMouseButton = panningMouseButton;
  52320. this.inputs.attachElement(element, noPreventDefault);
  52321. this._reset = function () {
  52322. _this.inertialAlphaOffset = 0;
  52323. _this.inertialBetaOffset = 0;
  52324. _this.inertialRadiusOffset = 0;
  52325. _this.inertialPanningX = 0;
  52326. _this.inertialPanningY = 0;
  52327. };
  52328. };
  52329. /**
  52330. * Detach the current controls from the camera.
  52331. * The camera will stop reacting to inputs.
  52332. * @param element Defines the element to stop listening the inputs from
  52333. */
  52334. ArcRotateCamera.prototype.detachControl = function (element) {
  52335. this.inputs.detachElement(element);
  52336. if (this._reset) {
  52337. this._reset();
  52338. }
  52339. };
  52340. /** @hidden */
  52341. ArcRotateCamera.prototype._checkInputs = function () {
  52342. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  52343. if (this._collisionTriggered) {
  52344. return;
  52345. }
  52346. this.inputs.checkInputs();
  52347. // Inertia
  52348. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  52349. var inertialAlphaOffset = this.inertialAlphaOffset;
  52350. if (this.beta <= 0) {
  52351. inertialAlphaOffset *= -1;
  52352. }
  52353. if (this.getScene().useRightHandedSystem) {
  52354. inertialAlphaOffset *= -1;
  52355. }
  52356. if (this.parent && this.parent._getWorldMatrixDeterminant() < 0) {
  52357. inertialAlphaOffset *= -1;
  52358. }
  52359. this.alpha += inertialAlphaOffset;
  52360. this.beta += this.inertialBetaOffset;
  52361. this.radius -= this.inertialRadiusOffset;
  52362. this.inertialAlphaOffset *= this.inertia;
  52363. this.inertialBetaOffset *= this.inertia;
  52364. this.inertialRadiusOffset *= this.inertia;
  52365. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon) {
  52366. this.inertialAlphaOffset = 0;
  52367. }
  52368. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon) {
  52369. this.inertialBetaOffset = 0;
  52370. }
  52371. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon) {
  52372. this.inertialRadiusOffset = 0;
  52373. }
  52374. }
  52375. // Panning inertia
  52376. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  52377. if (!this._localDirection) {
  52378. this._localDirection = BABYLON.Vector3.Zero();
  52379. this._transformedDirection = BABYLON.Vector3.Zero();
  52380. }
  52381. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  52382. this._localDirection.multiplyInPlace(this.panningAxis);
  52383. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  52384. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  52385. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  52386. if (!this.panningAxis.y) {
  52387. this._transformedDirection.y = 0;
  52388. }
  52389. if (!this._targetHost) {
  52390. if (this.panningDistanceLimit) {
  52391. this._transformedDirection.addInPlace(this._target);
  52392. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  52393. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  52394. this._target.copyFrom(this._transformedDirection);
  52395. }
  52396. }
  52397. else {
  52398. this._target.addInPlace(this._transformedDirection);
  52399. }
  52400. }
  52401. this.inertialPanningX *= this.panningInertia;
  52402. this.inertialPanningY *= this.panningInertia;
  52403. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon) {
  52404. this.inertialPanningX = 0;
  52405. }
  52406. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon) {
  52407. this.inertialPanningY = 0;
  52408. }
  52409. }
  52410. // Limits
  52411. this._checkLimits();
  52412. _super.prototype._checkInputs.call(this);
  52413. };
  52414. ArcRotateCamera.prototype._checkLimits = function () {
  52415. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  52416. if (this.allowUpsideDown && this.beta > Math.PI) {
  52417. this.beta = this.beta - (2 * Math.PI);
  52418. }
  52419. }
  52420. else {
  52421. if (this.beta < this.lowerBetaLimit) {
  52422. this.beta = this.lowerBetaLimit;
  52423. }
  52424. }
  52425. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  52426. if (this.allowUpsideDown && this.beta < -Math.PI) {
  52427. this.beta = this.beta + (2 * Math.PI);
  52428. }
  52429. }
  52430. else {
  52431. if (this.beta > this.upperBetaLimit) {
  52432. this.beta = this.upperBetaLimit;
  52433. }
  52434. }
  52435. if (this.lowerAlphaLimit !== null && this.alpha < this.lowerAlphaLimit) {
  52436. this.alpha = this.lowerAlphaLimit;
  52437. }
  52438. if (this.upperAlphaLimit !== null && this.alpha > this.upperAlphaLimit) {
  52439. this.alpha = this.upperAlphaLimit;
  52440. }
  52441. if (this.lowerRadiusLimit !== null && this.radius < this.lowerRadiusLimit) {
  52442. this.radius = this.lowerRadiusLimit;
  52443. this.inertialRadiusOffset = 0;
  52444. }
  52445. if (this.upperRadiusLimit !== null && this.radius > this.upperRadiusLimit) {
  52446. this.radius = this.upperRadiusLimit;
  52447. this.inertialRadiusOffset = 0;
  52448. }
  52449. };
  52450. /**
  52451. * Rebuilds angles (alpha, beta) and radius from the give position and target.
  52452. */
  52453. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  52454. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  52455. this.radius = this._computationVector.length();
  52456. if (this.radius === 0) {
  52457. this.radius = 0.0001; // Just to avoid division by zero
  52458. }
  52459. // Alpha
  52460. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  52461. if (this._computationVector.z < 0) {
  52462. this.alpha = 2 * Math.PI - this.alpha;
  52463. }
  52464. // Beta
  52465. this.beta = Math.acos(this._computationVector.y / this.radius);
  52466. this._checkLimits();
  52467. };
  52468. /**
  52469. * Use a position to define the current camera related information like aplha, beta and radius
  52470. * @param position Defines the position to set the camera at
  52471. */
  52472. ArcRotateCamera.prototype.setPosition = function (position) {
  52473. if (this.position.equals(position)) {
  52474. return;
  52475. }
  52476. this.position.copyFrom(position);
  52477. this.rebuildAnglesAndRadius();
  52478. };
  52479. /**
  52480. * Defines the target the camera should look at.
  52481. * This will automatically adapt alpha beta and radius to fit within the new target.
  52482. * @param target Defines the new target as a Vector or a mesh
  52483. * @param toBoundingCenter In case of a mesh target, defines wether to target the mesh position or its bounding information center
  52484. * @param allowSamePosition If false, prevents reapplying the new computed position if it is identical to the current one (optim)
  52485. */
  52486. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  52487. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  52488. if (allowSamePosition === void 0) { allowSamePosition = false; }
  52489. if (target.getBoundingInfo) {
  52490. if (toBoundingCenter) {
  52491. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  52492. }
  52493. else {
  52494. this._targetBoundingCenter = null;
  52495. }
  52496. this._targetHost = target;
  52497. this._target = this._getTargetPosition();
  52498. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  52499. }
  52500. else {
  52501. var newTarget = target;
  52502. var currentTarget = this._getTargetPosition();
  52503. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  52504. return;
  52505. }
  52506. this._targetHost = null;
  52507. this._target = newTarget;
  52508. this._targetBoundingCenter = null;
  52509. this.onMeshTargetChangedObservable.notifyObservers(null);
  52510. }
  52511. this.rebuildAnglesAndRadius();
  52512. };
  52513. /** @hidden */
  52514. ArcRotateCamera.prototype._getViewMatrix = function () {
  52515. // Compute
  52516. var cosa = Math.cos(this.alpha);
  52517. var sina = Math.sin(this.alpha);
  52518. var cosb = Math.cos(this.beta);
  52519. var sinb = Math.sin(this.beta);
  52520. if (sinb === 0) {
  52521. sinb = 0.0001;
  52522. }
  52523. var target = this._getTargetPosition();
  52524. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  52525. // Rotate according to up vector
  52526. if (this.upVector.x !== 0 || this.upVector.y !== 1.0 || this.upVector.z !== 0) {
  52527. if (!this._tempAxisVector) {
  52528. this._tempAxisVector = new BABYLON.Vector3();
  52529. this._tempAxisRotationMatrix = new BABYLON.Matrix();
  52530. }
  52531. BABYLON.Vector3.CrossToRef(BABYLON.Vector3.Up(), this.upVector, this._tempAxisVector);
  52532. this._tempAxisVector.normalize();
  52533. var angle = Math.acos(BABYLON.Vector3.Dot(BABYLON.Vector3.UpReadOnly, this.upVector));
  52534. BABYLON.Matrix.RotationAxisToRef(this._tempAxisVector, angle, this._tempAxisRotationMatrix);
  52535. this._tempAxisVector.copyFrom(this._computationVector);
  52536. BABYLON.Vector3.TransformCoordinatesToRef(this._tempAxisVector, this._tempAxisRotationMatrix, this._computationVector);
  52537. }
  52538. target.addToRef(this._computationVector, this._newPosition);
  52539. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  52540. if (!this._collider) {
  52541. this._collider = new BABYLON.Collider();
  52542. }
  52543. this._collider._radius = this.collisionRadius;
  52544. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  52545. this._collisionTriggered = true;
  52546. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  52547. }
  52548. else {
  52549. this.position.copyFrom(this._newPosition);
  52550. var up = this.upVector;
  52551. if (this.allowUpsideDown && sinb < 0) {
  52552. up = up.clone();
  52553. up = up.negate();
  52554. }
  52555. this._computeViewMatrix(this.position, target, up);
  52556. this._viewMatrix.addAtIndex(12, this.targetScreenOffset.x);
  52557. this._viewMatrix.addAtIndex(13, this.targetScreenOffset.y);
  52558. }
  52559. this._currentTarget = target;
  52560. return this._viewMatrix;
  52561. };
  52562. /**
  52563. * Zooms on a mesh to be at the min distance where we could see it fully in the current viewport.
  52564. * @param meshes Defines the mesh to zoom on
  52565. * @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)
  52566. */
  52567. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  52568. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  52569. meshes = meshes || this.getScene().meshes;
  52570. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  52571. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  52572. this.radius = distance * this.zoomOnFactor;
  52573. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  52574. };
  52575. /**
  52576. * Focus on a mesh or a bounding box. This adapts the target and maxRadius if necessary but does not update the current radius.
  52577. * The target will be changed but the radius
  52578. * @param meshesOrMinMaxVectorAndDistance Defines the mesh or bounding info to focus on
  52579. * @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)
  52580. */
  52581. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  52582. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  52583. var meshesOrMinMaxVector;
  52584. var distance;
  52585. if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
  52586. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  52587. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  52588. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  52589. }
  52590. else { //minMaxVector and distance
  52591. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  52592. meshesOrMinMaxVector = minMaxVectorAndDistance;
  52593. distance = minMaxVectorAndDistance.distance;
  52594. }
  52595. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  52596. if (!doNotUpdateMaxZ) {
  52597. this.maxZ = distance * 2;
  52598. }
  52599. };
  52600. /**
  52601. * @override
  52602. * Override Camera.createRigCamera
  52603. */
  52604. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  52605. var alphaShift = 0;
  52606. switch (this.cameraRigMode) {
  52607. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  52608. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  52609. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  52610. case BABYLON.Camera.RIG_MODE_VR:
  52611. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  52612. break;
  52613. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  52614. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  52615. break;
  52616. }
  52617. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  52618. rigCam._cameraRigParams = {};
  52619. return rigCam;
  52620. };
  52621. /**
  52622. * @hidden
  52623. * @override
  52624. * Override Camera._updateRigCameras
  52625. */
  52626. ArcRotateCamera.prototype._updateRigCameras = function () {
  52627. var camLeft = this._rigCameras[0];
  52628. var camRight = this._rigCameras[1];
  52629. camLeft.beta = camRight.beta = this.beta;
  52630. switch (this.cameraRigMode) {
  52631. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  52632. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  52633. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  52634. case BABYLON.Camera.RIG_MODE_VR:
  52635. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  52636. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  52637. break;
  52638. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  52639. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  52640. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  52641. break;
  52642. }
  52643. _super.prototype._updateRigCameras.call(this);
  52644. };
  52645. /**
  52646. * Destroy the camera and release the current resources hold by it.
  52647. */
  52648. ArcRotateCamera.prototype.dispose = function () {
  52649. this.inputs.clear();
  52650. _super.prototype.dispose.call(this);
  52651. };
  52652. /**
  52653. * Gets the current object class name.
  52654. * @return the class name
  52655. */
  52656. ArcRotateCamera.prototype.getClassName = function () {
  52657. return "ArcRotateCamera";
  52658. };
  52659. __decorate([
  52660. BABYLON.serialize()
  52661. ], ArcRotateCamera.prototype, "alpha", void 0);
  52662. __decorate([
  52663. BABYLON.serialize()
  52664. ], ArcRotateCamera.prototype, "beta", void 0);
  52665. __decorate([
  52666. BABYLON.serialize()
  52667. ], ArcRotateCamera.prototype, "radius", void 0);
  52668. __decorate([
  52669. BABYLON.serializeAsVector3("target")
  52670. ], ArcRotateCamera.prototype, "_target", void 0);
  52671. __decorate([
  52672. BABYLON.serialize()
  52673. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  52674. __decorate([
  52675. BABYLON.serialize()
  52676. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  52677. __decorate([
  52678. BABYLON.serialize()
  52679. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  52680. __decorate([
  52681. BABYLON.serialize()
  52682. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  52683. __decorate([
  52684. BABYLON.serialize()
  52685. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  52686. __decorate([
  52687. BABYLON.serialize()
  52688. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  52689. __decorate([
  52690. BABYLON.serialize()
  52691. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  52692. __decorate([
  52693. BABYLON.serialize()
  52694. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  52695. __decorate([
  52696. BABYLON.serialize()
  52697. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  52698. __decorate([
  52699. BABYLON.serialize()
  52700. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  52701. __decorate([
  52702. BABYLON.serialize()
  52703. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  52704. __decorate([
  52705. BABYLON.serialize()
  52706. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  52707. __decorate([
  52708. BABYLON.serialize()
  52709. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  52710. __decorate([
  52711. BABYLON.serializeAsVector3()
  52712. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  52713. __decorate([
  52714. BABYLON.serialize()
  52715. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  52716. __decorate([
  52717. BABYLON.serialize()
  52718. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  52719. __decorate([
  52720. BABYLON.serialize()
  52721. ], ArcRotateCamera.prototype, "targetScreenOffset", void 0);
  52722. __decorate([
  52723. BABYLON.serialize()
  52724. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  52725. __decorate([
  52726. BABYLON.serialize()
  52727. ], ArcRotateCamera.prototype, "useInputToRestoreState", void 0);
  52728. return ArcRotateCamera;
  52729. }(BABYLON.TargetCamera));
  52730. BABYLON.ArcRotateCamera = ArcRotateCamera;
  52731. })(BABYLON || (BABYLON = {}));
  52732. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  52733. var BABYLON;
  52734. (function (BABYLON) {
  52735. BABYLON.Node.AddNodeConstructor("Light_Type_3", function (name, scene) {
  52736. return function () { return new HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  52737. });
  52738. /**
  52739. * The HemisphericLight simulates the ambient environment light,
  52740. * so the passed direction is the light reflection direction, not the incoming direction.
  52741. */
  52742. var HemisphericLight = /** @class */ (function (_super) {
  52743. __extends(HemisphericLight, _super);
  52744. /**
  52745. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  52746. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  52747. * The HemisphericLight can't cast shadows.
  52748. * Documentation : https://doc.babylonjs.com/babylon101/lights
  52749. * @param name The friendly name of the light
  52750. * @param direction The direction of the light reflection
  52751. * @param scene The scene the light belongs to
  52752. */
  52753. function HemisphericLight(name, direction, scene) {
  52754. var _this = _super.call(this, name, scene) || this;
  52755. /**
  52756. * The groundColor is the light in the opposite direction to the one specified during creation.
  52757. * 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.
  52758. */
  52759. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  52760. _this.direction = direction || BABYLON.Vector3.Up();
  52761. return _this;
  52762. }
  52763. HemisphericLight.prototype._buildUniformLayout = function () {
  52764. this._uniformBuffer.addUniform("vLightData", 4);
  52765. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  52766. this._uniformBuffer.addUniform("vLightSpecular", 3);
  52767. this._uniformBuffer.addUniform("vLightGround", 3);
  52768. this._uniformBuffer.addUniform("shadowsInfo", 3);
  52769. this._uniformBuffer.addUniform("depthValues", 2);
  52770. this._uniformBuffer.create();
  52771. };
  52772. /**
  52773. * Returns the string "HemisphericLight".
  52774. * @return The class name
  52775. */
  52776. HemisphericLight.prototype.getClassName = function () {
  52777. return "HemisphericLight";
  52778. };
  52779. /**
  52780. * Sets the HemisphericLight direction towards the passed target (Vector3).
  52781. * Returns the updated direction.
  52782. * @param target The target the direction should point to
  52783. * @return The computed direction
  52784. */
  52785. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  52786. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  52787. return this.direction;
  52788. };
  52789. /**
  52790. * Returns the shadow generator associated to the light.
  52791. * @returns Always null for hemispheric lights because it does not support shadows.
  52792. */
  52793. HemisphericLight.prototype.getShadowGenerator = function () {
  52794. return null;
  52795. };
  52796. /**
  52797. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  52798. * @param effect The effect to update
  52799. * @param lightIndex The index of the light in the effect to update
  52800. * @returns The hemispheric light
  52801. */
  52802. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  52803. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  52804. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  52805. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  52806. return this;
  52807. };
  52808. /**
  52809. * Computes the world matrix of the node
  52810. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  52811. * @param useWasUpdatedFlag defines a reserved property
  52812. * @returns the world matrix
  52813. */
  52814. HemisphericLight.prototype.computeWorldMatrix = function (force, useWasUpdatedFlag) {
  52815. if (!this._worldMatrix) {
  52816. this._worldMatrix = BABYLON.Matrix.Identity();
  52817. }
  52818. return this._worldMatrix;
  52819. };
  52820. /**
  52821. * Returns the integer 3.
  52822. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  52823. */
  52824. HemisphericLight.prototype.getTypeID = function () {
  52825. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  52826. };
  52827. /**
  52828. * Prepares the list of defines specific to the light type.
  52829. * @param defines the list of defines
  52830. * @param lightIndex defines the index of the light for the effect
  52831. */
  52832. HemisphericLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  52833. defines["HEMILIGHT" + lightIndex] = true;
  52834. };
  52835. __decorate([
  52836. BABYLON.serializeAsColor3()
  52837. ], HemisphericLight.prototype, "groundColor", void 0);
  52838. __decorate([
  52839. BABYLON.serializeAsVector3()
  52840. ], HemisphericLight.prototype, "direction", void 0);
  52841. return HemisphericLight;
  52842. }(BABYLON.Light));
  52843. BABYLON.HemisphericLight = HemisphericLight;
  52844. })(BABYLON || (BABYLON = {}));
  52845. //# sourceMappingURL=babylon.hemisphericLight.js.map
  52846. var BABYLON;
  52847. (function (BABYLON) {
  52848. /**
  52849. * Base implementation IShadowLight
  52850. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  52851. */
  52852. var ShadowLight = /** @class */ (function (_super) {
  52853. __extends(ShadowLight, _super);
  52854. function ShadowLight() {
  52855. var _this = _super !== null && _super.apply(this, arguments) || this;
  52856. _this._needProjectionMatrixCompute = true;
  52857. return _this;
  52858. }
  52859. ShadowLight.prototype._setPosition = function (value) {
  52860. this._position = value;
  52861. };
  52862. Object.defineProperty(ShadowLight.prototype, "position", {
  52863. /**
  52864. * Sets the position the shadow will be casted from. Also use as the light position for both
  52865. * point and spot lights.
  52866. */
  52867. get: function () {
  52868. return this._position;
  52869. },
  52870. /**
  52871. * Sets the position the shadow will be casted from. Also use as the light position for both
  52872. * point and spot lights.
  52873. */
  52874. set: function (value) {
  52875. this._setPosition(value);
  52876. },
  52877. enumerable: true,
  52878. configurable: true
  52879. });
  52880. ShadowLight.prototype._setDirection = function (value) {
  52881. this._direction = value;
  52882. };
  52883. Object.defineProperty(ShadowLight.prototype, "direction", {
  52884. /**
  52885. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  52886. * Also use as the light direction on spot and directional lights.
  52887. */
  52888. get: function () {
  52889. return this._direction;
  52890. },
  52891. /**
  52892. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  52893. * Also use as the light direction on spot and directional lights.
  52894. */
  52895. set: function (value) {
  52896. this._setDirection(value);
  52897. },
  52898. enumerable: true,
  52899. configurable: true
  52900. });
  52901. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  52902. /**
  52903. * Gets the shadow projection clipping minimum z value.
  52904. */
  52905. get: function () {
  52906. return this._shadowMinZ;
  52907. },
  52908. /**
  52909. * Sets the shadow projection clipping minimum z value.
  52910. */
  52911. set: function (value) {
  52912. this._shadowMinZ = value;
  52913. this.forceProjectionMatrixCompute();
  52914. },
  52915. enumerable: true,
  52916. configurable: true
  52917. });
  52918. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  52919. /**
  52920. * Sets the shadow projection clipping maximum z value.
  52921. */
  52922. get: function () {
  52923. return this._shadowMaxZ;
  52924. },
  52925. /**
  52926. * Gets the shadow projection clipping maximum z value.
  52927. */
  52928. set: function (value) {
  52929. this._shadowMaxZ = value;
  52930. this.forceProjectionMatrixCompute();
  52931. },
  52932. enumerable: true,
  52933. configurable: true
  52934. });
  52935. /**
  52936. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  52937. * @returns true if the information has been computed, false if it does not need to (no parenting)
  52938. */
  52939. ShadowLight.prototype.computeTransformedInformation = function () {
  52940. if (this.parent && this.parent.getWorldMatrix) {
  52941. if (!this.transformedPosition) {
  52942. this.transformedPosition = BABYLON.Vector3.Zero();
  52943. }
  52944. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  52945. // In case the direction is present.
  52946. if (this.direction) {
  52947. if (!this.transformedDirection) {
  52948. this.transformedDirection = BABYLON.Vector3.Zero();
  52949. }
  52950. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  52951. }
  52952. return true;
  52953. }
  52954. return false;
  52955. };
  52956. /**
  52957. * Return the depth scale used for the shadow map.
  52958. * @returns the depth scale.
  52959. */
  52960. ShadowLight.prototype.getDepthScale = function () {
  52961. return 50.0;
  52962. };
  52963. /**
  52964. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  52965. * @param faceIndex The index of the face we are computed the direction to generate shadow
  52966. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  52967. */
  52968. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  52969. return this.transformedDirection ? this.transformedDirection : this.direction;
  52970. };
  52971. /**
  52972. * Returns the ShadowLight absolute position in the World.
  52973. * @returns the position vector in world space
  52974. */
  52975. ShadowLight.prototype.getAbsolutePosition = function () {
  52976. return this.transformedPosition ? this.transformedPosition : this.position;
  52977. };
  52978. /**
  52979. * Sets the ShadowLight direction toward the passed target.
  52980. * @param target The point tot target in local space
  52981. * @returns the updated ShadowLight direction
  52982. */
  52983. ShadowLight.prototype.setDirectionToTarget = function (target) {
  52984. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  52985. return this.direction;
  52986. };
  52987. /**
  52988. * Returns the light rotation in euler definition.
  52989. * @returns the x y z rotation in local space.
  52990. */
  52991. ShadowLight.prototype.getRotation = function () {
  52992. this.direction.normalize();
  52993. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  52994. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  52995. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  52996. };
  52997. /**
  52998. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  52999. * @returns true if a cube texture needs to be use
  53000. */
  53001. ShadowLight.prototype.needCube = function () {
  53002. return false;
  53003. };
  53004. /**
  53005. * Detects if the projection matrix requires to be recomputed this frame.
  53006. * @returns true if it requires to be recomputed otherwise, false.
  53007. */
  53008. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  53009. return this._needProjectionMatrixCompute;
  53010. };
  53011. /**
  53012. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  53013. */
  53014. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  53015. this._needProjectionMatrixCompute = true;
  53016. };
  53017. /** @hidden */
  53018. ShadowLight.prototype._initCache = function () {
  53019. _super.prototype._initCache.call(this);
  53020. this._cache.position = BABYLON.Vector3.Zero();
  53021. };
  53022. /** @hidden */
  53023. ShadowLight.prototype._isSynchronized = function () {
  53024. if (!this._cache.position.equals(this.position)) {
  53025. return false;
  53026. }
  53027. return true;
  53028. };
  53029. /**
  53030. * Computes the world matrix of the node
  53031. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  53032. * @returns the world matrix
  53033. */
  53034. ShadowLight.prototype.computeWorldMatrix = function (force) {
  53035. if (!force && this.isSynchronized()) {
  53036. this._currentRenderId = this.getScene().getRenderId();
  53037. return this._worldMatrix;
  53038. }
  53039. this._updateCache();
  53040. this._cache.position.copyFrom(this.position);
  53041. if (!this._worldMatrix) {
  53042. this._worldMatrix = BABYLON.Matrix.Identity();
  53043. }
  53044. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  53045. if (this.parent && this.parent.getWorldMatrix) {
  53046. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  53047. this._markSyncedWithParent();
  53048. }
  53049. // Cache the determinant
  53050. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  53051. return this._worldMatrix;
  53052. };
  53053. /**
  53054. * Gets the minZ used for shadow according to both the scene and the light.
  53055. * @param activeCamera The camera we are returning the min for
  53056. * @returns the depth min z
  53057. */
  53058. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  53059. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  53060. };
  53061. /**
  53062. * Gets the maxZ used for shadow according to both the scene and the light.
  53063. * @param activeCamera The camera we are returning the max for
  53064. * @returns the depth max z
  53065. */
  53066. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  53067. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  53068. };
  53069. /**
  53070. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  53071. * @param matrix The materix to updated with the projection information
  53072. * @param viewMatrix The transform matrix of the light
  53073. * @param renderList The list of mesh to render in the map
  53074. * @returns The current light
  53075. */
  53076. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  53077. if (this.customProjectionMatrixBuilder) {
  53078. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  53079. }
  53080. else {
  53081. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  53082. }
  53083. return this;
  53084. };
  53085. __decorate([
  53086. BABYLON.serializeAsVector3()
  53087. ], ShadowLight.prototype, "position", null);
  53088. __decorate([
  53089. BABYLON.serializeAsVector3()
  53090. ], ShadowLight.prototype, "direction", null);
  53091. __decorate([
  53092. BABYLON.serialize()
  53093. ], ShadowLight.prototype, "shadowMinZ", null);
  53094. __decorate([
  53095. BABYLON.serialize()
  53096. ], ShadowLight.prototype, "shadowMaxZ", null);
  53097. return ShadowLight;
  53098. }(BABYLON.Light));
  53099. BABYLON.ShadowLight = ShadowLight;
  53100. })(BABYLON || (BABYLON = {}));
  53101. //# sourceMappingURL=babylon.shadowLight.js.map
  53102. var BABYLON;
  53103. (function (BABYLON) {
  53104. BABYLON.Node.AddNodeConstructor("Light_Type_0", function (name, scene) {
  53105. return function () { return new PointLight(name, BABYLON.Vector3.Zero(), scene); };
  53106. });
  53107. /**
  53108. * A point light is a light defined by an unique point in world space.
  53109. * The light is emitted in every direction from this point.
  53110. * A good example of a point light is a standard light bulb.
  53111. * Documentation: https://doc.babylonjs.com/babylon101/lights
  53112. */
  53113. var PointLight = /** @class */ (function (_super) {
  53114. __extends(PointLight, _super);
  53115. /**
  53116. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  53117. * A PointLight emits the light in every direction.
  53118. * It can cast shadows.
  53119. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  53120. * ```javascript
  53121. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  53122. * ```
  53123. * Documentation : https://doc.babylonjs.com/babylon101/lights
  53124. * @param name The light friendly name
  53125. * @param position The position of the point light in the scene
  53126. * @param scene The scene the lights belongs to
  53127. */
  53128. function PointLight(name, position, scene) {
  53129. var _this = _super.call(this, name, scene) || this;
  53130. _this._shadowAngle = Math.PI / 2;
  53131. _this.position = position;
  53132. return _this;
  53133. }
  53134. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  53135. /**
  53136. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  53137. * This specifies what angle the shadow will use to be created.
  53138. *
  53139. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  53140. */
  53141. get: function () {
  53142. return this._shadowAngle;
  53143. },
  53144. /**
  53145. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  53146. * This specifies what angle the shadow will use to be created.
  53147. *
  53148. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  53149. */
  53150. set: function (value) {
  53151. this._shadowAngle = value;
  53152. this.forceProjectionMatrixCompute();
  53153. },
  53154. enumerable: true,
  53155. configurable: true
  53156. });
  53157. Object.defineProperty(PointLight.prototype, "direction", {
  53158. /**
  53159. * Gets the direction if it has been set.
  53160. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  53161. */
  53162. get: function () {
  53163. return this._direction;
  53164. },
  53165. /**
  53166. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  53167. */
  53168. set: function (value) {
  53169. var previousNeedCube = this.needCube();
  53170. this._direction = value;
  53171. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  53172. this._shadowGenerator.recreateShadowMap();
  53173. }
  53174. },
  53175. enumerable: true,
  53176. configurable: true
  53177. });
  53178. /**
  53179. * Returns the string "PointLight"
  53180. * @returns the class name
  53181. */
  53182. PointLight.prototype.getClassName = function () {
  53183. return "PointLight";
  53184. };
  53185. /**
  53186. * Returns the integer 0.
  53187. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  53188. */
  53189. PointLight.prototype.getTypeID = function () {
  53190. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  53191. };
  53192. /**
  53193. * Specifies wether or not the shadowmap should be a cube texture.
  53194. * @returns true if the shadowmap needs to be a cube texture.
  53195. */
  53196. PointLight.prototype.needCube = function () {
  53197. return !this.direction;
  53198. };
  53199. /**
  53200. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  53201. * @param faceIndex The index of the face we are computed the direction to generate shadow
  53202. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  53203. */
  53204. PointLight.prototype.getShadowDirection = function (faceIndex) {
  53205. if (this.direction) {
  53206. return _super.prototype.getShadowDirection.call(this, faceIndex);
  53207. }
  53208. else {
  53209. switch (faceIndex) {
  53210. case 0:
  53211. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  53212. case 1:
  53213. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  53214. case 2:
  53215. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  53216. case 3:
  53217. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  53218. case 4:
  53219. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  53220. case 5:
  53221. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  53222. }
  53223. }
  53224. return BABYLON.Vector3.Zero();
  53225. };
  53226. /**
  53227. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  53228. * - fov = PI / 2
  53229. * - aspect ratio : 1.0
  53230. * - z-near and far equal to the active camera minZ and maxZ.
  53231. * Returns the PointLight.
  53232. */
  53233. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  53234. var activeCamera = this.getScene().activeCamera;
  53235. if (!activeCamera) {
  53236. return;
  53237. }
  53238. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  53239. };
  53240. PointLight.prototype._buildUniformLayout = function () {
  53241. this._uniformBuffer.addUniform("vLightData", 4);
  53242. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  53243. this._uniformBuffer.addUniform("vLightSpecular", 3);
  53244. this._uniformBuffer.addUniform("vLightFalloff", 4);
  53245. this._uniformBuffer.addUniform("shadowsInfo", 3);
  53246. this._uniformBuffer.addUniform("depthValues", 2);
  53247. this._uniformBuffer.create();
  53248. };
  53249. /**
  53250. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  53251. * @param effect The effect to update
  53252. * @param lightIndex The index of the light in the effect to update
  53253. * @returns The point light
  53254. */
  53255. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  53256. if (this.computeTransformedInformation()) {
  53257. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  53258. }
  53259. else {
  53260. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  53261. }
  53262. this._uniformBuffer.updateFloat4("vLightFalloff", this.range, this._inverseSquaredRange, 0, 0, lightIndex);
  53263. return this;
  53264. };
  53265. /**
  53266. * Prepares the list of defines specific to the light type.
  53267. * @param defines the list of defines
  53268. * @param lightIndex defines the index of the light for the effect
  53269. */
  53270. PointLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  53271. defines["POINTLIGHT" + lightIndex] = true;
  53272. };
  53273. __decorate([
  53274. BABYLON.serialize()
  53275. ], PointLight.prototype, "shadowAngle", null);
  53276. return PointLight;
  53277. }(BABYLON.ShadowLight));
  53278. BABYLON.PointLight = PointLight;
  53279. })(BABYLON || (BABYLON = {}));
  53280. //# sourceMappingURL=babylon.pointLight.js.map
  53281. var BABYLON;
  53282. (function (BABYLON) {
  53283. BABYLON.Node.AddNodeConstructor("Light_Type_1", function (name, scene) {
  53284. return function () { return new DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  53285. });
  53286. /**
  53287. * A directional light is defined by a direction (what a surprise!).
  53288. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  53289. * 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.
  53290. * Documentation: https://doc.babylonjs.com/babylon101/lights
  53291. */
  53292. var DirectionalLight = /** @class */ (function (_super) {
  53293. __extends(DirectionalLight, _super);
  53294. /**
  53295. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  53296. * The directional light is emitted from everywhere in the given direction.
  53297. * It can cast shadows.
  53298. * Documentation : https://doc.babylonjs.com/babylon101/lights
  53299. * @param name The friendly name of the light
  53300. * @param direction The direction of the light
  53301. * @param scene The scene the light belongs to
  53302. */
  53303. function DirectionalLight(name, direction, scene) {
  53304. var _this = _super.call(this, name, scene) || this;
  53305. _this._shadowFrustumSize = 0;
  53306. _this._shadowOrthoScale = 0.1;
  53307. /**
  53308. * Automatically compute the projection matrix to best fit (including all the casters)
  53309. * on each frame.
  53310. */
  53311. _this.autoUpdateExtends = true;
  53312. // Cache
  53313. _this._orthoLeft = Number.MAX_VALUE;
  53314. _this._orthoRight = Number.MIN_VALUE;
  53315. _this._orthoTop = Number.MIN_VALUE;
  53316. _this._orthoBottom = Number.MAX_VALUE;
  53317. _this.position = direction.scale(-1.0);
  53318. _this.direction = direction;
  53319. return _this;
  53320. }
  53321. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  53322. /**
  53323. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  53324. */
  53325. get: function () {
  53326. return this._shadowFrustumSize;
  53327. },
  53328. /**
  53329. * Specifies a fix frustum size for the shadow generation.
  53330. */
  53331. set: function (value) {
  53332. this._shadowFrustumSize = value;
  53333. this.forceProjectionMatrixCompute();
  53334. },
  53335. enumerable: true,
  53336. configurable: true
  53337. });
  53338. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  53339. /**
  53340. * Gets the shadow projection scale against the optimal computed one.
  53341. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  53342. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  53343. */
  53344. get: function () {
  53345. return this._shadowOrthoScale;
  53346. },
  53347. /**
  53348. * Sets the shadow projection scale against the optimal computed one.
  53349. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  53350. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  53351. */
  53352. set: function (value) {
  53353. this._shadowOrthoScale = value;
  53354. this.forceProjectionMatrixCompute();
  53355. },
  53356. enumerable: true,
  53357. configurable: true
  53358. });
  53359. /**
  53360. * Returns the string "DirectionalLight".
  53361. * @return The class name
  53362. */
  53363. DirectionalLight.prototype.getClassName = function () {
  53364. return "DirectionalLight";
  53365. };
  53366. /**
  53367. * Returns the integer 1.
  53368. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  53369. */
  53370. DirectionalLight.prototype.getTypeID = function () {
  53371. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  53372. };
  53373. /**
  53374. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  53375. * Returns the DirectionalLight Shadow projection matrix.
  53376. */
  53377. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  53378. if (this.shadowFrustumSize > 0) {
  53379. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  53380. }
  53381. else {
  53382. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  53383. }
  53384. };
  53385. /**
  53386. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  53387. * Returns the DirectionalLight Shadow projection matrix.
  53388. */
  53389. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  53390. var activeCamera = this.getScene().activeCamera;
  53391. if (!activeCamera) {
  53392. return;
  53393. }
  53394. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  53395. };
  53396. /**
  53397. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  53398. * Returns the DirectionalLight Shadow projection matrix.
  53399. */
  53400. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  53401. var activeCamera = this.getScene().activeCamera;
  53402. if (!activeCamera) {
  53403. return;
  53404. }
  53405. // Check extends
  53406. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  53407. var tempVector3 = BABYLON.Vector3.Zero();
  53408. this._orthoLeft = Number.MAX_VALUE;
  53409. this._orthoRight = Number.MIN_VALUE;
  53410. this._orthoTop = Number.MIN_VALUE;
  53411. this._orthoBottom = Number.MAX_VALUE;
  53412. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  53413. var mesh = renderList[meshIndex];
  53414. if (!mesh) {
  53415. continue;
  53416. }
  53417. var boundingInfo = mesh.getBoundingInfo();
  53418. var boundingBox = boundingInfo.boundingBox;
  53419. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  53420. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  53421. if (tempVector3.x < this._orthoLeft) {
  53422. this._orthoLeft = tempVector3.x;
  53423. }
  53424. if (tempVector3.y < this._orthoBottom) {
  53425. this._orthoBottom = tempVector3.y;
  53426. }
  53427. if (tempVector3.x > this._orthoRight) {
  53428. this._orthoRight = tempVector3.x;
  53429. }
  53430. if (tempVector3.y > this._orthoTop) {
  53431. this._orthoTop = tempVector3.y;
  53432. }
  53433. }
  53434. }
  53435. }
  53436. var xOffset = this._orthoRight - this._orthoLeft;
  53437. var yOffset = this._orthoTop - this._orthoBottom;
  53438. 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);
  53439. };
  53440. DirectionalLight.prototype._buildUniformLayout = function () {
  53441. this._uniformBuffer.addUniform("vLightData", 4);
  53442. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  53443. this._uniformBuffer.addUniform("vLightSpecular", 3);
  53444. this._uniformBuffer.addUniform("shadowsInfo", 3);
  53445. this._uniformBuffer.addUniform("depthValues", 2);
  53446. this._uniformBuffer.create();
  53447. };
  53448. /**
  53449. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  53450. * @param effect The effect to update
  53451. * @param lightIndex The index of the light in the effect to update
  53452. * @returns The directional light
  53453. */
  53454. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  53455. if (this.computeTransformedInformation()) {
  53456. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  53457. return this;
  53458. }
  53459. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  53460. return this;
  53461. };
  53462. /**
  53463. * Gets the minZ used for shadow according to both the scene and the light.
  53464. *
  53465. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  53466. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  53467. * @param activeCamera The camera we are returning the min for
  53468. * @returns the depth min z
  53469. */
  53470. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  53471. return 1;
  53472. };
  53473. /**
  53474. * Gets the maxZ used for shadow according to both the scene and the light.
  53475. *
  53476. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  53477. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  53478. * @param activeCamera The camera we are returning the max for
  53479. * @returns the depth max z
  53480. */
  53481. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  53482. return 1;
  53483. };
  53484. /**
  53485. * Prepares the list of defines specific to the light type.
  53486. * @param defines the list of defines
  53487. * @param lightIndex defines the index of the light for the effect
  53488. */
  53489. DirectionalLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  53490. defines["DIRLIGHT" + lightIndex] = true;
  53491. };
  53492. __decorate([
  53493. BABYLON.serialize()
  53494. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  53495. __decorate([
  53496. BABYLON.serialize()
  53497. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  53498. __decorate([
  53499. BABYLON.serialize()
  53500. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  53501. return DirectionalLight;
  53502. }(BABYLON.ShadowLight));
  53503. BABYLON.DirectionalLight = DirectionalLight;
  53504. })(BABYLON || (BABYLON = {}));
  53505. //# sourceMappingURL=babylon.directionalLight.js.map
  53506. var BABYLON;
  53507. (function (BABYLON) {
  53508. BABYLON.Node.AddNodeConstructor("Light_Type_2", function (name, scene) {
  53509. return function () { return new SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  53510. });
  53511. /**
  53512. * A spot light is defined by a position, a direction, an angle, and an exponent.
  53513. * These values define a cone of light starting from the position, emitting toward the direction.
  53514. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  53515. * and the exponent defines the speed of the decay of the light with distance (reach).
  53516. * Documentation: https://doc.babylonjs.com/babylon101/lights
  53517. */
  53518. var SpotLight = /** @class */ (function (_super) {
  53519. __extends(SpotLight, _super);
  53520. /**
  53521. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  53522. * It can cast shadows.
  53523. * Documentation : https://doc.babylonjs.com/babylon101/lights
  53524. * @param name The light friendly name
  53525. * @param position The position of the spot light in the scene
  53526. * @param direction The direction of the light in the scene
  53527. * @param angle The cone angle of the light in Radians
  53528. * @param exponent The light decay speed with the distance from the emission spot
  53529. * @param scene The scene the lights belongs to
  53530. */
  53531. function SpotLight(name, position, direction, angle, exponent, scene) {
  53532. var _this = _super.call(this, name, scene) || this;
  53533. _this._innerAngle = 0;
  53534. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  53535. _this._projectionTextureLightNear = 1e-6;
  53536. _this._projectionTextureLightFar = 1000.0;
  53537. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  53538. _this._projectionTextureViewLightDirty = true;
  53539. _this._projectionTextureProjectionLightDirty = true;
  53540. _this._projectionTextureDirty = true;
  53541. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  53542. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  53543. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  53544. _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);
  53545. _this.position = position;
  53546. _this.direction = direction;
  53547. _this.angle = angle;
  53548. _this.exponent = exponent;
  53549. return _this;
  53550. }
  53551. Object.defineProperty(SpotLight.prototype, "angle", {
  53552. /**
  53553. * Gets the cone angle of the spot light in Radians.
  53554. */
  53555. get: function () {
  53556. return this._angle;
  53557. },
  53558. /**
  53559. * Sets the cone angle of the spot light in Radians.
  53560. */
  53561. set: function (value) {
  53562. this._angle = value;
  53563. this._cosHalfAngle = Math.cos(value * 0.5);
  53564. this._projectionTextureProjectionLightDirty = true;
  53565. this.forceProjectionMatrixCompute();
  53566. this._computeAngleValues();
  53567. },
  53568. enumerable: true,
  53569. configurable: true
  53570. });
  53571. Object.defineProperty(SpotLight.prototype, "innerAngle", {
  53572. /**
  53573. * Only used in gltf falloff mode, this defines the angle where
  53574. * the directional falloff will start before cutting at angle which could be seen
  53575. * as outer angle.
  53576. */
  53577. get: function () {
  53578. return this._innerAngle;
  53579. },
  53580. /**
  53581. * Only used in gltf falloff mode, this defines the angle where
  53582. * the directional falloff will start before cutting at angle which could be seen
  53583. * as outer angle.
  53584. */
  53585. set: function (value) {
  53586. this._innerAngle = value;
  53587. this._computeAngleValues();
  53588. },
  53589. enumerable: true,
  53590. configurable: true
  53591. });
  53592. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  53593. /**
  53594. * Allows scaling the angle of the light for shadow generation only.
  53595. */
  53596. get: function () {
  53597. return this._shadowAngleScale;
  53598. },
  53599. /**
  53600. * Allows scaling the angle of the light for shadow generation only.
  53601. */
  53602. set: function (value) {
  53603. this._shadowAngleScale = value;
  53604. this.forceProjectionMatrixCompute();
  53605. },
  53606. enumerable: true,
  53607. configurable: true
  53608. });
  53609. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  53610. /**
  53611. * Allows reading the projecton texture
  53612. */
  53613. get: function () {
  53614. return this._projectionTextureMatrix;
  53615. },
  53616. enumerable: true,
  53617. configurable: true
  53618. });
  53619. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  53620. /**
  53621. * Gets the near clip of the Spotlight for texture projection.
  53622. */
  53623. get: function () {
  53624. return this._projectionTextureLightNear;
  53625. },
  53626. /**
  53627. * Sets the near clip of the Spotlight for texture projection.
  53628. */
  53629. set: function (value) {
  53630. this._projectionTextureLightNear = value;
  53631. this._projectionTextureProjectionLightDirty = true;
  53632. },
  53633. enumerable: true,
  53634. configurable: true
  53635. });
  53636. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  53637. /**
  53638. * Gets the far clip of the Spotlight for texture projection.
  53639. */
  53640. get: function () {
  53641. return this._projectionTextureLightFar;
  53642. },
  53643. /**
  53644. * Sets the far clip of the Spotlight for texture projection.
  53645. */
  53646. set: function (value) {
  53647. this._projectionTextureLightFar = value;
  53648. this._projectionTextureProjectionLightDirty = true;
  53649. },
  53650. enumerable: true,
  53651. configurable: true
  53652. });
  53653. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  53654. /**
  53655. * Gets the Up vector of the Spotlight for texture projection.
  53656. */
  53657. get: function () {
  53658. return this._projectionTextureUpDirection;
  53659. },
  53660. /**
  53661. * Sets the Up vector of the Spotlight for texture projection.
  53662. */
  53663. set: function (value) {
  53664. this._projectionTextureUpDirection = value;
  53665. this._projectionTextureProjectionLightDirty = true;
  53666. },
  53667. enumerable: true,
  53668. configurable: true
  53669. });
  53670. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  53671. /**
  53672. * Gets the projection texture of the light.
  53673. */
  53674. get: function () {
  53675. return this._projectionTexture;
  53676. },
  53677. /**
  53678. * Sets the projection texture of the light.
  53679. */
  53680. set: function (value) {
  53681. this._projectionTexture = value;
  53682. this._projectionTextureDirty = true;
  53683. },
  53684. enumerable: true,
  53685. configurable: true
  53686. });
  53687. /**
  53688. * Returns the string "SpotLight".
  53689. * @returns the class name
  53690. */
  53691. SpotLight.prototype.getClassName = function () {
  53692. return "SpotLight";
  53693. };
  53694. /**
  53695. * Returns the integer 2.
  53696. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  53697. */
  53698. SpotLight.prototype.getTypeID = function () {
  53699. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  53700. };
  53701. /**
  53702. * Overrides the direction setter to recompute the projection texture view light Matrix.
  53703. */
  53704. SpotLight.prototype._setDirection = function (value) {
  53705. _super.prototype._setDirection.call(this, value);
  53706. this._projectionTextureViewLightDirty = true;
  53707. };
  53708. /**
  53709. * Overrides the position setter to recompute the projection texture view light Matrix.
  53710. */
  53711. SpotLight.prototype._setPosition = function (value) {
  53712. _super.prototype._setPosition.call(this, value);
  53713. this._projectionTextureViewLightDirty = true;
  53714. };
  53715. /**
  53716. * 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.
  53717. * Returns the SpotLight.
  53718. */
  53719. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  53720. var activeCamera = this.getScene().activeCamera;
  53721. if (!activeCamera) {
  53722. return;
  53723. }
  53724. this._shadowAngleScale = this._shadowAngleScale || 1;
  53725. var angle = this._shadowAngleScale * this._angle;
  53726. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  53727. };
  53728. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  53729. this._projectionTextureViewLightDirty = false;
  53730. this._projectionTextureDirty = true;
  53731. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  53732. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  53733. };
  53734. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  53735. this._projectionTextureProjectionLightDirty = false;
  53736. this._projectionTextureDirty = true;
  53737. var light_far = this.projectionTextureLightFar;
  53738. var light_near = this.projectionTextureLightNear;
  53739. var P = light_far / (light_far - light_near);
  53740. var Q = -P * light_near;
  53741. var S = 1.0 / Math.tan(this._angle / 2.0);
  53742. var A = 1.0;
  53743. 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);
  53744. };
  53745. /**
  53746. * Main function for light texture projection matrix computing.
  53747. */
  53748. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  53749. this._projectionTextureDirty = false;
  53750. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  53751. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  53752. };
  53753. SpotLight.prototype._buildUniformLayout = function () {
  53754. this._uniformBuffer.addUniform("vLightData", 4);
  53755. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  53756. this._uniformBuffer.addUniform("vLightSpecular", 3);
  53757. this._uniformBuffer.addUniform("vLightDirection", 3);
  53758. this._uniformBuffer.addUniform("vLightFalloff", 4);
  53759. this._uniformBuffer.addUniform("shadowsInfo", 3);
  53760. this._uniformBuffer.addUniform("depthValues", 2);
  53761. this._uniformBuffer.create();
  53762. };
  53763. SpotLight.prototype._computeAngleValues = function () {
  53764. this._lightAngleScale = 1.0 / Math.max(0.001, (Math.cos(this._innerAngle * 0.5) - this._cosHalfAngle));
  53765. this._lightAngleOffset = -this._cosHalfAngle * this._lightAngleScale;
  53766. };
  53767. /**
  53768. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  53769. * @param effect The effect to update
  53770. * @param lightIndex The index of the light in the effect to update
  53771. * @returns The spot light
  53772. */
  53773. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  53774. var normalizeDirection;
  53775. if (this.computeTransformedInformation()) {
  53776. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  53777. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  53778. }
  53779. else {
  53780. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  53781. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  53782. }
  53783. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, this._cosHalfAngle, lightIndex);
  53784. this._uniformBuffer.updateFloat4("vLightFalloff", this.range, this._inverseSquaredRange, this._lightAngleScale, this._lightAngleOffset, lightIndex);
  53785. if (this.projectionTexture && this.projectionTexture.isReady()) {
  53786. if (this._projectionTextureViewLightDirty) {
  53787. this._computeProjectionTextureViewLightMatrix();
  53788. }
  53789. if (this._projectionTextureProjectionLightDirty) {
  53790. this._computeProjectionTextureProjectionLightMatrix();
  53791. }
  53792. if (this._projectionTextureDirty) {
  53793. this._computeProjectionTextureMatrix();
  53794. }
  53795. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  53796. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  53797. }
  53798. return this;
  53799. };
  53800. /**
  53801. * Disposes the light and the associated resources.
  53802. */
  53803. SpotLight.prototype.dispose = function () {
  53804. _super.prototype.dispose.call(this);
  53805. if (this._projectionTexture) {
  53806. this._projectionTexture.dispose();
  53807. }
  53808. };
  53809. /**
  53810. * Prepares the list of defines specific to the light type.
  53811. * @param defines the list of defines
  53812. * @param lightIndex defines the index of the light for the effect
  53813. */
  53814. SpotLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  53815. defines["SPOTLIGHT" + lightIndex] = true;
  53816. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = this.projectionTexture ? true : false;
  53817. };
  53818. __decorate([
  53819. BABYLON.serialize()
  53820. ], SpotLight.prototype, "angle", null);
  53821. __decorate([
  53822. BABYLON.serialize()
  53823. ], SpotLight.prototype, "innerAngle", null);
  53824. __decorate([
  53825. BABYLON.serialize()
  53826. ], SpotLight.prototype, "shadowAngleScale", null);
  53827. __decorate([
  53828. BABYLON.serialize()
  53829. ], SpotLight.prototype, "exponent", void 0);
  53830. __decorate([
  53831. BABYLON.serialize()
  53832. ], SpotLight.prototype, "projectionTextureLightNear", null);
  53833. __decorate([
  53834. BABYLON.serialize()
  53835. ], SpotLight.prototype, "projectionTextureLightFar", null);
  53836. __decorate([
  53837. BABYLON.serialize()
  53838. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  53839. __decorate([
  53840. BABYLON.serializeAsTexture("projectedLightTexture")
  53841. ], SpotLight.prototype, "_projectionTexture", void 0);
  53842. return SpotLight;
  53843. }(BABYLON.ShadowLight));
  53844. BABYLON.SpotLight = SpotLight;
  53845. })(BABYLON || (BABYLON = {}));
  53846. //# sourceMappingURL=babylon.spotLight.js.map
  53847. var BABYLON;
  53848. (function (BABYLON) {
  53849. /**
  53850. * Class used to override all child animations of a given target
  53851. */
  53852. var AnimationPropertiesOverride = /** @class */ (function () {
  53853. function AnimationPropertiesOverride() {
  53854. /**
  53855. * Gets or sets a value indicating if animation blending must be used
  53856. */
  53857. this.enableBlending = false;
  53858. /**
  53859. * Gets or sets the blending speed to use when enableBlending is true
  53860. */
  53861. this.blendingSpeed = 0.01;
  53862. /**
  53863. * Gets or sets the default loop mode to use
  53864. */
  53865. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  53866. }
  53867. return AnimationPropertiesOverride;
  53868. }());
  53869. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  53870. })(BABYLON || (BABYLON = {}));
  53871. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  53872. var BABYLON;
  53873. (function (BABYLON) {
  53874. /**
  53875. * Represents the range of an animation
  53876. */
  53877. var AnimationRange = /** @class */ (function () {
  53878. /**
  53879. * Initializes the range of an animation
  53880. * @param name The name of the animation range
  53881. * @param from The starting frame of the animation
  53882. * @param to The ending frame of the animation
  53883. */
  53884. function AnimationRange(
  53885. /**The name of the animation range**/
  53886. name,
  53887. /**The starting frame of the animation */
  53888. from,
  53889. /**The ending frame of the animation*/
  53890. to) {
  53891. this.name = name;
  53892. this.from = from;
  53893. this.to = to;
  53894. }
  53895. /**
  53896. * Makes a copy of the animation range
  53897. * @returns A copy of the animation range
  53898. */
  53899. AnimationRange.prototype.clone = function () {
  53900. return new AnimationRange(this.name, this.from, this.to);
  53901. };
  53902. return AnimationRange;
  53903. }());
  53904. BABYLON.AnimationRange = AnimationRange;
  53905. /**
  53906. * Composed of a frame, and an action function
  53907. */
  53908. var AnimationEvent = /** @class */ (function () {
  53909. /**
  53910. * Initializes the animation event
  53911. * @param frame The frame for which the event is triggered
  53912. * @param action The event to perform when triggered
  53913. * @param onlyOnce Specifies if the event should be triggered only once
  53914. */
  53915. function AnimationEvent(
  53916. /** The frame for which the event is triggered **/
  53917. frame,
  53918. /** The event to perform when triggered **/
  53919. action,
  53920. /** Specifies if the event should be triggered only once**/
  53921. onlyOnce) {
  53922. this.frame = frame;
  53923. this.action = action;
  53924. this.onlyOnce = onlyOnce;
  53925. /**
  53926. * Specifies if the animation event is done
  53927. */
  53928. this.isDone = false;
  53929. }
  53930. /** @hidden */
  53931. AnimationEvent.prototype._clone = function () {
  53932. return new AnimationEvent(this.frame, this.action, this.onlyOnce);
  53933. };
  53934. return AnimationEvent;
  53935. }());
  53936. BABYLON.AnimationEvent = AnimationEvent;
  53937. /**
  53938. * A cursor which tracks a point on a path
  53939. */
  53940. var PathCursor = /** @class */ (function () {
  53941. /**
  53942. * Initializes the path cursor
  53943. * @param path The path to track
  53944. */
  53945. function PathCursor(path) {
  53946. this.path = path;
  53947. /**
  53948. * Stores path cursor callbacks for when an onchange event is triggered
  53949. */
  53950. this._onchange = new Array();
  53951. /**
  53952. * The value of the path cursor
  53953. */
  53954. this.value = 0;
  53955. /**
  53956. * The animation array of the path cursor
  53957. */
  53958. this.animations = new Array();
  53959. }
  53960. /**
  53961. * Gets the cursor point on the path
  53962. * @returns A point on the path cursor at the cursor location
  53963. */
  53964. PathCursor.prototype.getPoint = function () {
  53965. var point = this.path.getPointAtLengthPosition(this.value);
  53966. return new BABYLON.Vector3(point.x, 0, point.y);
  53967. };
  53968. /**
  53969. * Moves the cursor ahead by the step amount
  53970. * @param step The amount to move the cursor forward
  53971. * @returns This path cursor
  53972. */
  53973. PathCursor.prototype.moveAhead = function (step) {
  53974. if (step === void 0) { step = 0.002; }
  53975. this.move(step);
  53976. return this;
  53977. };
  53978. /**
  53979. * Moves the cursor behind by the step amount
  53980. * @param step The amount to move the cursor back
  53981. * @returns This path cursor
  53982. */
  53983. PathCursor.prototype.moveBack = function (step) {
  53984. if (step === void 0) { step = 0.002; }
  53985. this.move(-step);
  53986. return this;
  53987. };
  53988. /**
  53989. * Moves the cursor by the step amount
  53990. * If the step amount is greater than one, an exception is thrown
  53991. * @param step The amount to move the cursor
  53992. * @returns This path cursor
  53993. */
  53994. PathCursor.prototype.move = function (step) {
  53995. if (Math.abs(step) > 1) {
  53996. throw "step size should be less than 1.";
  53997. }
  53998. this.value += step;
  53999. this.ensureLimits();
  54000. this.raiseOnChange();
  54001. return this;
  54002. };
  54003. /**
  54004. * Ensures that the value is limited between zero and one
  54005. * @returns This path cursor
  54006. */
  54007. PathCursor.prototype.ensureLimits = function () {
  54008. while (this.value > 1) {
  54009. this.value -= 1;
  54010. }
  54011. while (this.value < 0) {
  54012. this.value += 1;
  54013. }
  54014. return this;
  54015. };
  54016. /**
  54017. * Runs onchange callbacks on change (used by the animation engine)
  54018. * @returns This path cursor
  54019. */
  54020. PathCursor.prototype.raiseOnChange = function () {
  54021. var _this = this;
  54022. this._onchange.forEach(function (f) { return f(_this); });
  54023. return this;
  54024. };
  54025. /**
  54026. * Executes a function on change
  54027. * @param f A path cursor onchange callback
  54028. * @returns This path cursor
  54029. */
  54030. PathCursor.prototype.onchange = function (f) {
  54031. this._onchange.push(f);
  54032. return this;
  54033. };
  54034. return PathCursor;
  54035. }());
  54036. BABYLON.PathCursor = PathCursor;
  54037. /**
  54038. * Enum for the animation key frame interpolation type
  54039. */
  54040. var AnimationKeyInterpolation;
  54041. (function (AnimationKeyInterpolation) {
  54042. /**
  54043. * Do not interpolate between keys and use the start key value only. Tangents are ignored
  54044. */
  54045. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  54046. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  54047. /**
  54048. * Class used to store any kind of animation
  54049. */
  54050. var Animation = /** @class */ (function () {
  54051. /**
  54052. * Initializes the animation
  54053. * @param name Name of the animation
  54054. * @param targetProperty Property to animate
  54055. * @param framePerSecond The frames per second of the animation
  54056. * @param dataType The data type of the animation
  54057. * @param loopMode The loop mode of the animation
  54058. * @param enableBlendings Specifies if blending should be enabled
  54059. */
  54060. function Animation(
  54061. /**Name of the animation */
  54062. name,
  54063. /**Property to animate */
  54064. targetProperty,
  54065. /**The frames per second of the animation */
  54066. framePerSecond,
  54067. /**The data type of the animation */
  54068. dataType,
  54069. /**The loop mode of the animation */
  54070. loopMode,
  54071. /**Specifies if blending should be enabled */
  54072. enableBlending) {
  54073. this.name = name;
  54074. this.targetProperty = targetProperty;
  54075. this.framePerSecond = framePerSecond;
  54076. this.dataType = dataType;
  54077. this.loopMode = loopMode;
  54078. this.enableBlending = enableBlending;
  54079. /**
  54080. * @hidden Internal use only
  54081. */
  54082. this._runtimeAnimations = new Array();
  54083. /**
  54084. * The set of event that will be linked to this animation
  54085. */
  54086. this._events = new Array();
  54087. /**
  54088. * Stores the blending speed of the animation
  54089. */
  54090. this.blendingSpeed = 0.01;
  54091. /**
  54092. * Stores the animation ranges for the animation
  54093. */
  54094. this._ranges = {};
  54095. this.targetPropertyPath = targetProperty.split(".");
  54096. this.dataType = dataType;
  54097. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  54098. }
  54099. /**
  54100. * @hidden Internal use
  54101. */
  54102. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  54103. var dataType = undefined;
  54104. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  54105. dataType = Animation.ANIMATIONTYPE_FLOAT;
  54106. }
  54107. else if (from instanceof BABYLON.Quaternion) {
  54108. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  54109. }
  54110. else if (from instanceof BABYLON.Vector3) {
  54111. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  54112. }
  54113. else if (from instanceof BABYLON.Vector2) {
  54114. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  54115. }
  54116. else if (from instanceof BABYLON.Color3) {
  54117. dataType = Animation.ANIMATIONTYPE_COLOR3;
  54118. }
  54119. else if (from instanceof BABYLON.Size) {
  54120. dataType = Animation.ANIMATIONTYPE_SIZE;
  54121. }
  54122. if (dataType == undefined) {
  54123. return null;
  54124. }
  54125. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  54126. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  54127. animation.setKeys(keys);
  54128. if (easingFunction !== undefined) {
  54129. animation.setEasingFunction(easingFunction);
  54130. }
  54131. return animation;
  54132. };
  54133. /**
  54134. * Sets up an animation
  54135. * @param property The property to animate
  54136. * @param animationType The animation type to apply
  54137. * @param framePerSecond The frames per second of the animation
  54138. * @param easingFunction The easing function used in the animation
  54139. * @returns The created animation
  54140. */
  54141. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  54142. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  54143. animation.setEasingFunction(easingFunction);
  54144. return animation;
  54145. };
  54146. /**
  54147. * Create and start an animation on a node
  54148. * @param name defines the name of the global animation that will be run on all nodes
  54149. * @param node defines the root node where the animation will take place
  54150. * @param targetProperty defines property to animate
  54151. * @param framePerSecond defines the number of frame per second yo use
  54152. * @param totalFrame defines the number of frames in total
  54153. * @param from defines the initial value
  54154. * @param to defines the final value
  54155. * @param loopMode defines which loop mode you want to use (off by default)
  54156. * @param easingFunction defines the easing function to use (linear by default)
  54157. * @param onAnimationEnd defines the callback to call when animation end
  54158. * @returns the animatable created for this animation
  54159. */
  54160. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  54161. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  54162. if (!animation) {
  54163. return null;
  54164. }
  54165. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  54166. };
  54167. /**
  54168. * Create and start an animation on a node and its descendants
  54169. * @param name defines the name of the global animation that will be run on all nodes
  54170. * @param node defines the root node where the animation will take place
  54171. * @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
  54172. * @param targetProperty defines property to animate
  54173. * @param framePerSecond defines the number of frame per second to use
  54174. * @param totalFrame defines the number of frames in total
  54175. * @param from defines the initial value
  54176. * @param to defines the final value
  54177. * @param loopMode defines which loop mode you want to use (off by default)
  54178. * @param easingFunction defines the easing function to use (linear by default)
  54179. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  54180. * @returns the list of animatables created for all nodes
  54181. * @example https://www.babylonjs-playground.com/#MH0VLI
  54182. */
  54183. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  54184. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  54185. if (!animation) {
  54186. return null;
  54187. }
  54188. var scene = node.getScene();
  54189. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  54190. };
  54191. /**
  54192. * Creates a new animation, merges it with the existing animations and starts it
  54193. * @param name Name of the animation
  54194. * @param node Node which contains the scene that begins the animations
  54195. * @param targetProperty Specifies which property to animate
  54196. * @param framePerSecond The frames per second of the animation
  54197. * @param totalFrame The total number of frames
  54198. * @param from The frame at the beginning of the animation
  54199. * @param to The frame at the end of the animation
  54200. * @param loopMode Specifies the loop mode of the animation
  54201. * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations
  54202. * @param onAnimationEnd Callback to run once the animation is complete
  54203. * @returns Nullable animation
  54204. */
  54205. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  54206. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  54207. if (!animation) {
  54208. return null;
  54209. }
  54210. node.animations.push(animation);
  54211. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  54212. };
  54213. /**
  54214. * Transition property of an host to the target Value
  54215. * @param property The property to transition
  54216. * @param targetValue The target Value of the property
  54217. * @param host The object where the property to animate belongs
  54218. * @param scene Scene used to run the animation
  54219. * @param frameRate Framerate (in frame/s) to use
  54220. * @param transition The transition type we want to use
  54221. * @param duration The duration of the animation, in milliseconds
  54222. * @param onAnimationEnd Callback trigger at the end of the animation
  54223. * @returns Nullable animation
  54224. */
  54225. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  54226. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  54227. if (duration <= 0) {
  54228. host[property] = targetValue;
  54229. if (onAnimationEnd) {
  54230. onAnimationEnd();
  54231. }
  54232. return null;
  54233. }
  54234. var endFrame = frameRate * (duration / 1000);
  54235. transition.setKeys([{
  54236. frame: 0,
  54237. value: host[property].clone ? host[property].clone() : host[property]
  54238. },
  54239. {
  54240. frame: endFrame,
  54241. value: targetValue
  54242. }]);
  54243. if (!host.animations) {
  54244. host.animations = [];
  54245. }
  54246. host.animations.push(transition);
  54247. var animation = scene.beginAnimation(host, 0, endFrame, false);
  54248. animation.onAnimationEnd = onAnimationEnd;
  54249. return animation;
  54250. };
  54251. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  54252. /**
  54253. * Return the array of runtime animations currently using this animation
  54254. */
  54255. get: function () {
  54256. return this._runtimeAnimations;
  54257. },
  54258. enumerable: true,
  54259. configurable: true
  54260. });
  54261. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  54262. /**
  54263. * Specifies if any of the runtime animations are currently running
  54264. */
  54265. get: function () {
  54266. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  54267. var runtimeAnimation = _a[_i];
  54268. if (!runtimeAnimation.isStopped) {
  54269. return true;
  54270. }
  54271. }
  54272. return false;
  54273. },
  54274. enumerable: true,
  54275. configurable: true
  54276. });
  54277. // Methods
  54278. /**
  54279. * Converts the animation to a string
  54280. * @param fullDetails support for multiple levels of logging within scene loading
  54281. * @returns String form of the animation
  54282. */
  54283. Animation.prototype.toString = function (fullDetails) {
  54284. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  54285. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  54286. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  54287. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  54288. if (fullDetails) {
  54289. ret += ", Ranges: {";
  54290. var first = true;
  54291. for (var name in this._ranges) {
  54292. if (first) {
  54293. ret += ", ";
  54294. first = false;
  54295. }
  54296. ret += name;
  54297. }
  54298. ret += "}";
  54299. }
  54300. return ret;
  54301. };
  54302. /**
  54303. * Add an event to this animation
  54304. * @param event Event to add
  54305. */
  54306. Animation.prototype.addEvent = function (event) {
  54307. this._events.push(event);
  54308. };
  54309. /**
  54310. * Remove all events found at the given frame
  54311. * @param frame The frame to remove events from
  54312. */
  54313. Animation.prototype.removeEvents = function (frame) {
  54314. for (var index = 0; index < this._events.length; index++) {
  54315. if (this._events[index].frame === frame) {
  54316. this._events.splice(index, 1);
  54317. index--;
  54318. }
  54319. }
  54320. };
  54321. /**
  54322. * Retrieves all the events from the animation
  54323. * @returns Events from the animation
  54324. */
  54325. Animation.prototype.getEvents = function () {
  54326. return this._events;
  54327. };
  54328. /**
  54329. * Creates an animation range
  54330. * @param name Name of the animation range
  54331. * @param from Starting frame of the animation range
  54332. * @param to Ending frame of the animation
  54333. */
  54334. Animation.prototype.createRange = function (name, from, to) {
  54335. // check name not already in use; could happen for bones after serialized
  54336. if (!this._ranges[name]) {
  54337. this._ranges[name] = new AnimationRange(name, from, to);
  54338. }
  54339. };
  54340. /**
  54341. * Deletes an animation range by name
  54342. * @param name Name of the animation range to delete
  54343. * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false)
  54344. */
  54345. Animation.prototype.deleteRange = function (name, deleteFrames) {
  54346. if (deleteFrames === void 0) { deleteFrames = true; }
  54347. var range = this._ranges[name];
  54348. if (!range) {
  54349. return;
  54350. }
  54351. if (deleteFrames) {
  54352. var from = range.from;
  54353. var to = range.to;
  54354. // this loop MUST go high to low for multiple splices to work
  54355. for (var key = this._keys.length - 1; key >= 0; key--) {
  54356. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  54357. this._keys.splice(key, 1);
  54358. }
  54359. }
  54360. }
  54361. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  54362. };
  54363. /**
  54364. * Gets the animation range by name, or null if not defined
  54365. * @param name Name of the animation range
  54366. * @returns Nullable animation range
  54367. */
  54368. Animation.prototype.getRange = function (name) {
  54369. return this._ranges[name];
  54370. };
  54371. /**
  54372. * Gets the key frames from the animation
  54373. * @returns The key frames of the animation
  54374. */
  54375. Animation.prototype.getKeys = function () {
  54376. return this._keys;
  54377. };
  54378. /**
  54379. * Gets the highest frame rate of the animation
  54380. * @returns Highest frame rate of the animation
  54381. */
  54382. Animation.prototype.getHighestFrame = function () {
  54383. var ret = 0;
  54384. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  54385. if (ret < this._keys[key].frame) {
  54386. ret = this._keys[key].frame;
  54387. }
  54388. }
  54389. return ret;
  54390. };
  54391. /**
  54392. * Gets the easing function of the animation
  54393. * @returns Easing function of the animation
  54394. */
  54395. Animation.prototype.getEasingFunction = function () {
  54396. return this._easingFunction;
  54397. };
  54398. /**
  54399. * Sets the easing function of the animation
  54400. * @param easingFunction A custom mathematical formula for animation
  54401. */
  54402. Animation.prototype.setEasingFunction = function (easingFunction) {
  54403. this._easingFunction = easingFunction;
  54404. };
  54405. /**
  54406. * Interpolates a scalar linearly
  54407. * @param startValue Start value of the animation curve
  54408. * @param endValue End value of the animation curve
  54409. * @param gradient Scalar amount to interpolate
  54410. * @returns Interpolated scalar value
  54411. */
  54412. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  54413. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  54414. };
  54415. /**
  54416. * Interpolates a scalar cubically
  54417. * @param startValue Start value of the animation curve
  54418. * @param outTangent End tangent of the animation
  54419. * @param endValue End value of the animation curve
  54420. * @param inTangent Start tangent of the animation curve
  54421. * @param gradient Scalar amount to interpolate
  54422. * @returns Interpolated scalar value
  54423. */
  54424. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  54425. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  54426. };
  54427. /**
  54428. * Interpolates a quaternion using a spherical linear interpolation
  54429. * @param startValue Start value of the animation curve
  54430. * @param endValue End value of the animation curve
  54431. * @param gradient Scalar amount to interpolate
  54432. * @returns Interpolated quaternion value
  54433. */
  54434. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  54435. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  54436. };
  54437. /**
  54438. * Interpolates a quaternion cubically
  54439. * @param startValue Start value of the animation curve
  54440. * @param outTangent End tangent of the animation curve
  54441. * @param endValue End value of the animation curve
  54442. * @param inTangent Start tangent of the animation curve
  54443. * @param gradient Scalar amount to interpolate
  54444. * @returns Interpolated quaternion value
  54445. */
  54446. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  54447. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  54448. };
  54449. /**
  54450. * Interpolates a Vector3 linearl
  54451. * @param startValue Start value of the animation curve
  54452. * @param endValue End value of the animation curve
  54453. * @param gradient Scalar amount to interpolate
  54454. * @returns Interpolated scalar value
  54455. */
  54456. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  54457. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  54458. };
  54459. /**
  54460. * Interpolates a Vector3 cubically
  54461. * @param startValue Start value of the animation curve
  54462. * @param outTangent End tangent of the animation
  54463. * @param endValue End value of the animation curve
  54464. * @param inTangent Start tangent of the animation curve
  54465. * @param gradient Scalar amount to interpolate
  54466. * @returns InterpolatedVector3 value
  54467. */
  54468. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  54469. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  54470. };
  54471. /**
  54472. * Interpolates a Vector2 linearly
  54473. * @param startValue Start value of the animation curve
  54474. * @param endValue End value of the animation curve
  54475. * @param gradient Scalar amount to interpolate
  54476. * @returns Interpolated Vector2 value
  54477. */
  54478. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  54479. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  54480. };
  54481. /**
  54482. * Interpolates a Vector2 cubically
  54483. * @param startValue Start value of the animation curve
  54484. * @param outTangent End tangent of the animation
  54485. * @param endValue End value of the animation curve
  54486. * @param inTangent Start tangent of the animation curve
  54487. * @param gradient Scalar amount to interpolate
  54488. * @returns Interpolated Vector2 value
  54489. */
  54490. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  54491. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  54492. };
  54493. /**
  54494. * Interpolates a size linearly
  54495. * @param startValue Start value of the animation curve
  54496. * @param endValue End value of the animation curve
  54497. * @param gradient Scalar amount to interpolate
  54498. * @returns Interpolated Size value
  54499. */
  54500. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  54501. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  54502. };
  54503. /**
  54504. * Interpolates a Color3 linearly
  54505. * @param startValue Start value of the animation curve
  54506. * @param endValue End value of the animation curve
  54507. * @param gradient Scalar amount to interpolate
  54508. * @returns Interpolated Color3 value
  54509. */
  54510. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  54511. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  54512. };
  54513. /**
  54514. * @hidden Internal use only
  54515. */
  54516. Animation.prototype._getKeyValue = function (value) {
  54517. if (typeof value === "function") {
  54518. return value();
  54519. }
  54520. return value;
  54521. };
  54522. /**
  54523. * @hidden Internal use only
  54524. */
  54525. Animation.prototype._interpolate = function (currentFrame, repeatCount, workValue, loopMode, offsetValue, highLimitValue) {
  54526. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  54527. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  54528. }
  54529. var keys = this.getKeys();
  54530. // Try to get a hash to find the right key
  54531. 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));
  54532. if (keys[startKeyIndex].frame >= currentFrame) {
  54533. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  54534. startKeyIndex--;
  54535. }
  54536. }
  54537. for (var key = startKeyIndex; key < keys.length; key++) {
  54538. var endKey = keys[key + 1];
  54539. if (endKey.frame >= currentFrame) {
  54540. var startKey = keys[key];
  54541. var startValue = this._getKeyValue(startKey.value);
  54542. if (startKey.interpolation === AnimationKeyInterpolation.STEP) {
  54543. return startValue;
  54544. }
  54545. var endValue = this._getKeyValue(endKey.value);
  54546. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  54547. var frameDelta = endKey.frame - startKey.frame;
  54548. // gradient : percent of currentFrame between the frame inf and the frame sup
  54549. var gradient = (currentFrame - startKey.frame) / frameDelta;
  54550. // check for easingFunction and correction of gradient
  54551. var easingFunction = this.getEasingFunction();
  54552. if (easingFunction != null) {
  54553. gradient = easingFunction.ease(gradient);
  54554. }
  54555. switch (this.dataType) {
  54556. // Float
  54557. case Animation.ANIMATIONTYPE_FLOAT:
  54558. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  54559. switch (loopMode) {
  54560. case Animation.ANIMATIONLOOPMODE_CYCLE:
  54561. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  54562. return floatValue;
  54563. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  54564. return offsetValue * repeatCount + floatValue;
  54565. }
  54566. break;
  54567. // Quaternion
  54568. case Animation.ANIMATIONTYPE_QUATERNION:
  54569. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  54570. switch (loopMode) {
  54571. case Animation.ANIMATIONLOOPMODE_CYCLE:
  54572. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  54573. return quatValue;
  54574. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  54575. return quatValue.addInPlace(offsetValue.scale(repeatCount));
  54576. }
  54577. return quatValue;
  54578. // Vector3
  54579. case Animation.ANIMATIONTYPE_VECTOR3:
  54580. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  54581. switch (loopMode) {
  54582. case Animation.ANIMATIONLOOPMODE_CYCLE:
  54583. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  54584. return vec3Value;
  54585. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  54586. return vec3Value.add(offsetValue.scale(repeatCount));
  54587. }
  54588. // Vector2
  54589. case Animation.ANIMATIONTYPE_VECTOR2:
  54590. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  54591. switch (loopMode) {
  54592. case Animation.ANIMATIONLOOPMODE_CYCLE:
  54593. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  54594. return vec2Value;
  54595. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  54596. return vec2Value.add(offsetValue.scale(repeatCount));
  54597. }
  54598. // Size
  54599. case Animation.ANIMATIONTYPE_SIZE:
  54600. switch (loopMode) {
  54601. case Animation.ANIMATIONLOOPMODE_CYCLE:
  54602. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  54603. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  54604. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  54605. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  54606. }
  54607. // Color3
  54608. case Animation.ANIMATIONTYPE_COLOR3:
  54609. switch (loopMode) {
  54610. case Animation.ANIMATIONLOOPMODE_CYCLE:
  54611. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  54612. return this.color3InterpolateFunction(startValue, endValue, gradient);
  54613. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  54614. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  54615. }
  54616. // Matrix
  54617. case Animation.ANIMATIONTYPE_MATRIX:
  54618. switch (loopMode) {
  54619. case Animation.ANIMATIONLOOPMODE_CYCLE:
  54620. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  54621. if (Animation.AllowMatricesInterpolation) {
  54622. return this.matrixInterpolateFunction(startValue, endValue, gradient, workValue);
  54623. }
  54624. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  54625. return startValue;
  54626. }
  54627. default:
  54628. break;
  54629. }
  54630. break;
  54631. }
  54632. }
  54633. return this._getKeyValue(keys[keys.length - 1].value);
  54634. };
  54635. /**
  54636. * Defines the function to use to interpolate matrices
  54637. * @param startValue defines the start matrix
  54638. * @param endValue defines the end matrix
  54639. * @param gradient defines the gradient between both matrices
  54640. * @param result defines an optional target matrix where to store the interpolation
  54641. * @returns the interpolated matrix
  54642. */
  54643. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) {
  54644. if (Animation.AllowMatrixDecomposeForInterpolation) {
  54645. if (result) {
  54646. BABYLON.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  54647. return result;
  54648. }
  54649. return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);
  54650. }
  54651. if (result) {
  54652. BABYLON.Matrix.LerpToRef(startValue, endValue, gradient, result);
  54653. return result;
  54654. }
  54655. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  54656. };
  54657. /**
  54658. * Makes a copy of the animation
  54659. * @returns Cloned animation
  54660. */
  54661. Animation.prototype.clone = function () {
  54662. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  54663. clone.enableBlending = this.enableBlending;
  54664. clone.blendingSpeed = this.blendingSpeed;
  54665. if (this._keys) {
  54666. clone.setKeys(this._keys);
  54667. }
  54668. if (this._ranges) {
  54669. clone._ranges = {};
  54670. for (var name in this._ranges) {
  54671. var range = this._ranges[name];
  54672. if (!range) {
  54673. continue;
  54674. }
  54675. clone._ranges[name] = range.clone();
  54676. }
  54677. }
  54678. return clone;
  54679. };
  54680. /**
  54681. * Sets the key frames of the animation
  54682. * @param values The animation key frames to set
  54683. */
  54684. Animation.prototype.setKeys = function (values) {
  54685. this._keys = values.slice(0);
  54686. };
  54687. /**
  54688. * Serializes the animation to an object
  54689. * @returns Serialized object
  54690. */
  54691. Animation.prototype.serialize = function () {
  54692. var serializationObject = {};
  54693. serializationObject.name = this.name;
  54694. serializationObject.property = this.targetProperty;
  54695. serializationObject.framePerSecond = this.framePerSecond;
  54696. serializationObject.dataType = this.dataType;
  54697. serializationObject.loopBehavior = this.loopMode;
  54698. serializationObject.enableBlending = this.enableBlending;
  54699. serializationObject.blendingSpeed = this.blendingSpeed;
  54700. var dataType = this.dataType;
  54701. serializationObject.keys = [];
  54702. var keys = this.getKeys();
  54703. for (var index = 0; index < keys.length; index++) {
  54704. var animationKey = keys[index];
  54705. var key = {};
  54706. key.frame = animationKey.frame;
  54707. switch (dataType) {
  54708. case Animation.ANIMATIONTYPE_FLOAT:
  54709. key.values = [animationKey.value];
  54710. break;
  54711. case Animation.ANIMATIONTYPE_QUATERNION:
  54712. case Animation.ANIMATIONTYPE_MATRIX:
  54713. case Animation.ANIMATIONTYPE_VECTOR3:
  54714. case Animation.ANIMATIONTYPE_COLOR3:
  54715. key.values = animationKey.value.asArray();
  54716. break;
  54717. }
  54718. serializationObject.keys.push(key);
  54719. }
  54720. serializationObject.ranges = [];
  54721. for (var name in this._ranges) {
  54722. var source = this._ranges[name];
  54723. if (!source) {
  54724. continue;
  54725. }
  54726. var range = {};
  54727. range.name = name;
  54728. range.from = source.from;
  54729. range.to = source.to;
  54730. serializationObject.ranges.push(range);
  54731. }
  54732. return serializationObject;
  54733. };
  54734. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  54735. /**
  54736. * Get the float animation type
  54737. */
  54738. get: function () {
  54739. return Animation._ANIMATIONTYPE_FLOAT;
  54740. },
  54741. enumerable: true,
  54742. configurable: true
  54743. });
  54744. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  54745. /**
  54746. * Get the Vector3 animation type
  54747. */
  54748. get: function () {
  54749. return Animation._ANIMATIONTYPE_VECTOR3;
  54750. },
  54751. enumerable: true,
  54752. configurable: true
  54753. });
  54754. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  54755. /**
  54756. * Get the Vector2 animation type
  54757. */
  54758. get: function () {
  54759. return Animation._ANIMATIONTYPE_VECTOR2;
  54760. },
  54761. enumerable: true,
  54762. configurable: true
  54763. });
  54764. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  54765. /**
  54766. * Get the Size animation type
  54767. */
  54768. get: function () {
  54769. return Animation._ANIMATIONTYPE_SIZE;
  54770. },
  54771. enumerable: true,
  54772. configurable: true
  54773. });
  54774. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  54775. /**
  54776. * Get the Quaternion animation type
  54777. */
  54778. get: function () {
  54779. return Animation._ANIMATIONTYPE_QUATERNION;
  54780. },
  54781. enumerable: true,
  54782. configurable: true
  54783. });
  54784. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  54785. /**
  54786. * Get the Matrix animation type
  54787. */
  54788. get: function () {
  54789. return Animation._ANIMATIONTYPE_MATRIX;
  54790. },
  54791. enumerable: true,
  54792. configurable: true
  54793. });
  54794. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  54795. /**
  54796. * Get the Color3 animation type
  54797. */
  54798. get: function () {
  54799. return Animation._ANIMATIONTYPE_COLOR3;
  54800. },
  54801. enumerable: true,
  54802. configurable: true
  54803. });
  54804. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  54805. /**
  54806. * Get the Relative Loop Mode
  54807. */
  54808. get: function () {
  54809. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  54810. },
  54811. enumerable: true,
  54812. configurable: true
  54813. });
  54814. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  54815. /**
  54816. * Get the Cycle Loop Mode
  54817. */
  54818. get: function () {
  54819. return Animation._ANIMATIONLOOPMODE_CYCLE;
  54820. },
  54821. enumerable: true,
  54822. configurable: true
  54823. });
  54824. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  54825. /**
  54826. * Get the Constant Loop Mode
  54827. */
  54828. get: function () {
  54829. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  54830. },
  54831. enumerable: true,
  54832. configurable: true
  54833. });
  54834. /** @hidden */
  54835. Animation._UniversalLerp = function (left, right, amount) {
  54836. var constructor = left.constructor;
  54837. if (constructor.Lerp) { // Lerp supported
  54838. return constructor.Lerp(left, right, amount);
  54839. }
  54840. else if (constructor.Slerp) { // Slerp supported
  54841. return constructor.Slerp(left, right, amount);
  54842. }
  54843. else if (left.toFixed) { // Number
  54844. return left * (1.0 - amount) + amount * right;
  54845. }
  54846. else { // Blending not supported
  54847. return right;
  54848. }
  54849. };
  54850. /**
  54851. * Parses an animation object and creates an animation
  54852. * @param parsedAnimation Parsed animation object
  54853. * @returns Animation object
  54854. */
  54855. Animation.Parse = function (parsedAnimation) {
  54856. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  54857. var dataType = parsedAnimation.dataType;
  54858. var keys = [];
  54859. var data;
  54860. var index;
  54861. if (parsedAnimation.enableBlending) {
  54862. animation.enableBlending = parsedAnimation.enableBlending;
  54863. }
  54864. if (parsedAnimation.blendingSpeed) {
  54865. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  54866. }
  54867. for (index = 0; index < parsedAnimation.keys.length; index++) {
  54868. var key = parsedAnimation.keys[index];
  54869. var inTangent;
  54870. var outTangent;
  54871. switch (dataType) {
  54872. case Animation.ANIMATIONTYPE_FLOAT:
  54873. data = key.values[0];
  54874. if (key.values.length >= 1) {
  54875. inTangent = key.values[1];
  54876. }
  54877. if (key.values.length >= 2) {
  54878. outTangent = key.values[2];
  54879. }
  54880. break;
  54881. case Animation.ANIMATIONTYPE_QUATERNION:
  54882. data = BABYLON.Quaternion.FromArray(key.values);
  54883. if (key.values.length >= 8) {
  54884. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  54885. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  54886. inTangent = _inTangent;
  54887. }
  54888. }
  54889. if (key.values.length >= 12) {
  54890. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  54891. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  54892. outTangent = _outTangent;
  54893. }
  54894. }
  54895. break;
  54896. case Animation.ANIMATIONTYPE_MATRIX:
  54897. data = BABYLON.Matrix.FromArray(key.values);
  54898. break;
  54899. case Animation.ANIMATIONTYPE_COLOR3:
  54900. data = BABYLON.Color3.FromArray(key.values);
  54901. break;
  54902. case Animation.ANIMATIONTYPE_VECTOR3:
  54903. default:
  54904. data = BABYLON.Vector3.FromArray(key.values);
  54905. break;
  54906. }
  54907. var keyData = {};
  54908. keyData.frame = key.frame;
  54909. keyData.value = data;
  54910. if (inTangent != undefined) {
  54911. keyData.inTangent = inTangent;
  54912. }
  54913. if (outTangent != undefined) {
  54914. keyData.outTangent = outTangent;
  54915. }
  54916. keys.push(keyData);
  54917. }
  54918. animation.setKeys(keys);
  54919. if (parsedAnimation.ranges) {
  54920. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  54921. data = parsedAnimation.ranges[index];
  54922. animation.createRange(data.name, data.from, data.to);
  54923. }
  54924. }
  54925. return animation;
  54926. };
  54927. /**
  54928. * Appends the serialized animations from the source animations
  54929. * @param source Source containing the animations
  54930. * @param destination Target to store the animations
  54931. */
  54932. Animation.AppendSerializedAnimations = function (source, destination) {
  54933. if (source.animations) {
  54934. destination.animations = [];
  54935. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  54936. var animation = source.animations[animationIndex];
  54937. destination.animations.push(animation.serialize());
  54938. }
  54939. }
  54940. };
  54941. /**
  54942. * Use matrix interpolation instead of using direct key value when animating matrices
  54943. */
  54944. Animation.AllowMatricesInterpolation = false;
  54945. /**
  54946. * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
  54947. */
  54948. Animation.AllowMatrixDecomposeForInterpolation = true;
  54949. // Statics
  54950. /**
  54951. * Float animation type
  54952. */
  54953. Animation._ANIMATIONTYPE_FLOAT = 0;
  54954. /**
  54955. * Vector3 animation type
  54956. */
  54957. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  54958. /**
  54959. * Quaternion animation type
  54960. */
  54961. Animation._ANIMATIONTYPE_QUATERNION = 2;
  54962. /**
  54963. * Matrix animation type
  54964. */
  54965. Animation._ANIMATIONTYPE_MATRIX = 3;
  54966. /**
  54967. * Color3 animation type
  54968. */
  54969. Animation._ANIMATIONTYPE_COLOR3 = 4;
  54970. /**
  54971. * Vector2 animation type
  54972. */
  54973. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  54974. /**
  54975. * Size animation type
  54976. */
  54977. Animation._ANIMATIONTYPE_SIZE = 6;
  54978. /**
  54979. * Relative Loop Mode
  54980. */
  54981. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  54982. /**
  54983. * Cycle Loop Mode
  54984. */
  54985. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  54986. /**
  54987. * Constant Loop Mode
  54988. */
  54989. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  54990. return Animation;
  54991. }());
  54992. BABYLON.Animation = Animation;
  54993. })(BABYLON || (BABYLON = {}));
  54994. //# sourceMappingURL=babylon.animation.js.map
  54995. var BABYLON;
  54996. (function (BABYLON) {
  54997. /**
  54998. * This class defines the direct association between an animation and a target
  54999. */
  55000. var TargetedAnimation = /** @class */ (function () {
  55001. function TargetedAnimation() {
  55002. }
  55003. return TargetedAnimation;
  55004. }());
  55005. BABYLON.TargetedAnimation = TargetedAnimation;
  55006. /**
  55007. * Use this class to create coordinated animations on multiple targets
  55008. */
  55009. var AnimationGroup = /** @class */ (function () {
  55010. /**
  55011. * Instantiates a new Animation Group.
  55012. * This helps managing several animations at once.
  55013. * @see http://doc.babylonjs.com/how_to/group
  55014. * @param name Defines the name of the group
  55015. * @param scene Defines the scene the group belongs to
  55016. */
  55017. function AnimationGroup(
  55018. /** The name of the animation group */
  55019. name, scene) {
  55020. if (scene === void 0) { scene = null; }
  55021. this.name = name;
  55022. this._targetedAnimations = new Array();
  55023. this._animatables = new Array();
  55024. this._from = Number.MAX_VALUE;
  55025. this._to = -Number.MAX_VALUE;
  55026. this._speedRatio = 1;
  55027. /**
  55028. * This observable will notify when one animation have ended
  55029. */
  55030. this.onAnimationEndObservable = new BABYLON.Observable();
  55031. /**
  55032. * Observer raised when one animation loops
  55033. */
  55034. this.onAnimationLoopObservable = new BABYLON.Observable();
  55035. /**
  55036. * This observable will notify when all animations have ended.
  55037. */
  55038. this.onAnimationGroupEndObservable = new BABYLON.Observable();
  55039. /**
  55040. * This observable will notify when all animations have paused.
  55041. */
  55042. this.onAnimationGroupPauseObservable = new BABYLON.Observable();
  55043. /**
  55044. * This observable will notify when all animations are playing.
  55045. */
  55046. this.onAnimationGroupPlayObservable = new BABYLON.Observable();
  55047. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  55048. this.uniqueId = this._scene.getUniqueId();
  55049. this._scene.animationGroups.push(this);
  55050. }
  55051. Object.defineProperty(AnimationGroup.prototype, "from", {
  55052. /**
  55053. * Gets the first frame
  55054. */
  55055. get: function () {
  55056. return this._from;
  55057. },
  55058. enumerable: true,
  55059. configurable: true
  55060. });
  55061. Object.defineProperty(AnimationGroup.prototype, "to", {
  55062. /**
  55063. * Gets the last frame
  55064. */
  55065. get: function () {
  55066. return this._to;
  55067. },
  55068. enumerable: true,
  55069. configurable: true
  55070. });
  55071. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  55072. /**
  55073. * Define if the animations are started
  55074. */
  55075. get: function () {
  55076. return this._isStarted;
  55077. },
  55078. enumerable: true,
  55079. configurable: true
  55080. });
  55081. Object.defineProperty(AnimationGroup.prototype, "isPlaying", {
  55082. /**
  55083. * Gets a value indicating that the current group is playing
  55084. */
  55085. get: function () {
  55086. return this._isStarted && !this._isPaused;
  55087. },
  55088. enumerable: true,
  55089. configurable: true
  55090. });
  55091. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  55092. /**
  55093. * Gets or sets the speed ratio to use for all animations
  55094. */
  55095. get: function () {
  55096. return this._speedRatio;
  55097. },
  55098. /**
  55099. * Gets or sets the speed ratio to use for all animations
  55100. */
  55101. set: function (value) {
  55102. if (this._speedRatio === value) {
  55103. return;
  55104. }
  55105. this._speedRatio = value;
  55106. for (var index = 0; index < this._animatables.length; index++) {
  55107. var animatable = this._animatables[index];
  55108. animatable.speedRatio = this._speedRatio;
  55109. }
  55110. },
  55111. enumerable: true,
  55112. configurable: true
  55113. });
  55114. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  55115. /**
  55116. * Gets the targeted animations for this animation group
  55117. */
  55118. get: function () {
  55119. return this._targetedAnimations;
  55120. },
  55121. enumerable: true,
  55122. configurable: true
  55123. });
  55124. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  55125. /**
  55126. * returning the list of animatables controlled by this animation group.
  55127. */
  55128. get: function () {
  55129. return this._animatables;
  55130. },
  55131. enumerable: true,
  55132. configurable: true
  55133. });
  55134. /**
  55135. * Add an animation (with its target) in the group
  55136. * @param animation defines the animation we want to add
  55137. * @param target defines the target of the animation
  55138. * @returns the TargetedAnimation object
  55139. */
  55140. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  55141. var targetedAnimation = {
  55142. animation: animation,
  55143. target: target
  55144. };
  55145. var keys = animation.getKeys();
  55146. if (this._from > keys[0].frame) {
  55147. this._from = keys[0].frame;
  55148. }
  55149. if (this._to < keys[keys.length - 1].frame) {
  55150. this._to = keys[keys.length - 1].frame;
  55151. }
  55152. this._targetedAnimations.push(targetedAnimation);
  55153. return targetedAnimation;
  55154. };
  55155. /**
  55156. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  55157. * It can add constant keys at begin or end
  55158. * @param beginFrame defines the new begin frame for all animations or the smallest begin frame of all animations if null (defaults to null)
  55159. * @param endFrame defines the new end frame for all animations or the largest end frame of all animations if null (defaults to null)
  55160. * @returns the animation group
  55161. */
  55162. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  55163. if (beginFrame === void 0) { beginFrame = null; }
  55164. if (endFrame === void 0) { endFrame = null; }
  55165. if (beginFrame == null) {
  55166. beginFrame = this._from;
  55167. }
  55168. if (endFrame == null) {
  55169. endFrame = this._to;
  55170. }
  55171. for (var index = 0; index < this._targetedAnimations.length; index++) {
  55172. var targetedAnimation = this._targetedAnimations[index];
  55173. var keys = targetedAnimation.animation.getKeys();
  55174. var startKey = keys[0];
  55175. var endKey = keys[keys.length - 1];
  55176. if (startKey.frame > beginFrame) {
  55177. var newKey = {
  55178. frame: beginFrame,
  55179. value: startKey.value,
  55180. inTangent: startKey.inTangent,
  55181. outTangent: startKey.outTangent,
  55182. interpolation: startKey.interpolation
  55183. };
  55184. keys.splice(0, 0, newKey);
  55185. }
  55186. if (endKey.frame < endFrame) {
  55187. var newKey = {
  55188. frame: endFrame,
  55189. value: endKey.value,
  55190. inTangent: endKey.outTangent,
  55191. outTangent: endKey.outTangent,
  55192. interpolation: endKey.interpolation
  55193. };
  55194. keys.push(newKey);
  55195. }
  55196. }
  55197. this._from = beginFrame;
  55198. this._to = endFrame;
  55199. return this;
  55200. };
  55201. /**
  55202. * Start all animations on given targets
  55203. * @param loop defines if animations must loop
  55204. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  55205. * @param from defines the from key (optional)
  55206. * @param to defines the to key (optional)
  55207. * @returns the current animation group
  55208. */
  55209. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  55210. var _this = this;
  55211. if (loop === void 0) { loop = false; }
  55212. if (speedRatio === void 0) { speedRatio = 1; }
  55213. if (this._isStarted || this._targetedAnimations.length === 0) {
  55214. return this;
  55215. }
  55216. var _loop_1 = function (targetedAnimation) {
  55217. var animatable = this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this_1._from, to !== undefined ? to : this_1._to, loop, speedRatio);
  55218. animatable.onAnimationEnd = function () {
  55219. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  55220. _this._checkAnimationGroupEnded(animatable);
  55221. };
  55222. animatable.onAnimationLoop = function () {
  55223. _this.onAnimationLoopObservable.notifyObservers(targetedAnimation);
  55224. };
  55225. this_1._animatables.push(animatable);
  55226. };
  55227. var this_1 = this;
  55228. for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) {
  55229. var targetedAnimation = _a[_i];
  55230. _loop_1(targetedAnimation);
  55231. }
  55232. this._speedRatio = speedRatio;
  55233. if (from !== undefined && to !== undefined && from > to && this._speedRatio > 0) {
  55234. this._speedRatio = -speedRatio;
  55235. }
  55236. this._isStarted = true;
  55237. this._isPaused = false;
  55238. this.onAnimationGroupPlayObservable.notifyObservers(this);
  55239. return this;
  55240. };
  55241. /**
  55242. * Pause all animations
  55243. * @returns the animation group
  55244. */
  55245. AnimationGroup.prototype.pause = function () {
  55246. if (!this._isStarted) {
  55247. return this;
  55248. }
  55249. this._isPaused = true;
  55250. for (var index = 0; index < this._animatables.length; index++) {
  55251. var animatable = this._animatables[index];
  55252. animatable.pause();
  55253. }
  55254. this.onAnimationGroupPauseObservable.notifyObservers(this);
  55255. return this;
  55256. };
  55257. /**
  55258. * Play all animations to initial state
  55259. * This function will start() the animations if they were not started or will restart() them if they were paused
  55260. * @param loop defines if animations must loop
  55261. * @returns the animation group
  55262. */
  55263. AnimationGroup.prototype.play = function (loop) {
  55264. // only if all animatables are ready and exist
  55265. if (this.isStarted && this._animatables.length === this._targetedAnimations.length) {
  55266. if (loop !== undefined) {
  55267. for (var index = 0; index < this._animatables.length; index++) {
  55268. var animatable = this._animatables[index];
  55269. animatable.loopAnimation = loop;
  55270. }
  55271. }
  55272. this.restart();
  55273. }
  55274. else {
  55275. this.stop();
  55276. this.start(loop, this._speedRatio);
  55277. }
  55278. this._isPaused = false;
  55279. return this;
  55280. };
  55281. /**
  55282. * Reset all animations to initial state
  55283. * @returns the animation group
  55284. */
  55285. AnimationGroup.prototype.reset = function () {
  55286. if (!this._isStarted) {
  55287. return this;
  55288. }
  55289. for (var index = 0; index < this._animatables.length; index++) {
  55290. var animatable = this._animatables[index];
  55291. animatable.reset();
  55292. }
  55293. return this;
  55294. };
  55295. /**
  55296. * Restart animations from key 0
  55297. * @returns the animation group
  55298. */
  55299. AnimationGroup.prototype.restart = function () {
  55300. if (!this._isStarted) {
  55301. return this;
  55302. }
  55303. for (var index = 0; index < this._animatables.length; index++) {
  55304. var animatable = this._animatables[index];
  55305. animatable.restart();
  55306. }
  55307. this.onAnimationGroupPlayObservable.notifyObservers(this);
  55308. return this;
  55309. };
  55310. /**
  55311. * Stop all animations
  55312. * @returns the animation group
  55313. */
  55314. AnimationGroup.prototype.stop = function () {
  55315. if (!this._isStarted) {
  55316. return this;
  55317. }
  55318. var list = this._animatables.slice();
  55319. for (var index = 0; index < list.length; index++) {
  55320. list[index].stop();
  55321. }
  55322. this._isStarted = false;
  55323. return this;
  55324. };
  55325. /**
  55326. * Set animation weight for all animatables
  55327. * @param weight defines the weight to use
  55328. * @return the animationGroup
  55329. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  55330. */
  55331. AnimationGroup.prototype.setWeightForAllAnimatables = function (weight) {
  55332. for (var index = 0; index < this._animatables.length; index++) {
  55333. var animatable = this._animatables[index];
  55334. animatable.weight = weight;
  55335. }
  55336. return this;
  55337. };
  55338. /**
  55339. * Synchronize and normalize all animatables with a source animatable
  55340. * @param root defines the root animatable to synchronize with
  55341. * @return the animationGroup
  55342. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  55343. */
  55344. AnimationGroup.prototype.syncAllAnimationsWith = function (root) {
  55345. for (var index = 0; index < this._animatables.length; index++) {
  55346. var animatable = this._animatables[index];
  55347. animatable.syncWith(root);
  55348. }
  55349. return this;
  55350. };
  55351. /**
  55352. * Goes to a specific frame in this animation group
  55353. * @param frame the frame number to go to
  55354. * @return the animationGroup
  55355. */
  55356. AnimationGroup.prototype.goToFrame = function (frame) {
  55357. if (!this._isStarted) {
  55358. return this;
  55359. }
  55360. for (var index = 0; index < this._animatables.length; index++) {
  55361. var animatable = this._animatables[index];
  55362. animatable.goToFrame(frame);
  55363. }
  55364. return this;
  55365. };
  55366. /**
  55367. * Dispose all associated resources
  55368. */
  55369. AnimationGroup.prototype.dispose = function () {
  55370. this._targetedAnimations = [];
  55371. this._animatables = [];
  55372. var index = this._scene.animationGroups.indexOf(this);
  55373. if (index > -1) {
  55374. this._scene.animationGroups.splice(index, 1);
  55375. }
  55376. this.onAnimationEndObservable.clear();
  55377. this.onAnimationGroupEndObservable.clear();
  55378. this.onAnimationGroupPauseObservable.clear();
  55379. this.onAnimationGroupPlayObservable.clear();
  55380. this.onAnimationLoopObservable.clear();
  55381. };
  55382. AnimationGroup.prototype._checkAnimationGroupEnded = function (animatable) {
  55383. // animatable should be taken out of the array
  55384. var idx = this._animatables.indexOf(animatable);
  55385. if (idx > -1) {
  55386. this._animatables.splice(idx, 1);
  55387. }
  55388. // all animatables were removed? animation group ended!
  55389. if (this._animatables.length === 0) {
  55390. this._isStarted = false;
  55391. this.onAnimationGroupEndObservable.notifyObservers(this);
  55392. }
  55393. };
  55394. // Statics
  55395. /**
  55396. * Returns a new AnimationGroup object parsed from the source provided.
  55397. * @param parsedAnimationGroup defines the source
  55398. * @param scene defines the scene that will receive the animationGroup
  55399. * @returns a new AnimationGroup
  55400. */
  55401. AnimationGroup.Parse = function (parsedAnimationGroup, scene) {
  55402. var animationGroup = new BABYLON.AnimationGroup(parsedAnimationGroup.name, scene);
  55403. for (var i = 0; i < parsedAnimationGroup.targetedAnimations.length; i++) {
  55404. var targetedAnimation = parsedAnimationGroup.targetedAnimations[i];
  55405. var animation = BABYLON.Animation.Parse(targetedAnimation.animation);
  55406. var id = targetedAnimation.targetId;
  55407. if (targetedAnimation.animation.property === "influence") { // morph target animation
  55408. var morphTarget = scene.getMorphTargetById(id);
  55409. if (morphTarget) {
  55410. animationGroup.addTargetedAnimation(animation, morphTarget);
  55411. }
  55412. }
  55413. else {
  55414. var targetNode = scene.getNodeByID(id);
  55415. if (targetNode != null) {
  55416. animationGroup.addTargetedAnimation(animation, targetNode);
  55417. }
  55418. }
  55419. }
  55420. if (parsedAnimationGroup.from !== null && parsedAnimationGroup.from !== null) {
  55421. animationGroup.normalize(parsedAnimationGroup.from, parsedAnimationGroup.to);
  55422. }
  55423. return animationGroup;
  55424. };
  55425. /**
  55426. * Returns the string "AnimationGroup"
  55427. * @returns "AnimationGroup"
  55428. */
  55429. AnimationGroup.prototype.getClassName = function () {
  55430. return "AnimationGroup";
  55431. };
  55432. /**
  55433. * Creates a detailled string about the object
  55434. * @param fullDetails defines if the output string will support multiple levels of logging within scene loading
  55435. * @returns a string representing the object
  55436. */
  55437. AnimationGroup.prototype.toString = function (fullDetails) {
  55438. var ret = "Name: " + this.name;
  55439. ret += ", type: " + this.getClassName();
  55440. if (fullDetails) {
  55441. ret += ", from: " + this._from;
  55442. ret += ", to: " + this._to;
  55443. ret += ", isStarted: " + this._isStarted;
  55444. ret += ", speedRatio: " + this._speedRatio;
  55445. ret += ", targetedAnimations length: " + this._targetedAnimations.length;
  55446. ret += ", animatables length: " + this._animatables;
  55447. }
  55448. return ret;
  55449. };
  55450. return AnimationGroup;
  55451. }());
  55452. BABYLON.AnimationGroup = AnimationGroup;
  55453. })(BABYLON || (BABYLON = {}));
  55454. //# sourceMappingURL=babylon.animationGroup.js.map
  55455. var BABYLON;
  55456. (function (BABYLON) {
  55457. // Static values to help the garbage collector
  55458. // Quaternion
  55459. var _staticOffsetValueQuaternion = Object.freeze(new BABYLON.Quaternion(0, 0, 0, 0));
  55460. // Vector3
  55461. var _staticOffsetValueVector3 = Object.freeze(BABYLON.Vector3.Zero());
  55462. // Vector2
  55463. var _staticOffsetValueVector2 = Object.freeze(BABYLON.Vector2.Zero());
  55464. // Size
  55465. var _staticOffsetValueSize = Object.freeze(BABYLON.Size.Zero());
  55466. // Color3
  55467. var _staticOffsetValueColor3 = Object.freeze(BABYLON.Color3.Black());
  55468. /**
  55469. * Defines a runtime animation
  55470. */
  55471. var RuntimeAnimation = /** @class */ (function () {
  55472. /**
  55473. * Create a new RuntimeAnimation object
  55474. * @param target defines the target of the animation
  55475. * @param animation defines the source animation object
  55476. * @param scene defines the hosting scene
  55477. * @param host defines the initiating Animatable
  55478. */
  55479. function RuntimeAnimation(target, animation, scene, host) {
  55480. var _this = this;
  55481. this._events = new Array();
  55482. /**
  55483. * The current frame of the runtime animation
  55484. */
  55485. this._currentFrame = 0;
  55486. /**
  55487. * The original value of the runtime animation
  55488. */
  55489. this._originalValue = new Array();
  55490. /**
  55491. * The offsets cache of the runtime animation
  55492. */
  55493. this._offsetsCache = {};
  55494. /**
  55495. * The high limits cache of the runtime animation
  55496. */
  55497. this._highLimitsCache = {};
  55498. /**
  55499. * Specifies if the runtime animation has been stopped
  55500. */
  55501. this._stopped = false;
  55502. /**
  55503. * The blending factor of the runtime animation
  55504. */
  55505. this._blendingFactor = 0;
  55506. /**
  55507. * The target path of the runtime animation
  55508. */
  55509. this._targetPath = "";
  55510. /**
  55511. * The weight of the runtime animation
  55512. */
  55513. this._weight = 1.0;
  55514. /**
  55515. * The ratio offset of the runtime animation
  55516. */
  55517. this._ratioOffset = 0;
  55518. /**
  55519. * The previous delay of the runtime animation
  55520. */
  55521. this._previousDelay = 0;
  55522. /**
  55523. * The previous ratio of the runtime animation
  55524. */
  55525. this._previousRatio = 0;
  55526. this._animation = animation;
  55527. this._target = target;
  55528. this._scene = scene;
  55529. this._host = host;
  55530. animation._runtimeAnimations.push(this);
  55531. // Cloning events locally
  55532. var events = animation.getEvents();
  55533. if (events && events.length > 0) {
  55534. events.forEach(function (e) {
  55535. _this._events.push(e._clone());
  55536. });
  55537. }
  55538. }
  55539. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  55540. /**
  55541. * Gets the current frame of the runtime animation
  55542. */
  55543. get: function () {
  55544. return this._currentFrame;
  55545. },
  55546. enumerable: true,
  55547. configurable: true
  55548. });
  55549. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  55550. /**
  55551. * Gets the weight of the runtime animation
  55552. */
  55553. get: function () {
  55554. return this._weight;
  55555. },
  55556. enumerable: true,
  55557. configurable: true
  55558. });
  55559. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  55560. /**
  55561. * Gets the current value of the runtime animation
  55562. */
  55563. get: function () {
  55564. return this._currentValue;
  55565. },
  55566. enumerable: true,
  55567. configurable: true
  55568. });
  55569. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  55570. /**
  55571. * Gets the target path of the runtime animation
  55572. */
  55573. get: function () {
  55574. return this._targetPath;
  55575. },
  55576. enumerable: true,
  55577. configurable: true
  55578. });
  55579. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  55580. /**
  55581. * Gets the actual target of the runtime animation
  55582. */
  55583. get: function () {
  55584. return this._activeTarget;
  55585. },
  55586. enumerable: true,
  55587. configurable: true
  55588. });
  55589. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  55590. /**
  55591. * Gets the animation from the runtime animation
  55592. */
  55593. get: function () {
  55594. return this._animation;
  55595. },
  55596. enumerable: true,
  55597. configurable: true
  55598. });
  55599. /**
  55600. * Resets the runtime animation to the beginning
  55601. * @param restoreOriginal defines whether to restore the target property to the original value
  55602. */
  55603. RuntimeAnimation.prototype.reset = function (restoreOriginal) {
  55604. if (restoreOriginal === void 0) { restoreOriginal = false; }
  55605. if (restoreOriginal) {
  55606. if (this._target instanceof Array) {
  55607. var index = 0;
  55608. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  55609. var target = _a[_i];
  55610. if (this._originalValue[index] !== undefined) {
  55611. this._setValue(target, this._originalValue[index], -1);
  55612. }
  55613. index++;
  55614. }
  55615. }
  55616. else {
  55617. if (this._originalValue[0] !== undefined) {
  55618. this._setValue(this._target, this._originalValue[0], -1);
  55619. }
  55620. }
  55621. }
  55622. this._offsetsCache = {};
  55623. this._highLimitsCache = {};
  55624. this._currentFrame = 0;
  55625. this._blendingFactor = 0;
  55626. this._originalValue = new Array();
  55627. // Events
  55628. for (var index = 0; index < this._events.length; index++) {
  55629. this._events[index].isDone = false;
  55630. }
  55631. };
  55632. /**
  55633. * Specifies if the runtime animation is stopped
  55634. * @returns Boolean specifying if the runtime animation is stopped
  55635. */
  55636. RuntimeAnimation.prototype.isStopped = function () {
  55637. return this._stopped;
  55638. };
  55639. /**
  55640. * Disposes of the runtime animation
  55641. */
  55642. RuntimeAnimation.prototype.dispose = function () {
  55643. var index = this._animation.runtimeAnimations.indexOf(this);
  55644. if (index > -1) {
  55645. this._animation.runtimeAnimations.splice(index, 1);
  55646. }
  55647. };
  55648. /**
  55649. * Interpolates the animation from the current frame
  55650. * @param currentFrame The frame to interpolate the animation to
  55651. * @param repeatCount The number of times that the animation should loop
  55652. * @param loopMode The type of looping mode to use
  55653. * @param offsetValue Animation offset value
  55654. * @param highLimitValue The high limit value
  55655. * @returns The interpolated value
  55656. */
  55657. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  55658. this._currentFrame = currentFrame;
  55659. if (this._animation.dataType === BABYLON.Animation.ANIMATIONTYPE_MATRIX && !this._workValue) {
  55660. this._workValue = BABYLON.Matrix.Zero();
  55661. }
  55662. return this._animation._interpolate(currentFrame, repeatCount, this._workValue, loopMode, offsetValue, highLimitValue);
  55663. };
  55664. /**
  55665. * Apply the interpolated value to the target
  55666. * @param currentValue defines the value computed by the animation
  55667. * @param weight defines the weight to apply to this value (Defaults to 1.0)
  55668. */
  55669. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  55670. if (weight === void 0) { weight = 1.0; }
  55671. if (this._target instanceof Array) {
  55672. var index = 0;
  55673. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  55674. var target = _a[_i];
  55675. this._setValue(target, currentValue, weight, index);
  55676. index++;
  55677. }
  55678. }
  55679. else {
  55680. this._setValue(this._target, currentValue, weight);
  55681. }
  55682. };
  55683. RuntimeAnimation.prototype._setValue = function (target, currentValue, weight, targetIndex) {
  55684. if (targetIndex === void 0) { targetIndex = 0; }
  55685. // Set value
  55686. var path;
  55687. var destination;
  55688. var targetPropertyPath = this._animation.targetPropertyPath;
  55689. if (targetPropertyPath.length > 1) {
  55690. var property = target[targetPropertyPath[0]];
  55691. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  55692. property = property[targetPropertyPath[index]];
  55693. }
  55694. path = targetPropertyPath[targetPropertyPath.length - 1];
  55695. destination = property;
  55696. }
  55697. else {
  55698. path = targetPropertyPath[0];
  55699. destination = target;
  55700. }
  55701. this._targetPath = path;
  55702. this._activeTarget = destination;
  55703. this._weight = weight;
  55704. if (this._originalValue[targetIndex] === undefined) {
  55705. var originalValue = void 0;
  55706. if (destination.getRestPose && path === "_matrix") { // For bones
  55707. originalValue = destination.getRestPose();
  55708. }
  55709. else {
  55710. originalValue = destination[path];
  55711. }
  55712. if (originalValue && originalValue.clone) {
  55713. this._originalValue[targetIndex] = originalValue.clone();
  55714. }
  55715. else {
  55716. this._originalValue[targetIndex] = originalValue;
  55717. }
  55718. }
  55719. // Blending
  55720. var enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  55721. if (enableBlending && this._blendingFactor <= 1.0) {
  55722. if (!this._originalBlendValue) {
  55723. var originalValue = destination[path];
  55724. if (originalValue.clone) {
  55725. this._originalBlendValue = originalValue.clone();
  55726. }
  55727. else {
  55728. this._originalBlendValue = originalValue;
  55729. }
  55730. }
  55731. if (this._originalBlendValue.m) { // Matrix
  55732. if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {
  55733. if (this._currentValue) {
  55734. BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  55735. }
  55736. else {
  55737. this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  55738. }
  55739. }
  55740. else {
  55741. if (this._currentValue) {
  55742. BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  55743. }
  55744. else {
  55745. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  55746. }
  55747. }
  55748. }
  55749. else {
  55750. this._currentValue = BABYLON.Animation._UniversalLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  55751. }
  55752. var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  55753. this._blendingFactor += blendingSpeed;
  55754. }
  55755. else {
  55756. this._currentValue = currentValue;
  55757. }
  55758. if (weight !== -1.0) {
  55759. this._scene._registerTargetForLateAnimationBinding(this, this._originalValue[targetIndex]);
  55760. }
  55761. else {
  55762. destination[path] = this._currentValue;
  55763. }
  55764. if (target.markAsDirty) {
  55765. target.markAsDirty(this._animation.targetProperty);
  55766. }
  55767. };
  55768. /**
  55769. * Gets the loop pmode of the runtime animation
  55770. * @returns Loop Mode
  55771. */
  55772. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  55773. if (this._target && this._target.animationPropertiesOverride) {
  55774. return this._target.animationPropertiesOverride.loopMode;
  55775. }
  55776. return this._animation.loopMode;
  55777. };
  55778. /**
  55779. * Move the current animation to a given frame
  55780. * @param frame defines the frame to move to
  55781. */
  55782. RuntimeAnimation.prototype.goToFrame = function (frame) {
  55783. var keys = this._animation.getKeys();
  55784. if (frame < keys[0].frame) {
  55785. frame = keys[0].frame;
  55786. }
  55787. else if (frame > keys[keys.length - 1].frame) {
  55788. frame = keys[keys.length - 1].frame;
  55789. }
  55790. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  55791. this.setValue(currentValue, -1);
  55792. };
  55793. /**
  55794. * @hidden Internal use only
  55795. */
  55796. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  55797. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  55798. this._ratioOffset = this._previousRatio - newRatio;
  55799. };
  55800. /**
  55801. * Execute the current animation
  55802. * @param delay defines the delay to add to the current frame
  55803. * @param from defines the lower bound of the animation range
  55804. * @param to defines the upper bound of the animation range
  55805. * @param loop defines if the current animation must loop
  55806. * @param speedRatio defines the current speed ratio
  55807. * @param weight defines the weight of the animation (default is -1 so no weight)
  55808. * @param onLoop optional callback called when animation loops
  55809. * @returns a boolean indicating if the animation is running
  55810. */
  55811. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight, onLoop) {
  55812. if (weight === void 0) { weight = -1.0; }
  55813. var targetPropertyPath = this._animation.targetPropertyPath;
  55814. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  55815. this._stopped = true;
  55816. return false;
  55817. }
  55818. var returnValue = true;
  55819. var keys = this._animation.getKeys();
  55820. // Adding a start key at frame 0 if missing
  55821. if (keys[0].frame !== 0) {
  55822. var newKey = { frame: 0, value: keys[0].value };
  55823. keys.splice(0, 0, newKey);
  55824. }
  55825. // Adding a duplicate key when there is only one key at frame zero
  55826. else if (keys.length === 1) {
  55827. var newKey = { frame: 0.001, value: keys[0].value };
  55828. keys.push(newKey);
  55829. }
  55830. // Check limits
  55831. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  55832. from = keys[0].frame;
  55833. }
  55834. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  55835. to = keys[keys.length - 1].frame;
  55836. }
  55837. //to and from cannot be the same key
  55838. if (from === to) {
  55839. if (from > keys[0].frame) {
  55840. from--;
  55841. }
  55842. else if (to < keys[keys.length - 1].frame) {
  55843. to++;
  55844. }
  55845. }
  55846. // Compute ratio
  55847. var range = to - from;
  55848. var offsetValue;
  55849. // ratio represents the frame delta between from and to
  55850. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  55851. var highLimitValue = 0;
  55852. this._previousDelay = delay;
  55853. this._previousRatio = ratio;
  55854. if (((to > from && ratio >= range) || (from > to && ratio <= range)) && !loop) { // If we are out of range and not looping get back to caller
  55855. returnValue = false;
  55856. highLimitValue = this._animation._getKeyValue(keys[keys.length - 1].value);
  55857. }
  55858. else {
  55859. // Get max value if required
  55860. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  55861. var keyOffset = to.toString() + from.toString();
  55862. if (!this._offsetsCache[keyOffset]) {
  55863. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  55864. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  55865. switch (this._animation.dataType) {
  55866. // Float
  55867. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  55868. this._offsetsCache[keyOffset] = toValue - fromValue;
  55869. break;
  55870. // Quaternion
  55871. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  55872. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  55873. break;
  55874. // Vector3
  55875. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  55876. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  55877. // Vector2
  55878. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  55879. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  55880. // Size
  55881. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  55882. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  55883. // Color3
  55884. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  55885. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  55886. default:
  55887. break;
  55888. }
  55889. this._highLimitsCache[keyOffset] = toValue;
  55890. }
  55891. highLimitValue = this._highLimitsCache[keyOffset];
  55892. offsetValue = this._offsetsCache[keyOffset];
  55893. }
  55894. }
  55895. if (offsetValue === undefined) {
  55896. switch (this._animation.dataType) {
  55897. // Float
  55898. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  55899. offsetValue = 0;
  55900. break;
  55901. // Quaternion
  55902. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  55903. offsetValue = _staticOffsetValueQuaternion;
  55904. break;
  55905. // Vector3
  55906. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  55907. offsetValue = _staticOffsetValueVector3;
  55908. break;
  55909. // Vector2
  55910. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  55911. offsetValue = _staticOffsetValueVector2;
  55912. break;
  55913. // Size
  55914. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  55915. offsetValue = _staticOffsetValueSize;
  55916. break;
  55917. // Color3
  55918. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  55919. offsetValue = _staticOffsetValueColor3;
  55920. }
  55921. }
  55922. // Compute value
  55923. var repeatCount = (ratio / range) >> 0;
  55924. var currentFrame = returnValue ? from + ratio % range : to;
  55925. // Need to normalize?
  55926. if (this._host && this._host.syncRoot) {
  55927. var syncRoot = this._host.syncRoot;
  55928. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  55929. currentFrame = from + (to - from) * hostNormalizedFrame;
  55930. }
  55931. // Reset events if looping
  55932. var events = this._events;
  55933. if (range > 0 && this.currentFrame > currentFrame ||
  55934. range < 0 && this.currentFrame < currentFrame) {
  55935. if (onLoop) {
  55936. onLoop();
  55937. }
  55938. // Need to reset animation events
  55939. for (var index = 0; index < events.length; index++) {
  55940. if (!events[index].onlyOnce) {
  55941. // reset event, the animation is looping
  55942. events[index].isDone = false;
  55943. }
  55944. }
  55945. }
  55946. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  55947. // Set value
  55948. this.setValue(currentValue, weight);
  55949. // Check events
  55950. for (var index = 0; index < events.length; index++) {
  55951. // Make sure current frame has passed event frame and that event frame is within the current range
  55952. // Also, handle both forward and reverse animations
  55953. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  55954. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  55955. var event = events[index];
  55956. if (!event.isDone) {
  55957. // If event should be done only once, remove it.
  55958. if (event.onlyOnce) {
  55959. events.splice(index, 1);
  55960. index--;
  55961. }
  55962. event.isDone = true;
  55963. event.action(currentFrame);
  55964. } // Don't do anything if the event has already be done.
  55965. }
  55966. }
  55967. if (!returnValue) {
  55968. this._stopped = true;
  55969. }
  55970. return returnValue;
  55971. };
  55972. return RuntimeAnimation;
  55973. }());
  55974. BABYLON.RuntimeAnimation = RuntimeAnimation;
  55975. })(BABYLON || (BABYLON = {}));
  55976. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  55977. var BABYLON;
  55978. (function (BABYLON) {
  55979. /**
  55980. * Class used to store an actual running animation
  55981. */
  55982. var Animatable = /** @class */ (function () {
  55983. /**
  55984. * Creates a new Animatable
  55985. * @param scene defines the hosting scene
  55986. * @param target defines the target object
  55987. * @param fromFrame defines the starting frame number (default is 0)
  55988. * @param toFrame defines the ending frame number (default is 100)
  55989. * @param loopAnimation defines if the animation must loop (default is false)
  55990. * @param speedRatio defines the factor to apply to animation speed (default is 1)
  55991. * @param onAnimationEnd defines a callback to call when animation ends if it is not looping
  55992. * @param animations defines a group of animation to add to the new Animatable
  55993. * @param onAnimationLoop defines a callback to call when animation loops
  55994. */
  55995. function Animatable(scene,
  55996. /** defines the target object */
  55997. target,
  55998. /** defines the starting frame number (default is 0) */
  55999. fromFrame,
  56000. /** defines the ending frame number (default is 100) */
  56001. toFrame,
  56002. /** defines if the animation must loop (default is false) */
  56003. loopAnimation, speedRatio,
  56004. /** defines a callback to call when animation ends if it is not looping */
  56005. onAnimationEnd, animations,
  56006. /** defines a callback to call when animation loops */
  56007. onAnimationLoop) {
  56008. if (fromFrame === void 0) { fromFrame = 0; }
  56009. if (toFrame === void 0) { toFrame = 100; }
  56010. if (loopAnimation === void 0) { loopAnimation = false; }
  56011. if (speedRatio === void 0) { speedRatio = 1.0; }
  56012. this.target = target;
  56013. this.fromFrame = fromFrame;
  56014. this.toFrame = toFrame;
  56015. this.loopAnimation = loopAnimation;
  56016. this.onAnimationEnd = onAnimationEnd;
  56017. this.onAnimationLoop = onAnimationLoop;
  56018. this._localDelayOffset = null;
  56019. this._pausedDelay = null;
  56020. this._runtimeAnimations = new Array();
  56021. this._paused = false;
  56022. this._speedRatio = 1;
  56023. this._weight = -1.0;
  56024. /**
  56025. * Gets or sets a boolean indicating if the animatable must be disposed and removed at the end of the animation.
  56026. * This will only apply for non looping animation (default is true)
  56027. */
  56028. this.disposeOnEnd = true;
  56029. /**
  56030. * Gets a boolean indicating if the animation has started
  56031. */
  56032. this.animationStarted = false;
  56033. /**
  56034. * Observer raised when the animation ends
  56035. */
  56036. this.onAnimationEndObservable = new BABYLON.Observable();
  56037. /**
  56038. * Observer raised when the animation loops
  56039. */
  56040. this.onAnimationLoopObservable = new BABYLON.Observable();
  56041. this._scene = scene;
  56042. if (animations) {
  56043. this.appendAnimations(target, animations);
  56044. }
  56045. this._speedRatio = speedRatio;
  56046. scene._activeAnimatables.push(this);
  56047. }
  56048. Object.defineProperty(Animatable.prototype, "syncRoot", {
  56049. /**
  56050. * Gets the root Animatable used to synchronize and normalize animations
  56051. */
  56052. get: function () {
  56053. return this._syncRoot;
  56054. },
  56055. enumerable: true,
  56056. configurable: true
  56057. });
  56058. Object.defineProperty(Animatable.prototype, "masterFrame", {
  56059. /**
  56060. * Gets the current frame of the first RuntimeAnimation
  56061. * Used to synchronize Animatables
  56062. */
  56063. get: function () {
  56064. if (this._runtimeAnimations.length === 0) {
  56065. return 0;
  56066. }
  56067. return this._runtimeAnimations[0].currentFrame;
  56068. },
  56069. enumerable: true,
  56070. configurable: true
  56071. });
  56072. Object.defineProperty(Animatable.prototype, "weight", {
  56073. /**
  56074. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  56075. */
  56076. get: function () {
  56077. return this._weight;
  56078. },
  56079. set: function (value) {
  56080. if (value === -1) { // -1 is ok and means no weight
  56081. this._weight = -1;
  56082. return;
  56083. }
  56084. // Else weight must be in [0, 1] range
  56085. this._weight = Math.min(Math.max(value, 0), 1.0);
  56086. },
  56087. enumerable: true,
  56088. configurable: true
  56089. });
  56090. Object.defineProperty(Animatable.prototype, "speedRatio", {
  56091. /**
  56092. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  56093. */
  56094. get: function () {
  56095. return this._speedRatio;
  56096. },
  56097. set: function (value) {
  56098. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  56099. var animation = this._runtimeAnimations[index];
  56100. animation._prepareForSpeedRatioChange(value);
  56101. }
  56102. this._speedRatio = value;
  56103. },
  56104. enumerable: true,
  56105. configurable: true
  56106. });
  56107. // Methods
  56108. /**
  56109. * Synchronize and normalize current Animatable with a source Animatable
  56110. * This is useful when using animation weights and when animations are not of the same length
  56111. * @param root defines the root Animatable to synchronize with
  56112. * @returns the current Animatable
  56113. */
  56114. Animatable.prototype.syncWith = function (root) {
  56115. this._syncRoot = root;
  56116. if (root) {
  56117. // Make sure this animatable will animate after the root
  56118. var index = this._scene._activeAnimatables.indexOf(this);
  56119. if (index > -1) {
  56120. this._scene._activeAnimatables.splice(index, 1);
  56121. this._scene._activeAnimatables.push(this);
  56122. }
  56123. }
  56124. return this;
  56125. };
  56126. /**
  56127. * Gets the list of runtime animations
  56128. * @returns an array of RuntimeAnimation
  56129. */
  56130. Animatable.prototype.getAnimations = function () {
  56131. return this._runtimeAnimations;
  56132. };
  56133. /**
  56134. * Adds more animations to the current animatable
  56135. * @param target defines the target of the animations
  56136. * @param animations defines the new animations to add
  56137. */
  56138. Animatable.prototype.appendAnimations = function (target, animations) {
  56139. for (var index = 0; index < animations.length; index++) {
  56140. var animation = animations[index];
  56141. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  56142. }
  56143. };
  56144. /**
  56145. * Gets the source animation for a specific property
  56146. * @param property defines the propertyu to look for
  56147. * @returns null or the source animation for the given property
  56148. */
  56149. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  56150. var runtimeAnimations = this._runtimeAnimations;
  56151. for (var index = 0; index < runtimeAnimations.length; index++) {
  56152. if (runtimeAnimations[index].animation.targetProperty === property) {
  56153. return runtimeAnimations[index].animation;
  56154. }
  56155. }
  56156. return null;
  56157. };
  56158. /**
  56159. * Gets the runtime animation for a specific property
  56160. * @param property defines the propertyu to look for
  56161. * @returns null or the runtime animation for the given property
  56162. */
  56163. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  56164. var runtimeAnimations = this._runtimeAnimations;
  56165. for (var index = 0; index < runtimeAnimations.length; index++) {
  56166. if (runtimeAnimations[index].animation.targetProperty === property) {
  56167. return runtimeAnimations[index];
  56168. }
  56169. }
  56170. return null;
  56171. };
  56172. /**
  56173. * Resets the animatable to its original state
  56174. */
  56175. Animatable.prototype.reset = function () {
  56176. var runtimeAnimations = this._runtimeAnimations;
  56177. for (var index = 0; index < runtimeAnimations.length; index++) {
  56178. runtimeAnimations[index].reset(true);
  56179. }
  56180. this._localDelayOffset = null;
  56181. this._pausedDelay = null;
  56182. };
  56183. /**
  56184. * Allows the animatable to blend with current running animations
  56185. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  56186. * @param blendingSpeed defines the blending speed to use
  56187. */
  56188. Animatable.prototype.enableBlending = function (blendingSpeed) {
  56189. var runtimeAnimations = this._runtimeAnimations;
  56190. for (var index = 0; index < runtimeAnimations.length; index++) {
  56191. runtimeAnimations[index].animation.enableBlending = true;
  56192. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  56193. }
  56194. };
  56195. /**
  56196. * Disable animation blending
  56197. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  56198. */
  56199. Animatable.prototype.disableBlending = function () {
  56200. var runtimeAnimations = this._runtimeAnimations;
  56201. for (var index = 0; index < runtimeAnimations.length; index++) {
  56202. runtimeAnimations[index].animation.enableBlending = false;
  56203. }
  56204. };
  56205. /**
  56206. * Jump directly to a given frame
  56207. * @param frame defines the frame to jump to
  56208. */
  56209. Animatable.prototype.goToFrame = function (frame) {
  56210. var runtimeAnimations = this._runtimeAnimations;
  56211. if (runtimeAnimations[0]) {
  56212. var fps = runtimeAnimations[0].animation.framePerSecond;
  56213. var currentFrame = runtimeAnimations[0].currentFrame;
  56214. var adjustTime = frame - currentFrame;
  56215. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  56216. if (this._localDelayOffset === null) {
  56217. this._localDelayOffset = 0;
  56218. }
  56219. this._localDelayOffset -= delay;
  56220. }
  56221. for (var index = 0; index < runtimeAnimations.length; index++) {
  56222. runtimeAnimations[index].goToFrame(frame);
  56223. }
  56224. };
  56225. /**
  56226. * Pause the animation
  56227. */
  56228. Animatable.prototype.pause = function () {
  56229. if (this._paused) {
  56230. return;
  56231. }
  56232. this._paused = true;
  56233. };
  56234. /**
  56235. * Restart the animation
  56236. */
  56237. Animatable.prototype.restart = function () {
  56238. this._paused = false;
  56239. };
  56240. Animatable.prototype._raiseOnAnimationEnd = function () {
  56241. if (this.onAnimationEnd) {
  56242. this.onAnimationEnd();
  56243. }
  56244. this.onAnimationEndObservable.notifyObservers(this);
  56245. };
  56246. /**
  56247. * Stop and delete the current animation
  56248. * @param animationName defines a string used to only stop some of the runtime animations instead of all
  56249. * @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)
  56250. */
  56251. Animatable.prototype.stop = function (animationName, targetMask) {
  56252. if (animationName || targetMask) {
  56253. var idx = this._scene._activeAnimatables.indexOf(this);
  56254. if (idx > -1) {
  56255. var runtimeAnimations = this._runtimeAnimations;
  56256. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  56257. var runtimeAnimation = runtimeAnimations[index];
  56258. if (animationName && runtimeAnimation.animation.name != animationName) {
  56259. continue;
  56260. }
  56261. if (targetMask && !targetMask(runtimeAnimation.target)) {
  56262. continue;
  56263. }
  56264. runtimeAnimation.dispose();
  56265. runtimeAnimations.splice(index, 1);
  56266. }
  56267. if (runtimeAnimations.length == 0) {
  56268. this._scene._activeAnimatables.splice(idx, 1);
  56269. this._raiseOnAnimationEnd();
  56270. }
  56271. }
  56272. }
  56273. else {
  56274. var index = this._scene._activeAnimatables.indexOf(this);
  56275. if (index > -1) {
  56276. this._scene._activeAnimatables.splice(index, 1);
  56277. var runtimeAnimations = this._runtimeAnimations;
  56278. for (var index = 0; index < runtimeAnimations.length; index++) {
  56279. runtimeAnimations[index].dispose();
  56280. }
  56281. this._raiseOnAnimationEnd();
  56282. }
  56283. }
  56284. };
  56285. /**
  56286. * Wait asynchronously for the animation to end
  56287. * @returns a promise which will be fullfilled when the animation ends
  56288. */
  56289. Animatable.prototype.waitAsync = function () {
  56290. var _this = this;
  56291. return new Promise(function (resolve, reject) {
  56292. _this.onAnimationEndObservable.add(function () {
  56293. resolve(_this);
  56294. }, undefined, undefined, _this, true);
  56295. });
  56296. };
  56297. /** @hidden */
  56298. Animatable.prototype._animate = function (delay) {
  56299. var _this = this;
  56300. if (this._paused) {
  56301. this.animationStarted = false;
  56302. if (this._pausedDelay === null) {
  56303. this._pausedDelay = delay;
  56304. }
  56305. return true;
  56306. }
  56307. if (this._localDelayOffset === null) {
  56308. this._localDelayOffset = delay;
  56309. this._pausedDelay = null;
  56310. }
  56311. else if (this._pausedDelay !== null) {
  56312. this._localDelayOffset += delay - this._pausedDelay;
  56313. this._pausedDelay = null;
  56314. }
  56315. if (this._weight === 0) { // We consider that an animation with a weight === 0 is "actively" paused
  56316. return true;
  56317. }
  56318. // Animating
  56319. var running = false;
  56320. var runtimeAnimations = this._runtimeAnimations;
  56321. var index;
  56322. for (index = 0; index < runtimeAnimations.length; index++) {
  56323. var animation = runtimeAnimations[index];
  56324. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight, function () {
  56325. _this.onAnimationLoopObservable.notifyObservers(_this);
  56326. if (_this.onAnimationLoop) {
  56327. _this.onAnimationLoop();
  56328. }
  56329. });
  56330. running = running || isRunning;
  56331. }
  56332. this.animationStarted = running;
  56333. if (!running) {
  56334. if (this.disposeOnEnd) {
  56335. // Remove from active animatables
  56336. index = this._scene._activeAnimatables.indexOf(this);
  56337. this._scene._activeAnimatables.splice(index, 1);
  56338. // Dispose all runtime animations
  56339. for (index = 0; index < runtimeAnimations.length; index++) {
  56340. runtimeAnimations[index].dispose();
  56341. }
  56342. }
  56343. this._raiseOnAnimationEnd();
  56344. if (this.disposeOnEnd) {
  56345. this.onAnimationEnd = null;
  56346. this.onAnimationLoop = null;
  56347. this.onAnimationLoopObservable.clear();
  56348. this.onAnimationEndObservable.clear();
  56349. }
  56350. }
  56351. return running;
  56352. };
  56353. return Animatable;
  56354. }());
  56355. BABYLON.Animatable = Animatable;
  56356. })(BABYLON || (BABYLON = {}));
  56357. //# sourceMappingURL=babylon.animatable.js.map
  56358. var BABYLON;
  56359. (function (BABYLON) {
  56360. /**
  56361. * Base class used for every default easing function.
  56362. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  56363. */
  56364. var EasingFunction = /** @class */ (function () {
  56365. function EasingFunction() {
  56366. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  56367. }
  56368. /**
  56369. * Sets the easing mode of the current function.
  56370. * @param easingMode Defines the willing mode (EASINGMODE_EASEIN, EASINGMODE_EASEOUT or EASINGMODE_EASEINOUT)
  56371. */
  56372. EasingFunction.prototype.setEasingMode = function (easingMode) {
  56373. var n = Math.min(Math.max(easingMode, 0), 2);
  56374. this._easingMode = n;
  56375. };
  56376. /**
  56377. * Gets the current easing mode.
  56378. * @returns the easing mode
  56379. */
  56380. EasingFunction.prototype.getEasingMode = function () {
  56381. return this._easingMode;
  56382. };
  56383. /**
  56384. * @hidden
  56385. */
  56386. EasingFunction.prototype.easeInCore = function (gradient) {
  56387. throw new Error('You must implement this method');
  56388. };
  56389. /**
  56390. * Given an input gradient between 0 and 1, this returns the corrseponding value
  56391. * of the easing function.
  56392. * @param gradient Defines the value between 0 and 1 we want the easing value for
  56393. * @returns the corresponding value on the curve defined by the easing function
  56394. */
  56395. EasingFunction.prototype.ease = function (gradient) {
  56396. switch (this._easingMode) {
  56397. case EasingFunction.EASINGMODE_EASEIN:
  56398. return this.easeInCore(gradient);
  56399. case EasingFunction.EASINGMODE_EASEOUT:
  56400. return (1 - this.easeInCore(1 - gradient));
  56401. }
  56402. if (gradient >= 0.5) {
  56403. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  56404. }
  56405. return (this.easeInCore(gradient * 2) * 0.5);
  56406. };
  56407. /**
  56408. * Interpolation follows the mathematical formula associated with the easing function.
  56409. */
  56410. EasingFunction.EASINGMODE_EASEIN = 0;
  56411. /**
  56412. * Interpolation follows 100% interpolation minus the output of the formula associated with the easing function.
  56413. */
  56414. EasingFunction.EASINGMODE_EASEOUT = 1;
  56415. /**
  56416. * Interpolation uses EaseIn for the first half of the animation and EaseOut for the second half.
  56417. */
  56418. EasingFunction.EASINGMODE_EASEINOUT = 2;
  56419. return EasingFunction;
  56420. }());
  56421. BABYLON.EasingFunction = EasingFunction;
  56422. /**
  56423. * Easing function with a circle shape (see link below).
  56424. * @see https://easings.net/#easeInCirc
  56425. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  56426. */
  56427. var CircleEase = /** @class */ (function (_super) {
  56428. __extends(CircleEase, _super);
  56429. function CircleEase() {
  56430. return _super !== null && _super.apply(this, arguments) || this;
  56431. }
  56432. /** @hidden */
  56433. CircleEase.prototype.easeInCore = function (gradient) {
  56434. gradient = Math.max(0, Math.min(1, gradient));
  56435. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  56436. };
  56437. return CircleEase;
  56438. }(EasingFunction));
  56439. BABYLON.CircleEase = CircleEase;
  56440. /**
  56441. * Easing function with a ease back shape (see link below).
  56442. * @see https://easings.net/#easeInBack
  56443. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  56444. */
  56445. var BackEase = /** @class */ (function (_super) {
  56446. __extends(BackEase, _super);
  56447. /**
  56448. * Instantiates a back ease easing
  56449. * @see https://easings.net/#easeInBack
  56450. * @param amplitude Defines the amplitude of the function
  56451. */
  56452. function BackEase(
  56453. /** Defines the amplitude of the function */
  56454. amplitude) {
  56455. if (amplitude === void 0) { amplitude = 1; }
  56456. var _this = _super.call(this) || this;
  56457. _this.amplitude = amplitude;
  56458. return _this;
  56459. }
  56460. /** @hidden */
  56461. BackEase.prototype.easeInCore = function (gradient) {
  56462. var num = Math.max(0, this.amplitude);
  56463. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  56464. };
  56465. return BackEase;
  56466. }(EasingFunction));
  56467. BABYLON.BackEase = BackEase;
  56468. /**
  56469. * Easing function with a bouncing shape (see link below).
  56470. * @see https://easings.net/#easeInBounce
  56471. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  56472. */
  56473. var BounceEase = /** @class */ (function (_super) {
  56474. __extends(BounceEase, _super);
  56475. /**
  56476. * Instantiates a bounce easing
  56477. * @see https://easings.net/#easeInBounce
  56478. * @param bounces Defines the number of bounces
  56479. * @param bounciness Defines the amplitude of the bounce
  56480. */
  56481. function BounceEase(
  56482. /** Defines the number of bounces */
  56483. bounces,
  56484. /** Defines the amplitude of the bounce */
  56485. bounciness) {
  56486. if (bounces === void 0) { bounces = 3; }
  56487. if (bounciness === void 0) { bounciness = 2; }
  56488. var _this = _super.call(this) || this;
  56489. _this.bounces = bounces;
  56490. _this.bounciness = bounciness;
  56491. return _this;
  56492. }
  56493. /** @hidden */
  56494. BounceEase.prototype.easeInCore = function (gradient) {
  56495. var y = Math.max(0.0, this.bounces);
  56496. var bounciness = this.bounciness;
  56497. if (bounciness <= 1.0) {
  56498. bounciness = 1.001;
  56499. }
  56500. var num9 = Math.pow(bounciness, y);
  56501. var num5 = 1.0 - bounciness;
  56502. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  56503. var num15 = gradient * num4;
  56504. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  56505. var num3 = Math.floor(num65);
  56506. var num13 = num3 + 1.0;
  56507. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  56508. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  56509. var num7 = (num8 + num12) * 0.5;
  56510. var num6 = gradient - num7;
  56511. var num2 = num7 - num8;
  56512. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  56513. };
  56514. return BounceEase;
  56515. }(EasingFunction));
  56516. BABYLON.BounceEase = BounceEase;
  56517. /**
  56518. * Easing function with a power of 3 shape (see link below).
  56519. * @see https://easings.net/#easeInCubic
  56520. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  56521. */
  56522. var CubicEase = /** @class */ (function (_super) {
  56523. __extends(CubicEase, _super);
  56524. function CubicEase() {
  56525. return _super !== null && _super.apply(this, arguments) || this;
  56526. }
  56527. /** @hidden */
  56528. CubicEase.prototype.easeInCore = function (gradient) {
  56529. return (gradient * gradient * gradient);
  56530. };
  56531. return CubicEase;
  56532. }(EasingFunction));
  56533. BABYLON.CubicEase = CubicEase;
  56534. /**
  56535. * Easing function with an elastic shape (see link below).
  56536. * @see https://easings.net/#easeInElastic
  56537. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  56538. */
  56539. var ElasticEase = /** @class */ (function (_super) {
  56540. __extends(ElasticEase, _super);
  56541. /**
  56542. * Instantiates an elastic easing function
  56543. * @see https://easings.net/#easeInElastic
  56544. * @param oscillations Defines the number of oscillations
  56545. * @param springiness Defines the amplitude of the oscillations
  56546. */
  56547. function ElasticEase(
  56548. /** Defines the number of oscillations*/
  56549. oscillations,
  56550. /** Defines the amplitude of the oscillations*/
  56551. springiness) {
  56552. if (oscillations === void 0) { oscillations = 3; }
  56553. if (springiness === void 0) { springiness = 3; }
  56554. var _this = _super.call(this) || this;
  56555. _this.oscillations = oscillations;
  56556. _this.springiness = springiness;
  56557. return _this;
  56558. }
  56559. /** @hidden */
  56560. ElasticEase.prototype.easeInCore = function (gradient) {
  56561. var num2;
  56562. var num3 = Math.max(0.0, this.oscillations);
  56563. var num = Math.max(0.0, this.springiness);
  56564. if (num == 0) {
  56565. num2 = gradient;
  56566. }
  56567. else {
  56568. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  56569. }
  56570. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  56571. };
  56572. return ElasticEase;
  56573. }(EasingFunction));
  56574. BABYLON.ElasticEase = ElasticEase;
  56575. /**
  56576. * Easing function with an exponential shape (see link below).
  56577. * @see https://easings.net/#easeInExpo
  56578. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  56579. */
  56580. var ExponentialEase = /** @class */ (function (_super) {
  56581. __extends(ExponentialEase, _super);
  56582. /**
  56583. * Instantiates an exponential easing function
  56584. * @see https://easings.net/#easeInExpo
  56585. * @param exponent Defines the exponent of the function
  56586. */
  56587. function ExponentialEase(
  56588. /** Defines the exponent of the function */
  56589. exponent) {
  56590. if (exponent === void 0) { exponent = 2; }
  56591. var _this = _super.call(this) || this;
  56592. _this.exponent = exponent;
  56593. return _this;
  56594. }
  56595. /** @hidden */
  56596. ExponentialEase.prototype.easeInCore = function (gradient) {
  56597. if (this.exponent <= 0) {
  56598. return gradient;
  56599. }
  56600. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  56601. };
  56602. return ExponentialEase;
  56603. }(EasingFunction));
  56604. BABYLON.ExponentialEase = ExponentialEase;
  56605. /**
  56606. * Easing function with a power shape (see link below).
  56607. * @see https://easings.net/#easeInQuad
  56608. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  56609. */
  56610. var PowerEase = /** @class */ (function (_super) {
  56611. __extends(PowerEase, _super);
  56612. /**
  56613. * Instantiates an power base easing function
  56614. * @see https://easings.net/#easeInQuad
  56615. * @param power Defines the power of the function
  56616. */
  56617. function PowerEase(
  56618. /** Defines the power of the function */
  56619. power) {
  56620. if (power === void 0) { power = 2; }
  56621. var _this = _super.call(this) || this;
  56622. _this.power = power;
  56623. return _this;
  56624. }
  56625. /** @hidden */
  56626. PowerEase.prototype.easeInCore = function (gradient) {
  56627. var y = Math.max(0.0, this.power);
  56628. return Math.pow(gradient, y);
  56629. };
  56630. return PowerEase;
  56631. }(EasingFunction));
  56632. BABYLON.PowerEase = PowerEase;
  56633. /**
  56634. * Easing function with a power of 2 shape (see link below).
  56635. * @see https://easings.net/#easeInQuad
  56636. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  56637. */
  56638. var QuadraticEase = /** @class */ (function (_super) {
  56639. __extends(QuadraticEase, _super);
  56640. function QuadraticEase() {
  56641. return _super !== null && _super.apply(this, arguments) || this;
  56642. }
  56643. /** @hidden */
  56644. QuadraticEase.prototype.easeInCore = function (gradient) {
  56645. return (gradient * gradient);
  56646. };
  56647. return QuadraticEase;
  56648. }(EasingFunction));
  56649. BABYLON.QuadraticEase = QuadraticEase;
  56650. /**
  56651. * Easing function with a power of 4 shape (see link below).
  56652. * @see https://easings.net/#easeInQuart
  56653. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  56654. */
  56655. var QuarticEase = /** @class */ (function (_super) {
  56656. __extends(QuarticEase, _super);
  56657. function QuarticEase() {
  56658. return _super !== null && _super.apply(this, arguments) || this;
  56659. }
  56660. /** @hidden */
  56661. QuarticEase.prototype.easeInCore = function (gradient) {
  56662. return (gradient * gradient * gradient * gradient);
  56663. };
  56664. return QuarticEase;
  56665. }(EasingFunction));
  56666. BABYLON.QuarticEase = QuarticEase;
  56667. /**
  56668. * Easing function with a power of 5 shape (see link below).
  56669. * @see https://easings.net/#easeInQuint
  56670. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  56671. */
  56672. var QuinticEase = /** @class */ (function (_super) {
  56673. __extends(QuinticEase, _super);
  56674. function QuinticEase() {
  56675. return _super !== null && _super.apply(this, arguments) || this;
  56676. }
  56677. /** @hidden */
  56678. QuinticEase.prototype.easeInCore = function (gradient) {
  56679. return (gradient * gradient * gradient * gradient * gradient);
  56680. };
  56681. return QuinticEase;
  56682. }(EasingFunction));
  56683. BABYLON.QuinticEase = QuinticEase;
  56684. /**
  56685. * Easing function with a sin shape (see link below).
  56686. * @see https://easings.net/#easeInSine
  56687. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  56688. */
  56689. var SineEase = /** @class */ (function (_super) {
  56690. __extends(SineEase, _super);
  56691. function SineEase() {
  56692. return _super !== null && _super.apply(this, arguments) || this;
  56693. }
  56694. /** @hidden */
  56695. SineEase.prototype.easeInCore = function (gradient) {
  56696. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  56697. };
  56698. return SineEase;
  56699. }(EasingFunction));
  56700. BABYLON.SineEase = SineEase;
  56701. /**
  56702. * Easing function with a bezier shape (see link below).
  56703. * @see http://cubic-bezier.com/#.17,.67,.83,.67
  56704. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  56705. */
  56706. var BezierCurveEase = /** @class */ (function (_super) {
  56707. __extends(BezierCurveEase, _super);
  56708. /**
  56709. * Instantiates a bezier function
  56710. * @see http://cubic-bezier.com/#.17,.67,.83,.67
  56711. * @param x1 Defines the x component of the start tangent in the bezier curve
  56712. * @param y1 Defines the y component of the start tangent in the bezier curve
  56713. * @param x2 Defines the x component of the end tangent in the bezier curve
  56714. * @param y2 Defines the y component of the end tangent in the bezier curve
  56715. */
  56716. function BezierCurveEase(
  56717. /** Defines the x component of the start tangent in the bezier curve */
  56718. x1,
  56719. /** Defines the y component of the start tangent in the bezier curve */
  56720. y1,
  56721. /** Defines the x component of the end tangent in the bezier curve */
  56722. x2,
  56723. /** Defines the y component of the end tangent in the bezier curve */
  56724. y2) {
  56725. if (x1 === void 0) { x1 = 0; }
  56726. if (y1 === void 0) { y1 = 0; }
  56727. if (x2 === void 0) { x2 = 1; }
  56728. if (y2 === void 0) { y2 = 1; }
  56729. var _this = _super.call(this) || this;
  56730. _this.x1 = x1;
  56731. _this.y1 = y1;
  56732. _this.x2 = x2;
  56733. _this.y2 = y2;
  56734. return _this;
  56735. }
  56736. /** @hidden */
  56737. BezierCurveEase.prototype.easeInCore = function (gradient) {
  56738. return BABYLON.BezierCurve.Interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  56739. };
  56740. return BezierCurveEase;
  56741. }(EasingFunction));
  56742. BABYLON.BezierCurveEase = BezierCurveEase;
  56743. })(BABYLON || (BABYLON = {}));
  56744. //# sourceMappingURL=babylon.easing.js.map
  56745. var BABYLON;
  56746. (function (BABYLON) {
  56747. /**
  56748. * A Condition applied to an Action
  56749. */
  56750. var Condition = /** @class */ (function () {
  56751. /**
  56752. * Creates a new Condition
  56753. * @param actionManager the manager of the action the condition is applied to
  56754. */
  56755. function Condition(actionManager) {
  56756. this._actionManager = actionManager;
  56757. }
  56758. /**
  56759. * Check if the current condition is valid
  56760. * @returns a boolean
  56761. */
  56762. Condition.prototype.isValid = function () {
  56763. return true;
  56764. };
  56765. /**
  56766. * Internal only
  56767. * @hidden
  56768. */
  56769. Condition.prototype._getProperty = function (propertyPath) {
  56770. return this._actionManager._getProperty(propertyPath);
  56771. };
  56772. /**
  56773. * Internal only
  56774. * @hidden
  56775. */
  56776. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  56777. return this._actionManager._getEffectiveTarget(target, propertyPath);
  56778. };
  56779. /**
  56780. * Serialize placeholder for child classes
  56781. * @returns the serialized object
  56782. */
  56783. Condition.prototype.serialize = function () {
  56784. };
  56785. /**
  56786. * Internal only
  56787. * @hidden
  56788. */
  56789. Condition.prototype._serialize = function (serializedCondition) {
  56790. return {
  56791. type: 2,
  56792. children: [],
  56793. name: serializedCondition.name,
  56794. properties: serializedCondition.properties
  56795. };
  56796. };
  56797. return Condition;
  56798. }());
  56799. BABYLON.Condition = Condition;
  56800. /**
  56801. * Defines specific conditional operators as extensions of Condition
  56802. */
  56803. var ValueCondition = /** @class */ (function (_super) {
  56804. __extends(ValueCondition, _super);
  56805. /**
  56806. * Creates a new ValueCondition
  56807. * @param actionManager manager for the action the condition applies to
  56808. * @param target for the action
  56809. * @param propertyPath path to specify the property of the target the conditional operator uses
  56810. * @param value the value compared by the conditional operator against the current value of the property
  56811. * @param operator the conditional operator, default ValueCondition.IsEqual
  56812. */
  56813. function ValueCondition(actionManager, target,
  56814. /** path to specify the property of the target the conditional operator uses */
  56815. propertyPath,
  56816. /** the value compared by the conditional operator against the current value of the property */
  56817. value,
  56818. /** the conditional operator, default ValueCondition.IsEqual */
  56819. operator) {
  56820. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  56821. var _this = _super.call(this, actionManager) || this;
  56822. _this.propertyPath = propertyPath;
  56823. _this.value = value;
  56824. _this.operator = operator;
  56825. _this._target = target;
  56826. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  56827. _this._property = _this._getProperty(_this.propertyPath);
  56828. return _this;
  56829. }
  56830. Object.defineProperty(ValueCondition, "IsEqual", {
  56831. /**
  56832. * returns the number for IsEqual
  56833. */
  56834. get: function () {
  56835. return ValueCondition._IsEqual;
  56836. },
  56837. enumerable: true,
  56838. configurable: true
  56839. });
  56840. Object.defineProperty(ValueCondition, "IsDifferent", {
  56841. /**
  56842. * Returns the number for IsDifferent
  56843. */
  56844. get: function () {
  56845. return ValueCondition._IsDifferent;
  56846. },
  56847. enumerable: true,
  56848. configurable: true
  56849. });
  56850. Object.defineProperty(ValueCondition, "IsGreater", {
  56851. /**
  56852. * Returns the number for IsGreater
  56853. */
  56854. get: function () {
  56855. return ValueCondition._IsGreater;
  56856. },
  56857. enumerable: true,
  56858. configurable: true
  56859. });
  56860. Object.defineProperty(ValueCondition, "IsLesser", {
  56861. /**
  56862. * Returns the number for IsLesser
  56863. */
  56864. get: function () {
  56865. return ValueCondition._IsLesser;
  56866. },
  56867. enumerable: true,
  56868. configurable: true
  56869. });
  56870. /**
  56871. * Compares the given value with the property value for the specified conditional operator
  56872. * @returns the result of the comparison
  56873. */
  56874. ValueCondition.prototype.isValid = function () {
  56875. switch (this.operator) {
  56876. case ValueCondition.IsGreater:
  56877. return this._effectiveTarget[this._property] > this.value;
  56878. case ValueCondition.IsLesser:
  56879. return this._effectiveTarget[this._property] < this.value;
  56880. case ValueCondition.IsEqual:
  56881. case ValueCondition.IsDifferent:
  56882. var check;
  56883. if (this.value.equals) {
  56884. check = this.value.equals(this._effectiveTarget[this._property]);
  56885. }
  56886. else {
  56887. check = this.value === this._effectiveTarget[this._property];
  56888. }
  56889. return this.operator === ValueCondition.IsEqual ? check : !check;
  56890. }
  56891. return false;
  56892. };
  56893. /**
  56894. * Serialize the ValueCondition into a JSON compatible object
  56895. * @returns serialization object
  56896. */
  56897. ValueCondition.prototype.serialize = function () {
  56898. return this._serialize({
  56899. name: "ValueCondition",
  56900. properties: [
  56901. BABYLON.Action._GetTargetProperty(this._target),
  56902. { name: "propertyPath", value: this.propertyPath },
  56903. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  56904. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  56905. ]
  56906. });
  56907. };
  56908. /**
  56909. * Gets the name of the conditional operator for the ValueCondition
  56910. * @param operator the conditional operator
  56911. * @returns the name
  56912. */
  56913. ValueCondition.GetOperatorName = function (operator) {
  56914. switch (operator) {
  56915. case ValueCondition._IsEqual: return "IsEqual";
  56916. case ValueCondition._IsDifferent: return "IsDifferent";
  56917. case ValueCondition._IsGreater: return "IsGreater";
  56918. case ValueCondition._IsLesser: return "IsLesser";
  56919. default: return "";
  56920. }
  56921. };
  56922. /**
  56923. * Internal only
  56924. * @hidden
  56925. */
  56926. ValueCondition._IsEqual = 0;
  56927. /**
  56928. * Internal only
  56929. * @hidden
  56930. */
  56931. ValueCondition._IsDifferent = 1;
  56932. /**
  56933. * Internal only
  56934. * @hidden
  56935. */
  56936. ValueCondition._IsGreater = 2;
  56937. /**
  56938. * Internal only
  56939. * @hidden
  56940. */
  56941. ValueCondition._IsLesser = 3;
  56942. return ValueCondition;
  56943. }(Condition));
  56944. BABYLON.ValueCondition = ValueCondition;
  56945. /**
  56946. * Defines a predicate condition as an extension of Condition
  56947. */
  56948. var PredicateCondition = /** @class */ (function (_super) {
  56949. __extends(PredicateCondition, _super);
  56950. /**
  56951. * Creates a new PredicateCondition
  56952. * @param actionManager manager for the action the condition applies to
  56953. * @param predicate defines the predicate function used to validate the condition
  56954. */
  56955. function PredicateCondition(actionManager,
  56956. /** defines the predicate function used to validate the condition */
  56957. predicate) {
  56958. var _this = _super.call(this, actionManager) || this;
  56959. _this.predicate = predicate;
  56960. return _this;
  56961. }
  56962. /**
  56963. * @returns the validity of the predicate condition
  56964. */
  56965. PredicateCondition.prototype.isValid = function () {
  56966. return this.predicate();
  56967. };
  56968. return PredicateCondition;
  56969. }(Condition));
  56970. BABYLON.PredicateCondition = PredicateCondition;
  56971. /**
  56972. * Defines a state condition as an extension of Condition
  56973. */
  56974. var StateCondition = /** @class */ (function (_super) {
  56975. __extends(StateCondition, _super);
  56976. /**
  56977. * Creates a new StateCondition
  56978. * @param actionManager manager for the action the condition applies to
  56979. * @param target of the condition
  56980. * @param value to compare with target state
  56981. */
  56982. function StateCondition(actionManager, target,
  56983. /** Value to compare with target state */
  56984. value) {
  56985. var _this = _super.call(this, actionManager) || this;
  56986. _this.value = value;
  56987. _this._target = target;
  56988. return _this;
  56989. }
  56990. /**
  56991. * Gets a boolean indicating if the current condition is met
  56992. * @returns the validity of the state
  56993. */
  56994. StateCondition.prototype.isValid = function () {
  56995. return this._target.state === this.value;
  56996. };
  56997. /**
  56998. * Serialize the StateCondition into a JSON compatible object
  56999. * @returns serialization object
  57000. */
  57001. StateCondition.prototype.serialize = function () {
  57002. return this._serialize({
  57003. name: "StateCondition",
  57004. properties: [
  57005. BABYLON.Action._GetTargetProperty(this._target),
  57006. { name: "value", value: this.value }
  57007. ]
  57008. });
  57009. };
  57010. return StateCondition;
  57011. }(Condition));
  57012. BABYLON.StateCondition = StateCondition;
  57013. })(BABYLON || (BABYLON = {}));
  57014. //# sourceMappingURL=babylon.condition.js.map
  57015. var BABYLON;
  57016. (function (BABYLON) {
  57017. /**
  57018. * The action to be carried out following a trigger
  57019. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  57020. */
  57021. var Action = /** @class */ (function () {
  57022. /**
  57023. * Creates a new Action
  57024. * @param triggerOptions the trigger, with or without parameters, for the action
  57025. * @param condition an optional determinant of action
  57026. */
  57027. function Action(
  57028. /** the trigger, with or without parameters, for the action */
  57029. triggerOptions, condition) {
  57030. this.triggerOptions = triggerOptions;
  57031. /**
  57032. * An event triggered prior to action being executed.
  57033. */
  57034. this.onBeforeExecuteObservable = new BABYLON.Observable();
  57035. if (triggerOptions.parameter) {
  57036. this.trigger = triggerOptions.trigger;
  57037. this._triggerParameter = triggerOptions.parameter;
  57038. }
  57039. else if (triggerOptions.trigger) {
  57040. this.trigger = triggerOptions.trigger;
  57041. }
  57042. else {
  57043. this.trigger = triggerOptions;
  57044. }
  57045. this._nextActiveAction = this;
  57046. this._condition = condition;
  57047. }
  57048. /**
  57049. * Internal only
  57050. * @hidden
  57051. */
  57052. Action.prototype._prepare = function () {
  57053. };
  57054. /**
  57055. * Gets the trigger parameters
  57056. * @returns the trigger parameters
  57057. */
  57058. Action.prototype.getTriggerParameter = function () {
  57059. return this._triggerParameter;
  57060. };
  57061. /**
  57062. * Internal only - executes current action event
  57063. * @hidden
  57064. */
  57065. Action.prototype._executeCurrent = function (evt) {
  57066. if (this._nextActiveAction._condition) {
  57067. var condition = this._nextActiveAction._condition;
  57068. var currentRenderId = this._actionManager.getScene().getRenderId();
  57069. // We cache the current evaluation for the current frame
  57070. if (condition._evaluationId === currentRenderId) {
  57071. if (!condition._currentResult) {
  57072. return;
  57073. }
  57074. }
  57075. else {
  57076. condition._evaluationId = currentRenderId;
  57077. if (!condition.isValid()) {
  57078. condition._currentResult = false;
  57079. return;
  57080. }
  57081. condition._currentResult = true;
  57082. }
  57083. }
  57084. this.onBeforeExecuteObservable.notifyObservers(this);
  57085. this._nextActiveAction.execute(evt);
  57086. this.skipToNextActiveAction();
  57087. };
  57088. /**
  57089. * Execute placeholder for child classes
  57090. * @param evt optional action event
  57091. */
  57092. Action.prototype.execute = function (evt) {
  57093. };
  57094. /**
  57095. * Skips to next active action
  57096. */
  57097. Action.prototype.skipToNextActiveAction = function () {
  57098. if (this._nextActiveAction._child) {
  57099. if (!this._nextActiveAction._child._actionManager) {
  57100. this._nextActiveAction._child._actionManager = this._actionManager;
  57101. }
  57102. this._nextActiveAction = this._nextActiveAction._child;
  57103. }
  57104. else {
  57105. this._nextActiveAction = this;
  57106. }
  57107. };
  57108. /**
  57109. * Adds action to chain of actions, may be a DoNothingAction
  57110. * @param action defines the next action to execute
  57111. * @returns The action passed in
  57112. * @see https://www.babylonjs-playground.com/#1T30HR#0
  57113. */
  57114. Action.prototype.then = function (action) {
  57115. this._child = action;
  57116. action._actionManager = this._actionManager;
  57117. action._prepare();
  57118. return action;
  57119. };
  57120. /**
  57121. * Internal only
  57122. * @hidden
  57123. */
  57124. Action.prototype._getProperty = function (propertyPath) {
  57125. return this._actionManager._getProperty(propertyPath);
  57126. };
  57127. /**
  57128. * Internal only
  57129. * @hidden
  57130. */
  57131. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  57132. return this._actionManager._getEffectiveTarget(target, propertyPath);
  57133. };
  57134. /**
  57135. * Serialize placeholder for child classes
  57136. * @param parent of child
  57137. * @returns the serialized object
  57138. */
  57139. Action.prototype.serialize = function (parent) {
  57140. };
  57141. /**
  57142. * Internal only called by serialize
  57143. * @hidden
  57144. */
  57145. Action.prototype._serialize = function (serializedAction, parent) {
  57146. var serializationObject = {
  57147. type: 1,
  57148. children: [],
  57149. name: serializedAction.name,
  57150. properties: serializedAction.properties || []
  57151. };
  57152. // Serialize child
  57153. if (this._child) {
  57154. this._child.serialize(serializationObject);
  57155. }
  57156. // Check if "this" has a condition
  57157. if (this._condition) {
  57158. var serializedCondition = this._condition.serialize();
  57159. serializedCondition.children.push(serializationObject);
  57160. if (parent) {
  57161. parent.children.push(serializedCondition);
  57162. }
  57163. return serializedCondition;
  57164. }
  57165. if (parent) {
  57166. parent.children.push(serializationObject);
  57167. }
  57168. return serializationObject;
  57169. };
  57170. /**
  57171. * Internal only
  57172. * @hidden
  57173. */
  57174. Action._SerializeValueAsString = function (value) {
  57175. if (typeof value === "number") {
  57176. return value.toString();
  57177. }
  57178. if (typeof value === "boolean") {
  57179. return value ? "true" : "false";
  57180. }
  57181. if (value instanceof BABYLON.Vector2) {
  57182. return value.x + ", " + value.y;
  57183. }
  57184. if (value instanceof BABYLON.Vector3) {
  57185. return value.x + ", " + value.y + ", " + value.z;
  57186. }
  57187. if (value instanceof BABYLON.Color3) {
  57188. return value.r + ", " + value.g + ", " + value.b;
  57189. }
  57190. if (value instanceof BABYLON.Color4) {
  57191. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  57192. }
  57193. return value; // string
  57194. };
  57195. /**
  57196. * Internal only
  57197. * @hidden
  57198. */
  57199. Action._GetTargetProperty = function (target) {
  57200. return {
  57201. name: "target",
  57202. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  57203. : target instanceof BABYLON.Light ? "LightProperties"
  57204. : target instanceof BABYLON.Camera ? "CameraProperties"
  57205. : "SceneProperties",
  57206. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  57207. };
  57208. };
  57209. return Action;
  57210. }());
  57211. BABYLON.Action = Action;
  57212. })(BABYLON || (BABYLON = {}));
  57213. //# sourceMappingURL=babylon.action.js.map
  57214. var BABYLON;
  57215. (function (BABYLON) {
  57216. /**
  57217. * ActionEvent is the event being sent when an action is triggered.
  57218. */
  57219. var ActionEvent = /** @class */ (function () {
  57220. /**
  57221. * Creates a new ActionEvent
  57222. * @param source The mesh or sprite that triggered the action
  57223. * @param pointerX The X mouse cursor position at the time of the event
  57224. * @param pointerY The Y mouse cursor position at the time of the event
  57225. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  57226. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  57227. * @param additionalData additional data for the event
  57228. */
  57229. function ActionEvent(
  57230. /** The mesh or sprite that triggered the action */
  57231. source,
  57232. /** The X mouse cursor position at the time of the event */
  57233. pointerX,
  57234. /** The Y mouse cursor position at the time of the event */
  57235. pointerY,
  57236. /** The mesh that is currently pointed at (can be null) */
  57237. meshUnderPointer,
  57238. /** the original (browser) event that triggered the ActionEvent */
  57239. sourceEvent,
  57240. /** additional data for the event */
  57241. additionalData) {
  57242. this.source = source;
  57243. this.pointerX = pointerX;
  57244. this.pointerY = pointerY;
  57245. this.meshUnderPointer = meshUnderPointer;
  57246. this.sourceEvent = sourceEvent;
  57247. this.additionalData = additionalData;
  57248. }
  57249. /**
  57250. * Helper function to auto-create an ActionEvent from a source mesh.
  57251. * @param source The source mesh that triggered the event
  57252. * @param evt The original (browser) event
  57253. * @param additionalData additional data for the event
  57254. * @returns the new ActionEvent
  57255. */
  57256. ActionEvent.CreateNew = function (source, evt, additionalData) {
  57257. var scene = source.getScene();
  57258. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  57259. };
  57260. /**
  57261. * Helper function to auto-create an ActionEvent from a source sprite
  57262. * @param source The source sprite that triggered the event
  57263. * @param scene Scene associated with the sprite
  57264. * @param evt The original (browser) event
  57265. * @param additionalData additional data for the event
  57266. * @returns the new ActionEvent
  57267. */
  57268. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  57269. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  57270. };
  57271. /**
  57272. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  57273. * @param scene the scene where the event occurred
  57274. * @param evt The original (browser) event
  57275. * @returns the new ActionEvent
  57276. */
  57277. ActionEvent.CreateNewFromScene = function (scene, evt) {
  57278. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  57279. };
  57280. /**
  57281. * Helper function to auto-create an ActionEvent from a primitive
  57282. * @param prim defines the target primitive
  57283. * @param pointerPos defines the pointer position
  57284. * @param evt The original (browser) event
  57285. * @param additionalData additional data for the event
  57286. * @returns the new ActionEvent
  57287. */
  57288. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  57289. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  57290. };
  57291. return ActionEvent;
  57292. }());
  57293. BABYLON.ActionEvent = ActionEvent;
  57294. /**
  57295. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  57296. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  57297. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  57298. */
  57299. var ActionManager = /** @class */ (function () {
  57300. /**
  57301. * Creates a new action manager
  57302. * @param scene defines the hosting scene
  57303. */
  57304. function ActionManager(scene) {
  57305. // Members
  57306. /** Gets the list of actions */
  57307. this.actions = new Array();
  57308. /** Gets the cursor to use when hovering items */
  57309. this.hoverCursor = '';
  57310. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  57311. scene.actionManagers.push(this);
  57312. }
  57313. // Methods
  57314. /**
  57315. * Releases all associated resources
  57316. */
  57317. ActionManager.prototype.dispose = function () {
  57318. var index = this._scene.actionManagers.indexOf(this);
  57319. for (var i = 0; i < this.actions.length; i++) {
  57320. var action = this.actions[i];
  57321. ActionManager.Triggers[action.trigger]--;
  57322. if (ActionManager.Triggers[action.trigger] === 0) {
  57323. delete ActionManager.Triggers[action.trigger];
  57324. }
  57325. }
  57326. if (index > -1) {
  57327. this._scene.actionManagers.splice(index, 1);
  57328. }
  57329. };
  57330. /**
  57331. * Gets hosting scene
  57332. * @returns the hosting scene
  57333. */
  57334. ActionManager.prototype.getScene = function () {
  57335. return this._scene;
  57336. };
  57337. /**
  57338. * Does this action manager handles actions of any of the given triggers
  57339. * @param triggers defines the triggers to be tested
  57340. * @return a boolean indicating whether one (or more) of the triggers is handled
  57341. */
  57342. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  57343. for (var index = 0; index < this.actions.length; index++) {
  57344. var action = this.actions[index];
  57345. if (triggers.indexOf(action.trigger) > -1) {
  57346. return true;
  57347. }
  57348. }
  57349. return false;
  57350. };
  57351. /**
  57352. * Does this action manager handles actions of any of the given triggers. This function takes two arguments for
  57353. * speed.
  57354. * @param triggerA defines the trigger to be tested
  57355. * @param triggerB defines the trigger to be tested
  57356. * @return a boolean indicating whether one (or more) of the triggers is handled
  57357. */
  57358. ActionManager.prototype.hasSpecificTriggers2 = function (triggerA, triggerB) {
  57359. for (var index = 0; index < this.actions.length; index++) {
  57360. var action = this.actions[index];
  57361. if (triggerA == action.trigger || triggerB == action.trigger) {
  57362. return true;
  57363. }
  57364. }
  57365. return false;
  57366. };
  57367. /**
  57368. * Does this action manager handles actions of a given trigger
  57369. * @param trigger defines the trigger to be tested
  57370. * @param parameterPredicate defines an optional predicate to filter triggers by parameter
  57371. * @return whether the trigger is handled
  57372. */
  57373. ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {
  57374. for (var index = 0; index < this.actions.length; index++) {
  57375. var action = this.actions[index];
  57376. if (action.trigger === trigger) {
  57377. if (parameterPredicate) {
  57378. if (parameterPredicate(action.getTriggerParameter())) {
  57379. return true;
  57380. }
  57381. }
  57382. else {
  57383. return true;
  57384. }
  57385. }
  57386. }
  57387. return false;
  57388. };
  57389. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  57390. /**
  57391. * Does this action manager has pointer triggers
  57392. */
  57393. get: function () {
  57394. for (var index = 0; index < this.actions.length; index++) {
  57395. var action = this.actions[index];
  57396. if (action.trigger >= ActionManager.OnPickTrigger && action.trigger <= ActionManager.OnPointerOutTrigger) {
  57397. return true;
  57398. }
  57399. }
  57400. return false;
  57401. },
  57402. enumerable: true,
  57403. configurable: true
  57404. });
  57405. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  57406. /**
  57407. * Does this action manager has pick triggers
  57408. */
  57409. get: function () {
  57410. for (var index = 0; index < this.actions.length; index++) {
  57411. var action = this.actions[index];
  57412. if (action.trigger >= ActionManager.OnPickTrigger && action.trigger <= ActionManager.OnPickUpTrigger) {
  57413. return true;
  57414. }
  57415. }
  57416. return false;
  57417. },
  57418. enumerable: true,
  57419. configurable: true
  57420. });
  57421. Object.defineProperty(ActionManager, "HasTriggers", {
  57422. /**
  57423. * Does exist one action manager with at least one trigger
  57424. **/
  57425. get: function () {
  57426. for (var t in ActionManager.Triggers) {
  57427. if (ActionManager.Triggers.hasOwnProperty(t)) {
  57428. return true;
  57429. }
  57430. }
  57431. return false;
  57432. },
  57433. enumerable: true,
  57434. configurable: true
  57435. });
  57436. Object.defineProperty(ActionManager, "HasPickTriggers", {
  57437. /**
  57438. * Does exist one action manager with at least one pick trigger
  57439. **/
  57440. get: function () {
  57441. for (var t in ActionManager.Triggers) {
  57442. if (ActionManager.Triggers.hasOwnProperty(t)) {
  57443. var t_int = parseInt(t);
  57444. if (t_int >= ActionManager.OnPickTrigger && t_int <= ActionManager.OnPickUpTrigger) {
  57445. return true;
  57446. }
  57447. }
  57448. }
  57449. return false;
  57450. },
  57451. enumerable: true,
  57452. configurable: true
  57453. });
  57454. /**
  57455. * Does exist one action manager that handles actions of a given trigger
  57456. * @param trigger defines the trigger to be tested
  57457. * @return a boolean indicating whether the trigger is handeled by at least one action manager
  57458. **/
  57459. ActionManager.HasSpecificTrigger = function (trigger) {
  57460. for (var t in ActionManager.Triggers) {
  57461. if (ActionManager.Triggers.hasOwnProperty(t)) {
  57462. var t_int = parseInt(t);
  57463. if (t_int === trigger) {
  57464. return true;
  57465. }
  57466. }
  57467. }
  57468. return false;
  57469. };
  57470. /**
  57471. * Registers an action to this action manager
  57472. * @param action defines the action to be registered
  57473. * @return the action amended (prepared) after registration
  57474. */
  57475. ActionManager.prototype.registerAction = function (action) {
  57476. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  57477. if (this.getScene().actionManager !== this) {
  57478. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  57479. return null;
  57480. }
  57481. }
  57482. this.actions.push(action);
  57483. if (ActionManager.Triggers[action.trigger]) {
  57484. ActionManager.Triggers[action.trigger]++;
  57485. }
  57486. else {
  57487. ActionManager.Triggers[action.trigger] = 1;
  57488. }
  57489. action._actionManager = this;
  57490. action._prepare();
  57491. return action;
  57492. };
  57493. /**
  57494. * Unregisters an action to this action manager
  57495. * @param action defines the action to be unregistered
  57496. * @return a boolean indicating whether the action has been unregistered
  57497. */
  57498. ActionManager.prototype.unregisterAction = function (action) {
  57499. var index = this.actions.indexOf(action);
  57500. if (index !== -1) {
  57501. this.actions.splice(index, 1);
  57502. ActionManager.Triggers[action.trigger] -= 1;
  57503. if (ActionManager.Triggers[action.trigger] === 0) {
  57504. delete ActionManager.Triggers[action.trigger];
  57505. }
  57506. delete action._actionManager;
  57507. return true;
  57508. }
  57509. return false;
  57510. };
  57511. /**
  57512. * Process a specific trigger
  57513. * @param trigger defines the trigger to process
  57514. * @param evt defines the event details to be processed
  57515. */
  57516. ActionManager.prototype.processTrigger = function (trigger, evt) {
  57517. for (var index = 0; index < this.actions.length; index++) {
  57518. var action = this.actions[index];
  57519. if (action.trigger === trigger) {
  57520. if (evt) {
  57521. if (trigger === ActionManager.OnKeyUpTrigger
  57522. || trigger === ActionManager.OnKeyDownTrigger) {
  57523. var parameter = action.getTriggerParameter();
  57524. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  57525. if (!parameter.toLowerCase) {
  57526. continue;
  57527. }
  57528. var lowerCase = parameter.toLowerCase();
  57529. if (lowerCase !== evt.sourceEvent.key) {
  57530. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  57531. var actualkey = String.fromCharCode(unicode).toLowerCase();
  57532. if (actualkey !== lowerCase) {
  57533. continue;
  57534. }
  57535. }
  57536. }
  57537. }
  57538. }
  57539. action._executeCurrent(evt);
  57540. }
  57541. }
  57542. };
  57543. /** @hidden */
  57544. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  57545. var properties = propertyPath.split(".");
  57546. for (var index = 0; index < properties.length - 1; index++) {
  57547. target = target[properties[index]];
  57548. }
  57549. return target;
  57550. };
  57551. /** @hidden */
  57552. ActionManager.prototype._getProperty = function (propertyPath) {
  57553. var properties = propertyPath.split(".");
  57554. return properties[properties.length - 1];
  57555. };
  57556. /**
  57557. * Serialize this manager to a JSON object
  57558. * @param name defines the property name to store this manager
  57559. * @returns a JSON representation of this manager
  57560. */
  57561. ActionManager.prototype.serialize = function (name) {
  57562. var root = {
  57563. children: new Array(),
  57564. name: name,
  57565. type: 3,
  57566. properties: new Array() // Empty for root but required
  57567. };
  57568. for (var i = 0; i < this.actions.length; i++) {
  57569. var triggerObject = {
  57570. type: 0,
  57571. children: new Array(),
  57572. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  57573. properties: new Array()
  57574. };
  57575. var triggerOptions = this.actions[i].triggerOptions;
  57576. if (triggerOptions && typeof triggerOptions !== "number") {
  57577. if (triggerOptions.parameter instanceof BABYLON.Node) {
  57578. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  57579. }
  57580. else {
  57581. var parameter = {};
  57582. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  57583. if (triggerOptions.parameter && triggerOptions.parameter.mesh) {
  57584. parameter._meshId = triggerOptions.parameter.mesh.id;
  57585. }
  57586. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  57587. }
  57588. }
  57589. // Serialize child action, recursively
  57590. this.actions[i].serialize(triggerObject);
  57591. // Add serialized trigger
  57592. root.children.push(triggerObject);
  57593. }
  57594. return root;
  57595. };
  57596. /**
  57597. * Creates a new ActionManager from a JSON data
  57598. * @param parsedActions defines the JSON data to read from
  57599. * @param object defines the hosting mesh
  57600. * @param scene defines the hosting scene
  57601. */
  57602. ActionManager.Parse = function (parsedActions, object, scene) {
  57603. var actionManager = new ActionManager(scene);
  57604. if (object === null) {
  57605. scene.actionManager = actionManager;
  57606. }
  57607. else {
  57608. object.actionManager = actionManager;
  57609. }
  57610. // instanciate a new object
  57611. var instanciate = function (name, params) {
  57612. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  57613. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  57614. newInstance.constructor.apply(newInstance, params);
  57615. return newInstance;
  57616. };
  57617. var parseParameter = function (name, value, target, propertyPath) {
  57618. if (propertyPath === null) {
  57619. // String, boolean or float
  57620. var floatValue = parseFloat(value);
  57621. if (value === "true" || value === "false") {
  57622. return value === "true";
  57623. }
  57624. else {
  57625. return isNaN(floatValue) ? value : floatValue;
  57626. }
  57627. }
  57628. var effectiveTarget = propertyPath.split(".");
  57629. var values = value.split(",");
  57630. // Get effective Target
  57631. for (var i = 0; i < effectiveTarget.length; i++) {
  57632. target = target[effectiveTarget[i]];
  57633. }
  57634. // Return appropriate value with its type
  57635. if (typeof (target) === "boolean") {
  57636. return values[0] === "true";
  57637. }
  57638. if (typeof (target) === "string") {
  57639. return values[0];
  57640. }
  57641. // Parameters with multiple values such as Vector3 etc.
  57642. var split = new Array();
  57643. for (var i = 0; i < values.length; i++) {
  57644. split.push(parseFloat(values[i]));
  57645. }
  57646. if (target instanceof BABYLON.Vector3) {
  57647. return BABYLON.Vector3.FromArray(split);
  57648. }
  57649. if (target instanceof BABYLON.Vector4) {
  57650. return BABYLON.Vector4.FromArray(split);
  57651. }
  57652. if (target instanceof BABYLON.Color3) {
  57653. return BABYLON.Color3.FromArray(split);
  57654. }
  57655. if (target instanceof BABYLON.Color4) {
  57656. return BABYLON.Color4.FromArray(split);
  57657. }
  57658. return parseFloat(values[0]);
  57659. };
  57660. // traverse graph per trigger
  57661. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  57662. if (combineArray === void 0) { combineArray = null; }
  57663. if (parsedAction.detached) {
  57664. return;
  57665. }
  57666. var parameters = new Array();
  57667. var target = null;
  57668. var propertyPath = null;
  57669. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  57670. // Parameters
  57671. if (parsedAction.type === 2) {
  57672. parameters.push(actionManager);
  57673. }
  57674. else {
  57675. parameters.push(trigger);
  57676. }
  57677. if (combine) {
  57678. var actions = new Array();
  57679. for (var j = 0; j < parsedAction.combine.length; j++) {
  57680. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  57681. }
  57682. parameters.push(actions);
  57683. }
  57684. else {
  57685. for (var i = 0; i < parsedAction.properties.length; i++) {
  57686. var value = parsedAction.properties[i].value;
  57687. var name = parsedAction.properties[i].name;
  57688. var targetType = parsedAction.properties[i].targetType;
  57689. if (name === "target") {
  57690. if (targetType !== null && targetType === "SceneProperties") {
  57691. value = target = scene;
  57692. }
  57693. else {
  57694. value = target = scene.getNodeByName(value);
  57695. }
  57696. }
  57697. else if (name === "parent") {
  57698. value = scene.getNodeByName(value);
  57699. }
  57700. else if (name === "sound") {
  57701. // Can not externalize to component, so only checks for the presence off the API.
  57702. if (scene.getSoundByName) {
  57703. value = scene.getSoundByName(value);
  57704. }
  57705. }
  57706. else if (name !== "propertyPath") {
  57707. if (parsedAction.type === 2 && name === "operator") {
  57708. value = BABYLON.ValueCondition[value];
  57709. }
  57710. else {
  57711. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  57712. }
  57713. }
  57714. else {
  57715. propertyPath = value;
  57716. }
  57717. parameters.push(value);
  57718. }
  57719. }
  57720. if (combineArray === null) {
  57721. parameters.push(condition);
  57722. }
  57723. else {
  57724. parameters.push(null);
  57725. }
  57726. // If interpolate value action
  57727. if (parsedAction.name === "InterpolateValueAction") {
  57728. var param = parameters[parameters.length - 2];
  57729. parameters[parameters.length - 1] = param;
  57730. parameters[parameters.length - 2] = condition;
  57731. }
  57732. // Action or condition(s) and not CombineAction
  57733. var newAction = instanciate(parsedAction.name, parameters);
  57734. if (newAction instanceof BABYLON.Condition && condition !== null) {
  57735. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  57736. if (action) {
  57737. action.then(nothing);
  57738. }
  57739. else {
  57740. actionManager.registerAction(nothing);
  57741. }
  57742. action = nothing;
  57743. }
  57744. if (combineArray === null) {
  57745. if (newAction instanceof BABYLON.Condition) {
  57746. condition = newAction;
  57747. newAction = action;
  57748. }
  57749. else {
  57750. condition = null;
  57751. if (action) {
  57752. action.then(newAction);
  57753. }
  57754. else {
  57755. actionManager.registerAction(newAction);
  57756. }
  57757. }
  57758. }
  57759. else {
  57760. combineArray.push(newAction);
  57761. }
  57762. for (var i = 0; i < parsedAction.children.length; i++) {
  57763. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  57764. }
  57765. };
  57766. // triggers
  57767. for (var i = 0; i < parsedActions.children.length; i++) {
  57768. var triggerParams;
  57769. var trigger = parsedActions.children[i];
  57770. if (trigger.properties.length > 0) {
  57771. var param = trigger.properties[0].value;
  57772. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  57773. if (value._meshId) {
  57774. value.mesh = scene.getMeshByID(value._meshId);
  57775. }
  57776. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  57777. }
  57778. else {
  57779. triggerParams = ActionManager[trigger.name];
  57780. }
  57781. for (var j = 0; j < trigger.children.length; j++) {
  57782. if (!trigger.detached) {
  57783. traverse(trigger.children[j], triggerParams, null, null);
  57784. }
  57785. }
  57786. }
  57787. };
  57788. /**
  57789. * Get a trigger name by index
  57790. * @param trigger defines the trigger index
  57791. * @returns a trigger name
  57792. */
  57793. ActionManager.GetTriggerName = function (trigger) {
  57794. switch (trigger) {
  57795. case 0: return "NothingTrigger";
  57796. case 1: return "OnPickTrigger";
  57797. case 2: return "OnLeftPickTrigger";
  57798. case 3: return "OnRightPickTrigger";
  57799. case 4: return "OnCenterPickTrigger";
  57800. case 5: return "OnPickDownTrigger";
  57801. case 6: return "OnPickUpTrigger";
  57802. case 7: return "OnLongPressTrigger";
  57803. case 8: return "OnPointerOverTrigger";
  57804. case 9: return "OnPointerOutTrigger";
  57805. case 10: return "OnEveryFrameTrigger";
  57806. case 11: return "OnIntersectionEnterTrigger";
  57807. case 12: return "OnIntersectionExitTrigger";
  57808. case 13: return "OnKeyDownTrigger";
  57809. case 14: return "OnKeyUpTrigger";
  57810. case 15: return "OnPickOutTrigger";
  57811. default: return "";
  57812. }
  57813. };
  57814. /**
  57815. * Nothing
  57816. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  57817. */
  57818. ActionManager.NothingTrigger = 0;
  57819. /**
  57820. * On pick
  57821. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  57822. */
  57823. ActionManager.OnPickTrigger = 1;
  57824. /**
  57825. * On left pick
  57826. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  57827. */
  57828. ActionManager.OnLeftPickTrigger = 2;
  57829. /**
  57830. * On right pick
  57831. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  57832. */
  57833. ActionManager.OnRightPickTrigger = 3;
  57834. /**
  57835. * On center pick
  57836. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  57837. */
  57838. ActionManager.OnCenterPickTrigger = 4;
  57839. /**
  57840. * On pick down
  57841. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  57842. */
  57843. ActionManager.OnPickDownTrigger = 5;
  57844. /**
  57845. * On double pick
  57846. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  57847. */
  57848. ActionManager.OnDoublePickTrigger = 6;
  57849. /**
  57850. * On pick up
  57851. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  57852. */
  57853. ActionManager.OnPickUpTrigger = 7;
  57854. /**
  57855. * On pick out.
  57856. * This trigger will only be raised if you also declared a OnPickDown
  57857. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  57858. */
  57859. ActionManager.OnPickOutTrigger = 16;
  57860. /**
  57861. * On long press
  57862. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  57863. */
  57864. ActionManager.OnLongPressTrigger = 8;
  57865. /**
  57866. * On pointer over
  57867. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  57868. */
  57869. ActionManager.OnPointerOverTrigger = 9;
  57870. /**
  57871. * On pointer out
  57872. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  57873. */
  57874. ActionManager.OnPointerOutTrigger = 10;
  57875. /**
  57876. * On every frame
  57877. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  57878. */
  57879. ActionManager.OnEveryFrameTrigger = 11;
  57880. /**
  57881. * On intersection enter
  57882. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  57883. */
  57884. ActionManager.OnIntersectionEnterTrigger = 12;
  57885. /**
  57886. * On intersection exit
  57887. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  57888. */
  57889. ActionManager.OnIntersectionExitTrigger = 13;
  57890. /**
  57891. * On key down
  57892. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  57893. */
  57894. ActionManager.OnKeyDownTrigger = 14;
  57895. /**
  57896. * On key up
  57897. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  57898. */
  57899. ActionManager.OnKeyUpTrigger = 15;
  57900. /** Gets the list of active triggers */
  57901. ActionManager.Triggers = {};
  57902. return ActionManager;
  57903. }());
  57904. BABYLON.ActionManager = ActionManager;
  57905. })(BABYLON || (BABYLON = {}));
  57906. //# sourceMappingURL=babylon.actionManager.js.map
  57907. var BABYLON;
  57908. (function (BABYLON) {
  57909. /**
  57910. * This defines an action responsible to change the value of a property
  57911. * by interpolating between its current value and the newly set one once triggered.
  57912. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  57913. */
  57914. var InterpolateValueAction = /** @class */ (function (_super) {
  57915. __extends(InterpolateValueAction, _super);
  57916. /**
  57917. * Instantiate the action
  57918. * @param triggerOptions defines the trigger options
  57919. * @param target defines the object containing the value to interpolate
  57920. * @param propertyPath defines the path to the property in the target object
  57921. * @param value defines the target value at the end of the interpolation
  57922. * @param duration deines the time it will take for the property to interpolate to the value.
  57923. * @param condition defines the trigger related conditions
  57924. * @param stopOtherAnimations defines if the other scene animations should be stopped when the action has been triggered
  57925. * @param onInterpolationDone defines a callback raised once the interpolation animation has been done
  57926. */
  57927. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  57928. if (duration === void 0) { duration = 1000; }
  57929. var _this = _super.call(this, triggerOptions, condition) || this;
  57930. /**
  57931. * Defines the time it will take for the property to interpolate to the value.
  57932. */
  57933. _this.duration = 1000;
  57934. /**
  57935. * Observable triggered once the interpolation animation has been done.
  57936. */
  57937. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  57938. _this.propertyPath = propertyPath;
  57939. _this.value = value;
  57940. _this.duration = duration;
  57941. _this.stopOtherAnimations = stopOtherAnimations;
  57942. _this.onInterpolationDone = onInterpolationDone;
  57943. _this._target = _this._effectiveTarget = target;
  57944. return _this;
  57945. }
  57946. /** @hidden */
  57947. InterpolateValueAction.prototype._prepare = function () {
  57948. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  57949. this._property = this._getProperty(this.propertyPath);
  57950. };
  57951. /**
  57952. * Execute the action starts the value interpolation.
  57953. */
  57954. InterpolateValueAction.prototype.execute = function () {
  57955. var _this = this;
  57956. var scene = this._actionManager.getScene();
  57957. var keys = [
  57958. {
  57959. frame: 0,
  57960. value: this._effectiveTarget[this._property]
  57961. }, {
  57962. frame: 100,
  57963. value: this.value
  57964. }
  57965. ];
  57966. var dataType;
  57967. if (typeof this.value === "number") {
  57968. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  57969. }
  57970. else if (this.value instanceof BABYLON.Color3) {
  57971. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  57972. }
  57973. else if (this.value instanceof BABYLON.Vector3) {
  57974. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  57975. }
  57976. else if (this.value instanceof BABYLON.Matrix) {
  57977. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  57978. }
  57979. else if (this.value instanceof BABYLON.Quaternion) {
  57980. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  57981. }
  57982. else {
  57983. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  57984. return;
  57985. }
  57986. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  57987. animation.setKeys(keys);
  57988. if (this.stopOtherAnimations) {
  57989. scene.stopAnimation(this._effectiveTarget);
  57990. }
  57991. var wrapper = function () {
  57992. _this.onInterpolationDoneObservable.notifyObservers(_this);
  57993. if (_this.onInterpolationDone) {
  57994. _this.onInterpolationDone();
  57995. }
  57996. };
  57997. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  57998. };
  57999. /**
  58000. * Serializes the actions and its related information.
  58001. * @param parent defines the object to serialize in
  58002. * @returns the serialized object
  58003. */
  58004. InterpolateValueAction.prototype.serialize = function (parent) {
  58005. return _super.prototype._serialize.call(this, {
  58006. name: "InterpolateValueAction",
  58007. properties: [
  58008. BABYLON.Action._GetTargetProperty(this._target),
  58009. { name: "propertyPath", value: this.propertyPath },
  58010. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  58011. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  58012. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  58013. ]
  58014. }, parent);
  58015. };
  58016. return InterpolateValueAction;
  58017. }(BABYLON.Action));
  58018. BABYLON.InterpolateValueAction = InterpolateValueAction;
  58019. })(BABYLON || (BABYLON = {}));
  58020. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  58021. var BABYLON;
  58022. (function (BABYLON) {
  58023. /**
  58024. * This defines an action responsible to toggle a boolean once triggered.
  58025. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  58026. */
  58027. var SwitchBooleanAction = /** @class */ (function (_super) {
  58028. __extends(SwitchBooleanAction, _super);
  58029. /**
  58030. * Instantiate the action
  58031. * @param triggerOptions defines the trigger options
  58032. * @param target defines the object containing the boolean
  58033. * @param propertyPath defines the path to the boolean property in the target object
  58034. * @param condition defines the trigger related conditions
  58035. */
  58036. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  58037. var _this = _super.call(this, triggerOptions, condition) || this;
  58038. _this.propertyPath = propertyPath;
  58039. _this._target = _this._effectiveTarget = target;
  58040. return _this;
  58041. }
  58042. /** @hidden */
  58043. SwitchBooleanAction.prototype._prepare = function () {
  58044. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  58045. this._property = this._getProperty(this.propertyPath);
  58046. };
  58047. /**
  58048. * Execute the action toggle the boolean value.
  58049. */
  58050. SwitchBooleanAction.prototype.execute = function () {
  58051. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  58052. };
  58053. /**
  58054. * Serializes the actions and its related information.
  58055. * @param parent defines the object to serialize in
  58056. * @returns the serialized object
  58057. */
  58058. SwitchBooleanAction.prototype.serialize = function (parent) {
  58059. return _super.prototype._serialize.call(this, {
  58060. name: "SwitchBooleanAction",
  58061. properties: [
  58062. BABYLON.Action._GetTargetProperty(this._target),
  58063. { name: "propertyPath", value: this.propertyPath }
  58064. ]
  58065. }, parent);
  58066. };
  58067. return SwitchBooleanAction;
  58068. }(BABYLON.Action));
  58069. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  58070. /**
  58071. * This defines an action responsible to set a the state field of the target
  58072. * to a desired value once triggered.
  58073. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  58074. */
  58075. var SetStateAction = /** @class */ (function (_super) {
  58076. __extends(SetStateAction, _super);
  58077. /**
  58078. * Instantiate the action
  58079. * @param triggerOptions defines the trigger options
  58080. * @param target defines the object containing the state property
  58081. * @param value defines the value to store in the state field
  58082. * @param condition defines the trigger related conditions
  58083. */
  58084. function SetStateAction(triggerOptions, target, value, condition) {
  58085. var _this = _super.call(this, triggerOptions, condition) || this;
  58086. _this.value = value;
  58087. _this._target = target;
  58088. return _this;
  58089. }
  58090. /**
  58091. * Execute the action and store the value on the target state property.
  58092. */
  58093. SetStateAction.prototype.execute = function () {
  58094. this._target.state = this.value;
  58095. };
  58096. /**
  58097. * Serializes the actions and its related information.
  58098. * @param parent defines the object to serialize in
  58099. * @returns the serialized object
  58100. */
  58101. SetStateAction.prototype.serialize = function (parent) {
  58102. return _super.prototype._serialize.call(this, {
  58103. name: "SetStateAction",
  58104. properties: [
  58105. BABYLON.Action._GetTargetProperty(this._target),
  58106. { name: "value", value: this.value }
  58107. ]
  58108. }, parent);
  58109. };
  58110. return SetStateAction;
  58111. }(BABYLON.Action));
  58112. BABYLON.SetStateAction = SetStateAction;
  58113. /**
  58114. * This defines an action responsible to set a property of the target
  58115. * to a desired value once triggered.
  58116. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  58117. */
  58118. var SetValueAction = /** @class */ (function (_super) {
  58119. __extends(SetValueAction, _super);
  58120. /**
  58121. * Instantiate the action
  58122. * @param triggerOptions defines the trigger options
  58123. * @param target defines the object containing the property
  58124. * @param propertyPath defines the path of the property to set in the target
  58125. * @param value defines the value to set in the property
  58126. * @param condition defines the trigger related conditions
  58127. */
  58128. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  58129. var _this = _super.call(this, triggerOptions, condition) || this;
  58130. _this.propertyPath = propertyPath;
  58131. _this.value = value;
  58132. _this._target = _this._effectiveTarget = target;
  58133. return _this;
  58134. }
  58135. /** @hidden */
  58136. SetValueAction.prototype._prepare = function () {
  58137. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  58138. this._property = this._getProperty(this.propertyPath);
  58139. };
  58140. /**
  58141. * Execute the action and set the targetted property to the desired value.
  58142. */
  58143. SetValueAction.prototype.execute = function () {
  58144. this._effectiveTarget[this._property] = this.value;
  58145. if (this._target.markAsDirty) {
  58146. this._target.markAsDirty(this._property);
  58147. }
  58148. };
  58149. /**
  58150. * Serializes the actions and its related information.
  58151. * @param parent defines the object to serialize in
  58152. * @returns the serialized object
  58153. */
  58154. SetValueAction.prototype.serialize = function (parent) {
  58155. return _super.prototype._serialize.call(this, {
  58156. name: "SetValueAction",
  58157. properties: [
  58158. BABYLON.Action._GetTargetProperty(this._target),
  58159. { name: "propertyPath", value: this.propertyPath },
  58160. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  58161. ]
  58162. }, parent);
  58163. };
  58164. return SetValueAction;
  58165. }(BABYLON.Action));
  58166. BABYLON.SetValueAction = SetValueAction;
  58167. /**
  58168. * This defines an action responsible to increment the target value
  58169. * to a desired value once triggered.
  58170. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  58171. */
  58172. var IncrementValueAction = /** @class */ (function (_super) {
  58173. __extends(IncrementValueAction, _super);
  58174. /**
  58175. * Instantiate the action
  58176. * @param triggerOptions defines the trigger options
  58177. * @param target defines the object containing the property
  58178. * @param propertyPath defines the path of the property to increment in the target
  58179. * @param value defines the value value we should increment the property by
  58180. * @param condition defines the trigger related conditions
  58181. */
  58182. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  58183. var _this = _super.call(this, triggerOptions, condition) || this;
  58184. _this.propertyPath = propertyPath;
  58185. _this.value = value;
  58186. _this._target = _this._effectiveTarget = target;
  58187. return _this;
  58188. }
  58189. /** @hidden */
  58190. IncrementValueAction.prototype._prepare = function () {
  58191. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  58192. this._property = this._getProperty(this.propertyPath);
  58193. if (typeof this._effectiveTarget[this._property] !== "number") {
  58194. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  58195. }
  58196. };
  58197. /**
  58198. * Execute the action and increment the target of the value amount.
  58199. */
  58200. IncrementValueAction.prototype.execute = function () {
  58201. this._effectiveTarget[this._property] += this.value;
  58202. if (this._target.markAsDirty) {
  58203. this._target.markAsDirty(this._property);
  58204. }
  58205. };
  58206. /**
  58207. * Serializes the actions and its related information.
  58208. * @param parent defines the object to serialize in
  58209. * @returns the serialized object
  58210. */
  58211. IncrementValueAction.prototype.serialize = function (parent) {
  58212. return _super.prototype._serialize.call(this, {
  58213. name: "IncrementValueAction",
  58214. properties: [
  58215. BABYLON.Action._GetTargetProperty(this._target),
  58216. { name: "propertyPath", value: this.propertyPath },
  58217. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  58218. ]
  58219. }, parent);
  58220. };
  58221. return IncrementValueAction;
  58222. }(BABYLON.Action));
  58223. BABYLON.IncrementValueAction = IncrementValueAction;
  58224. /**
  58225. * This defines an action responsible to start an animation once triggered.
  58226. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  58227. */
  58228. var PlayAnimationAction = /** @class */ (function (_super) {
  58229. __extends(PlayAnimationAction, _super);
  58230. /**
  58231. * Instantiate the action
  58232. * @param triggerOptions defines the trigger options
  58233. * @param target defines the target animation or animation name
  58234. * @param from defines from where the animation should start (animation frame)
  58235. * @param end defines where the animation should stop (animation frame)
  58236. * @param loop defines if the animation should loop or stop after the first play
  58237. * @param condition defines the trigger related conditions
  58238. */
  58239. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  58240. var _this = _super.call(this, triggerOptions, condition) || this;
  58241. _this.from = from;
  58242. _this.to = to;
  58243. _this.loop = loop;
  58244. _this._target = target;
  58245. return _this;
  58246. }
  58247. /** @hidden */
  58248. PlayAnimationAction.prototype._prepare = function () {
  58249. };
  58250. /**
  58251. * Execute the action and play the animation.
  58252. */
  58253. PlayAnimationAction.prototype.execute = function () {
  58254. var scene = this._actionManager.getScene();
  58255. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  58256. };
  58257. /**
  58258. * Serializes the actions and its related information.
  58259. * @param parent defines the object to serialize in
  58260. * @returns the serialized object
  58261. */
  58262. PlayAnimationAction.prototype.serialize = function (parent) {
  58263. return _super.prototype._serialize.call(this, {
  58264. name: "PlayAnimationAction",
  58265. properties: [
  58266. BABYLON.Action._GetTargetProperty(this._target),
  58267. { name: "from", value: String(this.from) },
  58268. { name: "to", value: String(this.to) },
  58269. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  58270. ]
  58271. }, parent);
  58272. };
  58273. return PlayAnimationAction;
  58274. }(BABYLON.Action));
  58275. BABYLON.PlayAnimationAction = PlayAnimationAction;
  58276. /**
  58277. * This defines an action responsible to stop an animation once triggered.
  58278. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  58279. */
  58280. var StopAnimationAction = /** @class */ (function (_super) {
  58281. __extends(StopAnimationAction, _super);
  58282. /**
  58283. * Instantiate the action
  58284. * @param triggerOptions defines the trigger options
  58285. * @param target defines the target animation or animation name
  58286. * @param condition defines the trigger related conditions
  58287. */
  58288. function StopAnimationAction(triggerOptions, target, condition) {
  58289. var _this = _super.call(this, triggerOptions, condition) || this;
  58290. _this._target = target;
  58291. return _this;
  58292. }
  58293. /** @hidden */
  58294. StopAnimationAction.prototype._prepare = function () {
  58295. };
  58296. /**
  58297. * Execute the action and stop the animation.
  58298. */
  58299. StopAnimationAction.prototype.execute = function () {
  58300. var scene = this._actionManager.getScene();
  58301. scene.stopAnimation(this._target);
  58302. };
  58303. /**
  58304. * Serializes the actions and its related information.
  58305. * @param parent defines the object to serialize in
  58306. * @returns the serialized object
  58307. */
  58308. StopAnimationAction.prototype.serialize = function (parent) {
  58309. return _super.prototype._serialize.call(this, {
  58310. name: "StopAnimationAction",
  58311. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  58312. }, parent);
  58313. };
  58314. return StopAnimationAction;
  58315. }(BABYLON.Action));
  58316. BABYLON.StopAnimationAction = StopAnimationAction;
  58317. /**
  58318. * This defines an action responsible that does nothing once triggered.
  58319. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  58320. */
  58321. var DoNothingAction = /** @class */ (function (_super) {
  58322. __extends(DoNothingAction, _super);
  58323. /**
  58324. * Instantiate the action
  58325. * @param triggerOptions defines the trigger options
  58326. * @param condition defines the trigger related conditions
  58327. */
  58328. function DoNothingAction(triggerOptions, condition) {
  58329. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  58330. return _super.call(this, triggerOptions, condition) || this;
  58331. }
  58332. /**
  58333. * Execute the action and do nothing.
  58334. */
  58335. DoNothingAction.prototype.execute = function () {
  58336. };
  58337. /**
  58338. * Serializes the actions and its related information.
  58339. * @param parent defines the object to serialize in
  58340. * @returns the serialized object
  58341. */
  58342. DoNothingAction.prototype.serialize = function (parent) {
  58343. return _super.prototype._serialize.call(this, {
  58344. name: "DoNothingAction",
  58345. properties: []
  58346. }, parent);
  58347. };
  58348. return DoNothingAction;
  58349. }(BABYLON.Action));
  58350. BABYLON.DoNothingAction = DoNothingAction;
  58351. /**
  58352. * This defines an action responsible to trigger several actions once triggered.
  58353. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  58354. */
  58355. var CombineAction = /** @class */ (function (_super) {
  58356. __extends(CombineAction, _super);
  58357. /**
  58358. * Instantiate the action
  58359. * @param triggerOptions defines the trigger options
  58360. * @param children defines the list of aggregated animations to run
  58361. * @param condition defines the trigger related conditions
  58362. */
  58363. function CombineAction(triggerOptions, children, condition) {
  58364. var _this = _super.call(this, triggerOptions, condition) || this;
  58365. _this.children = children;
  58366. return _this;
  58367. }
  58368. /** @hidden */
  58369. CombineAction.prototype._prepare = function () {
  58370. for (var index = 0; index < this.children.length; index++) {
  58371. this.children[index]._actionManager = this._actionManager;
  58372. this.children[index]._prepare();
  58373. }
  58374. };
  58375. /**
  58376. * Execute the action and executes all the aggregated actions.
  58377. */
  58378. CombineAction.prototype.execute = function (evt) {
  58379. for (var index = 0; index < this.children.length; index++) {
  58380. this.children[index].execute(evt);
  58381. }
  58382. };
  58383. /**
  58384. * Serializes the actions and its related information.
  58385. * @param parent defines the object to serialize in
  58386. * @returns the serialized object
  58387. */
  58388. CombineAction.prototype.serialize = function (parent) {
  58389. var serializationObject = _super.prototype._serialize.call(this, {
  58390. name: "CombineAction",
  58391. properties: [],
  58392. combine: []
  58393. }, parent);
  58394. for (var i = 0; i < this.children.length; i++) {
  58395. serializationObject.combine.push(this.children[i].serialize(null));
  58396. }
  58397. return serializationObject;
  58398. };
  58399. return CombineAction;
  58400. }(BABYLON.Action));
  58401. BABYLON.CombineAction = CombineAction;
  58402. /**
  58403. * This defines an action responsible to run code (external event) once triggered.
  58404. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  58405. */
  58406. var ExecuteCodeAction = /** @class */ (function (_super) {
  58407. __extends(ExecuteCodeAction, _super);
  58408. /**
  58409. * Instantiate the action
  58410. * @param triggerOptions defines the trigger options
  58411. * @param func defines the callback function to run
  58412. * @param condition defines the trigger related conditions
  58413. */
  58414. function ExecuteCodeAction(triggerOptions, func, condition) {
  58415. var _this = _super.call(this, triggerOptions, condition) || this;
  58416. _this.func = func;
  58417. return _this;
  58418. }
  58419. /**
  58420. * Execute the action and run the attached code.
  58421. */
  58422. ExecuteCodeAction.prototype.execute = function (evt) {
  58423. this.func(evt);
  58424. };
  58425. return ExecuteCodeAction;
  58426. }(BABYLON.Action));
  58427. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  58428. /**
  58429. * This defines an action responsible to set the parent property of the target once triggered.
  58430. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  58431. */
  58432. var SetParentAction = /** @class */ (function (_super) {
  58433. __extends(SetParentAction, _super);
  58434. /**
  58435. * Instantiate the action
  58436. * @param triggerOptions defines the trigger options
  58437. * @param target defines the target containing the parent property
  58438. * @param parent defines from where the animation should start (animation frame)
  58439. * @param condition defines the trigger related conditions
  58440. */
  58441. function SetParentAction(triggerOptions, target, parent, condition) {
  58442. var _this = _super.call(this, triggerOptions, condition) || this;
  58443. _this._target = target;
  58444. _this._parent = parent;
  58445. return _this;
  58446. }
  58447. /** @hidden */
  58448. SetParentAction.prototype._prepare = function () {
  58449. };
  58450. /**
  58451. * Execute the action and set the parent property.
  58452. */
  58453. SetParentAction.prototype.execute = function () {
  58454. if (this._target.parent === this._parent) {
  58455. return;
  58456. }
  58457. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  58458. invertParentWorldMatrix.invert();
  58459. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  58460. this._target.parent = this._parent;
  58461. };
  58462. /**
  58463. * Serializes the actions and its related information.
  58464. * @param parent defines the object to serialize in
  58465. * @returns the serialized object
  58466. */
  58467. SetParentAction.prototype.serialize = function (parent) {
  58468. return _super.prototype._serialize.call(this, {
  58469. name: "SetParentAction",
  58470. properties: [
  58471. BABYLON.Action._GetTargetProperty(this._target),
  58472. BABYLON.Action._GetTargetProperty(this._parent),
  58473. ]
  58474. }, parent);
  58475. };
  58476. return SetParentAction;
  58477. }(BABYLON.Action));
  58478. BABYLON.SetParentAction = SetParentAction;
  58479. })(BABYLON || (BABYLON = {}));
  58480. //# sourceMappingURL=babylon.directActions.js.map
  58481. var BABYLON;
  58482. (function (BABYLON) {
  58483. /**
  58484. * Class used to manage multiple sprites on the same spritesheet
  58485. * @see http://doc.babylonjs.com/babylon101/sprites
  58486. */
  58487. var SpriteManager = /** @class */ (function () {
  58488. /**
  58489. * Creates a new sprite manager
  58490. * @param name defines the manager's name
  58491. * @param imgUrl defines the sprite sheet url
  58492. * @param capacity defines the maximum allowed number of sprites
  58493. * @param cellSize defines the size of a sprite cell
  58494. * @param scene defines the hosting scene
  58495. * @param epsilon defines the epsilon value to align texture (0.01 by default)
  58496. * @param samplingMode defines the smapling mode to use with spritesheet
  58497. */
  58498. function SpriteManager(
  58499. /** defines the manager's name */
  58500. name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  58501. if (epsilon === void 0) { epsilon = 0.01; }
  58502. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58503. this.name = name;
  58504. /** Gets the list of sprites */
  58505. this.sprites = new Array();
  58506. /** Gets or sets the rendering group id (0 by default) */
  58507. this.renderingGroupId = 0;
  58508. /** Gets or sets camera layer mask */
  58509. this.layerMask = 0x0FFFFFFF;
  58510. /** Gets or sets a boolean indicating if the manager must consider scene fog when rendering */
  58511. this.fogEnabled = true;
  58512. /** Gets or sets a boolean indicating if the sprites are pickable */
  58513. this.isPickable = false;
  58514. /**
  58515. * An event triggered when the manager is disposed.
  58516. */
  58517. this.onDisposeObservable = new BABYLON.Observable();
  58518. this._vertexBuffers = {};
  58519. if (!scene._getComponent(BABYLON.SceneComponentConstants.NAME_SPRITE)) {
  58520. scene._addComponent(new BABYLON.SpriteSceneComponent(scene));
  58521. }
  58522. this._capacity = capacity;
  58523. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  58524. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58525. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58526. if (cellSize.width && cellSize.height) {
  58527. this.cellWidth = cellSize.width;
  58528. this.cellHeight = cellSize.height;
  58529. }
  58530. else if (cellSize !== undefined) {
  58531. this.cellWidth = cellSize;
  58532. this.cellHeight = cellSize;
  58533. }
  58534. else {
  58535. return;
  58536. }
  58537. this._epsilon = epsilon;
  58538. this._scene = scene;
  58539. this._scene.spriteManagers.push(this);
  58540. var indices = [];
  58541. var index = 0;
  58542. for (var count = 0; count < capacity; count++) {
  58543. indices.push(index);
  58544. indices.push(index + 1);
  58545. indices.push(index + 2);
  58546. indices.push(index);
  58547. indices.push(index + 2);
  58548. indices.push(index + 3);
  58549. index += 4;
  58550. }
  58551. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  58552. // VBO
  58553. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  58554. this._vertexData = new Float32Array(capacity * 16 * 4);
  58555. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  58556. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  58557. var options = this._buffer.createVertexBuffer("options", 4, 4);
  58558. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  58559. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  58560. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  58561. this._vertexBuffers["options"] = options;
  58562. this._vertexBuffers["cellInfo"] = cellInfo;
  58563. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  58564. // Effects
  58565. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  58566. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  58567. }
  58568. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  58569. /**
  58570. * Callback called when the manager is disposed
  58571. */
  58572. set: function (callback) {
  58573. if (this._onDisposeObserver) {
  58574. this.onDisposeObservable.remove(this._onDisposeObserver);
  58575. }
  58576. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  58577. },
  58578. enumerable: true,
  58579. configurable: true
  58580. });
  58581. Object.defineProperty(SpriteManager.prototype, "texture", {
  58582. /**
  58583. * Gets or sets the spritesheet texture
  58584. */
  58585. get: function () {
  58586. return this._spriteTexture;
  58587. },
  58588. set: function (value) {
  58589. this._spriteTexture = value;
  58590. },
  58591. enumerable: true,
  58592. configurable: true
  58593. });
  58594. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  58595. var arrayOffset = index * 16;
  58596. if (offsetX === 0) {
  58597. offsetX = this._epsilon;
  58598. }
  58599. else if (offsetX === 1) {
  58600. offsetX = 1 - this._epsilon;
  58601. }
  58602. if (offsetY === 0) {
  58603. offsetY = this._epsilon;
  58604. }
  58605. else if (offsetY === 1) {
  58606. offsetY = 1 - this._epsilon;
  58607. }
  58608. this._vertexData[arrayOffset] = sprite.position.x;
  58609. this._vertexData[arrayOffset + 1] = sprite.position.y;
  58610. this._vertexData[arrayOffset + 2] = sprite.position.z;
  58611. this._vertexData[arrayOffset + 3] = sprite.angle;
  58612. this._vertexData[arrayOffset + 4] = sprite.width;
  58613. this._vertexData[arrayOffset + 5] = sprite.height;
  58614. this._vertexData[arrayOffset + 6] = offsetX;
  58615. this._vertexData[arrayOffset + 7] = offsetY;
  58616. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  58617. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  58618. var offset = (sprite.cellIndex / rowSize) >> 0;
  58619. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  58620. this._vertexData[arrayOffset + 11] = offset;
  58621. // Color
  58622. this._vertexData[arrayOffset + 12] = sprite.color.r;
  58623. this._vertexData[arrayOffset + 13] = sprite.color.g;
  58624. this._vertexData[arrayOffset + 14] = sprite.color.b;
  58625. this._vertexData[arrayOffset + 15] = sprite.color.a;
  58626. };
  58627. /**
  58628. * Intersects the sprites with a ray
  58629. * @param ray defines the ray to intersect with
  58630. * @param camera defines the current active camera
  58631. * @param predicate defines a predicate used to select candidate sprites
  58632. * @param fastCheck defines if a fast check only must be done (the first potential sprite is will be used and not the closer)
  58633. * @returns null if no hit or a PickingInfo
  58634. */
  58635. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  58636. var count = Math.min(this._capacity, this.sprites.length);
  58637. var min = BABYLON.Vector3.Zero();
  58638. var max = BABYLON.Vector3.Zero();
  58639. var distance = Number.MAX_VALUE;
  58640. var currentSprite = null;
  58641. var cameraSpacePosition = BABYLON.Vector3.Zero();
  58642. var cameraView = camera.getViewMatrix();
  58643. for (var index = 0; index < count; index++) {
  58644. var sprite = this.sprites[index];
  58645. if (!sprite) {
  58646. continue;
  58647. }
  58648. if (predicate) {
  58649. if (!predicate(sprite)) {
  58650. continue;
  58651. }
  58652. }
  58653. else if (!sprite.isPickable) {
  58654. continue;
  58655. }
  58656. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  58657. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  58658. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  58659. if (ray.intersectsBoxMinMax(min, max)) {
  58660. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  58661. if (distance > currentDistance) {
  58662. distance = currentDistance;
  58663. currentSprite = sprite;
  58664. if (fastCheck) {
  58665. break;
  58666. }
  58667. }
  58668. }
  58669. }
  58670. if (currentSprite) {
  58671. var result = new BABYLON.PickingInfo();
  58672. result.hit = true;
  58673. result.pickedSprite = currentSprite;
  58674. result.distance = distance;
  58675. return result;
  58676. }
  58677. return null;
  58678. };
  58679. /**
  58680. * Render all child sprites
  58681. */
  58682. SpriteManager.prototype.render = function () {
  58683. // Check
  58684. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady()) {
  58685. return;
  58686. }
  58687. var engine = this._scene.getEngine();
  58688. var baseSize = this._spriteTexture.getBaseSize();
  58689. // Sprites
  58690. var deltaTime = engine.getDeltaTime();
  58691. var max = Math.min(this._capacity, this.sprites.length);
  58692. var rowSize = baseSize.width / this.cellWidth;
  58693. var offset = 0;
  58694. for (var index = 0; index < max; index++) {
  58695. var sprite = this.sprites[index];
  58696. if (!sprite || !sprite.isVisible) {
  58697. continue;
  58698. }
  58699. sprite._animate(deltaTime);
  58700. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  58701. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  58702. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  58703. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  58704. }
  58705. this._buffer.update(this._vertexData);
  58706. // Render
  58707. var effect = this._effectBase;
  58708. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  58709. effect = this._effectFog;
  58710. }
  58711. engine.enableEffect(effect);
  58712. var viewMatrix = this._scene.getViewMatrix();
  58713. effect.setTexture("diffuseSampler", this._spriteTexture);
  58714. effect.setMatrix("view", viewMatrix);
  58715. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  58716. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  58717. // Fog
  58718. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  58719. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  58720. effect.setColor3("vFogColor", this._scene.fogColor);
  58721. }
  58722. // VBOs
  58723. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  58724. // Draw order
  58725. engine.setDepthFunctionToLessOrEqual();
  58726. effect.setBool("alphaTest", true);
  58727. engine.setColorWrite(false);
  58728. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  58729. engine.setColorWrite(true);
  58730. effect.setBool("alphaTest", false);
  58731. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  58732. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  58733. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  58734. };
  58735. /**
  58736. * Release associated resources
  58737. */
  58738. SpriteManager.prototype.dispose = function () {
  58739. if (this._buffer) {
  58740. this._buffer.dispose();
  58741. this._buffer = null;
  58742. }
  58743. if (this._indexBuffer) {
  58744. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  58745. this._indexBuffer = null;
  58746. }
  58747. if (this._spriteTexture) {
  58748. this._spriteTexture.dispose();
  58749. this._spriteTexture = null;
  58750. }
  58751. // Remove from scene
  58752. var index = this._scene.spriteManagers.indexOf(this);
  58753. this._scene.spriteManagers.splice(index, 1);
  58754. // Callback
  58755. this.onDisposeObservable.notifyObservers(this);
  58756. this.onDisposeObservable.clear();
  58757. };
  58758. return SpriteManager;
  58759. }());
  58760. BABYLON.SpriteManager = SpriteManager;
  58761. })(BABYLON || (BABYLON = {}));
  58762. //# sourceMappingURL=babylon.spriteManager.js.map
  58763. var BABYLON;
  58764. (function (BABYLON) {
  58765. /**
  58766. * Class used to represent a sprite
  58767. * @see http://doc.babylonjs.com/babylon101/sprites
  58768. */
  58769. var Sprite = /** @class */ (function () {
  58770. /**
  58771. * Creates a new Sprite
  58772. * @param name defines the name
  58773. * @param manager defines the manager
  58774. */
  58775. function Sprite(
  58776. /** defines the name */
  58777. name, manager) {
  58778. this.name = name;
  58779. /** Gets or sets the main color */
  58780. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  58781. /** Gets or sets the width */
  58782. this.width = 1.0;
  58783. /** Gets or sets the height */
  58784. this.height = 1.0;
  58785. /** Gets or sets rotation angle */
  58786. this.angle = 0;
  58787. /** Gets or sets the cell index in the sprite sheet */
  58788. this.cellIndex = 0;
  58789. /** Gets or sets a boolean indicating if UV coordinates should be inverted in U axis */
  58790. this.invertU = 0;
  58791. /** Gets or sets a boolean indicating if UV coordinates should be inverted in B axis */
  58792. this.invertV = 0;
  58793. /** Gets the list of attached animations */
  58794. this.animations = new Array();
  58795. /** Gets or sets a boolean indicating if the sprite can be picked */
  58796. this.isPickable = false;
  58797. this._animationStarted = false;
  58798. this._loopAnimation = false;
  58799. this._fromIndex = 0;
  58800. this._toIndex = 0;
  58801. this._delay = 0;
  58802. this._direction = 1;
  58803. this._time = 0;
  58804. /**
  58805. * Gets or sets a boolean indicating if the sprite is visible (renderable). Default is true
  58806. */
  58807. this.isVisible = true;
  58808. this._manager = manager;
  58809. this._manager.sprites.push(this);
  58810. this.position = BABYLON.Vector3.Zero();
  58811. }
  58812. Object.defineProperty(Sprite.prototype, "size", {
  58813. /**
  58814. * Gets or sets the sprite size
  58815. */
  58816. get: function () {
  58817. return this.width;
  58818. },
  58819. set: function (value) {
  58820. this.width = value;
  58821. this.height = value;
  58822. },
  58823. enumerable: true,
  58824. configurable: true
  58825. });
  58826. /**
  58827. * Starts an animation
  58828. * @param from defines the initial key
  58829. * @param to defines the end key
  58830. * @param loop defines if the animation must loop
  58831. * @param delay defines the start delay (in ms)
  58832. * @param onAnimationEnd defines a callback to call when animation ends
  58833. */
  58834. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  58835. this._fromIndex = from;
  58836. this._toIndex = to;
  58837. this._loopAnimation = loop;
  58838. this._delay = delay;
  58839. this._animationStarted = true;
  58840. this._direction = from < to ? 1 : -1;
  58841. this.cellIndex = from;
  58842. this._time = 0;
  58843. this._onAnimationEnd = onAnimationEnd;
  58844. };
  58845. /** Stops current animation (if any) */
  58846. Sprite.prototype.stopAnimation = function () {
  58847. this._animationStarted = false;
  58848. };
  58849. /** @hidden */
  58850. Sprite.prototype._animate = function (deltaTime) {
  58851. if (!this._animationStarted) {
  58852. return;
  58853. }
  58854. this._time += deltaTime;
  58855. if (this._time > this._delay) {
  58856. this._time = this._time % this._delay;
  58857. this.cellIndex += this._direction;
  58858. if (this.cellIndex > this._toIndex) {
  58859. if (this._loopAnimation) {
  58860. this.cellIndex = this._fromIndex;
  58861. }
  58862. else {
  58863. this.cellIndex = this._toIndex;
  58864. this._animationStarted = false;
  58865. if (this._onAnimationEnd) {
  58866. this._onAnimationEnd();
  58867. }
  58868. if (this.disposeWhenFinishedAnimating) {
  58869. this.dispose();
  58870. }
  58871. }
  58872. }
  58873. }
  58874. };
  58875. /** Release associated resources */
  58876. Sprite.prototype.dispose = function () {
  58877. for (var i = 0; i < this._manager.sprites.length; i++) {
  58878. if (this._manager.sprites[i] == this) {
  58879. this._manager.sprites.splice(i, 1);
  58880. }
  58881. }
  58882. };
  58883. return Sprite;
  58884. }());
  58885. BABYLON.Sprite = Sprite;
  58886. })(BABYLON || (BABYLON = {}));
  58887. //# sourceMappingURL=babylon.sprite.js.map
  58888. var BABYLON;
  58889. (function (BABYLON) {
  58890. BABYLON.Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  58891. if (!BABYLON.PickingInfo) {
  58892. return null;
  58893. }
  58894. var pickingInfo = null;
  58895. if (!camera) {
  58896. if (!this.activeCamera) {
  58897. return null;
  58898. }
  58899. camera = this.activeCamera;
  58900. }
  58901. if (this.spriteManagers.length > 0) {
  58902. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  58903. var spriteManager = this.spriteManagers[spriteIndex];
  58904. if (!spriteManager.isPickable) {
  58905. continue;
  58906. }
  58907. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  58908. if (!result || !result.hit) {
  58909. continue;
  58910. }
  58911. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance) {
  58912. continue;
  58913. }
  58914. pickingInfo = result;
  58915. if (fastCheck) {
  58916. break;
  58917. }
  58918. }
  58919. }
  58920. return pickingInfo || new BABYLON.PickingInfo();
  58921. };
  58922. BABYLON.Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  58923. this.createPickingRayInCameraSpaceToRef(x, y, this._tempSpritePickingRay, camera);
  58924. return this._internalPickSprites(this._tempSpritePickingRay, predicate, fastCheck, camera);
  58925. };
  58926. BABYLON.Scene.prototype.pickSpriteWithRay = function (ray, predicate, fastCheck, camera) {
  58927. if (!this._tempSpritePickingRay) {
  58928. return null;
  58929. }
  58930. if (!camera) {
  58931. if (!this.activeCamera) {
  58932. return null;
  58933. }
  58934. camera = this.activeCamera;
  58935. }
  58936. BABYLON.Ray.TransformToRef(ray, camera.getViewMatrix(), this._tempSpritePickingRay);
  58937. return this._internalPickSprites(this._tempSpritePickingRay, predicate, fastCheck, camera);
  58938. };
  58939. BABYLON.Scene.prototype.setPointerOverSprite = function (sprite) {
  58940. if (this._pointerOverSprite === sprite) {
  58941. return;
  58942. }
  58943. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  58944. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  58945. }
  58946. this._pointerOverSprite = sprite;
  58947. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  58948. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  58949. }
  58950. };
  58951. BABYLON.Scene.prototype.getPointerOverSprite = function () {
  58952. return this._pointerOverSprite;
  58953. };
  58954. /**
  58955. * Defines the sprite scene component responsible to manage sprites
  58956. * in a given scene.
  58957. */
  58958. var SpriteSceneComponent = /** @class */ (function () {
  58959. /**
  58960. * Creates a new instance of the component for the given scene
  58961. * @param scene Defines the scene to register the component in
  58962. */
  58963. function SpriteSceneComponent(scene) {
  58964. /**
  58965. * The component name helpfull to identify the component in the list of scene components.
  58966. */
  58967. this.name = BABYLON.SceneComponentConstants.NAME_SPRITE;
  58968. this.scene = scene;
  58969. this.scene.spriteManagers = new Array();
  58970. this.scene._tempSpritePickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  58971. this.scene.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  58972. this.scene.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  58973. this._spritePredicate = function (sprite) {
  58974. if (!sprite.actionManager) {
  58975. return false;
  58976. }
  58977. return sprite.isPickable && sprite.actionManager.hasPointerTriggers;
  58978. };
  58979. }
  58980. /**
  58981. * Registers the component in a given scene
  58982. */
  58983. SpriteSceneComponent.prototype.register = function () {
  58984. this.scene._pointerMoveStage.registerStep(BABYLON.SceneComponentConstants.STEP_POINTERMOVE_SPRITE, this, this._pointerMove);
  58985. this.scene._pointerDownStage.registerStep(BABYLON.SceneComponentConstants.STEP_POINTERDOWN_SPRITE, this, this._pointerDown);
  58986. this.scene._pointerUpStage.registerStep(BABYLON.SceneComponentConstants.STEP_POINTERUP_SPRITE, this, this._pointerUp);
  58987. };
  58988. /**
  58989. * Rebuilds the elements related to this component in case of
  58990. * context lost for instance.
  58991. */
  58992. SpriteSceneComponent.prototype.rebuild = function () {
  58993. /** Nothing to do for sprites */
  58994. };
  58995. /**
  58996. * Disposes the component and the associated ressources.
  58997. */
  58998. SpriteSceneComponent.prototype.dispose = function () {
  58999. this.scene.onBeforeSpritesRenderingObservable.clear();
  59000. this.scene.onAfterSpritesRenderingObservable.clear();
  59001. var spriteManagers = this.scene.spriteManagers;
  59002. while (spriteManagers.length) {
  59003. spriteManagers[0].dispose();
  59004. }
  59005. };
  59006. SpriteSceneComponent.prototype._pickSpriteButKeepRay = function (originalPointerInfo, x, y, fastCheck, camera) {
  59007. var result = this.scene.pickSprite(x, y, this._spritePredicate, fastCheck, camera);
  59008. if (result) {
  59009. result.ray = originalPointerInfo ? originalPointerInfo.ray : null;
  59010. }
  59011. return result;
  59012. };
  59013. SpriteSceneComponent.prototype._pointerMove = function (unTranslatedPointerX, unTranslatedPointerY, pickResult, isMeshPicked, canvas) {
  59014. var scene = this.scene;
  59015. if (isMeshPicked) {
  59016. scene.setPointerOverSprite(null);
  59017. }
  59018. else {
  59019. pickResult = this._pickSpriteButKeepRay(pickResult, unTranslatedPointerX, unTranslatedPointerY, false, scene.cameraToUseForPointers || undefined);
  59020. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  59021. scene.setPointerOverSprite(pickResult.pickedSprite);
  59022. if (scene._pointerOverSprite && scene._pointerOverSprite.actionManager && scene._pointerOverSprite.actionManager.hoverCursor) {
  59023. canvas.style.cursor = scene._pointerOverSprite.actionManager.hoverCursor;
  59024. }
  59025. else {
  59026. canvas.style.cursor = scene.hoverCursor;
  59027. }
  59028. }
  59029. else {
  59030. scene.setPointerOverSprite(null);
  59031. }
  59032. }
  59033. return pickResult;
  59034. };
  59035. SpriteSceneComponent.prototype._pointerDown = function (unTranslatedPointerX, unTranslatedPointerY, pickResult, evt) {
  59036. var scene = this.scene;
  59037. scene._pickedDownSprite = null;
  59038. if (scene.spriteManagers.length > 0) {
  59039. pickResult = scene.pickSprite(unTranslatedPointerX, unTranslatedPointerY, this._spritePredicate, false, scene.cameraToUseForPointers || undefined);
  59040. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  59041. if (pickResult.pickedSprite.actionManager) {
  59042. scene._pickedDownSprite = pickResult.pickedSprite;
  59043. switch (evt.button) {
  59044. case 0:
  59045. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  59046. break;
  59047. case 1:
  59048. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  59049. break;
  59050. case 2:
  59051. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  59052. break;
  59053. }
  59054. if (pickResult.pickedSprite.actionManager) {
  59055. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  59056. }
  59057. }
  59058. }
  59059. }
  59060. return pickResult;
  59061. };
  59062. SpriteSceneComponent.prototype._pointerUp = function (unTranslatedPointerX, unTranslatedPointerY, pickResult, evt) {
  59063. var scene = this.scene;
  59064. if (scene.spriteManagers.length > 0) {
  59065. var spritePickResult = scene.pickSprite(unTranslatedPointerX, unTranslatedPointerY, this._spritePredicate, false, scene.cameraToUseForPointers || undefined);
  59066. if (spritePickResult) {
  59067. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  59068. if (spritePickResult.pickedSprite.actionManager) {
  59069. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, scene, evt));
  59070. if (spritePickResult.pickedSprite.actionManager) {
  59071. if (!this.scene._isPointerSwiping()) {
  59072. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, scene, evt));
  59073. }
  59074. }
  59075. }
  59076. }
  59077. if (scene._pickedDownSprite && scene._pickedDownSprite.actionManager && scene._pickedDownSprite !== spritePickResult.pickedSprite) {
  59078. scene._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(scene._pickedDownSprite, scene, evt));
  59079. }
  59080. }
  59081. }
  59082. return pickResult;
  59083. };
  59084. return SpriteSceneComponent;
  59085. }());
  59086. BABYLON.SpriteSceneComponent = SpriteSceneComponent;
  59087. })(BABYLON || (BABYLON = {}));
  59088. //# sourceMappingURL=babylon.spriteSceneComponent.js.map
  59089. var BABYLON;
  59090. (function (BABYLON) {
  59091. /**
  59092. * @hidden
  59093. */
  59094. var IntersectionInfo = /** @class */ (function () {
  59095. function IntersectionInfo(bu, bv, distance) {
  59096. this.bu = bu;
  59097. this.bv = bv;
  59098. this.distance = distance;
  59099. this.faceId = 0;
  59100. this.subMeshId = 0;
  59101. }
  59102. return IntersectionInfo;
  59103. }());
  59104. BABYLON.IntersectionInfo = IntersectionInfo;
  59105. /**
  59106. * Information about the result of picking within a scene
  59107. * @see https://doc.babylonjs.com/babylon101/picking_collisions
  59108. */
  59109. var PickingInfo = /** @class */ (function () {
  59110. function PickingInfo() {
  59111. /**
  59112. * If the pick collided with an object
  59113. */
  59114. this.hit = false;
  59115. /**
  59116. * Distance away where the pick collided
  59117. */
  59118. this.distance = 0;
  59119. /**
  59120. * The location of pick collision
  59121. */
  59122. this.pickedPoint = null;
  59123. /**
  59124. * The mesh corresponding the the pick collision
  59125. */
  59126. this.pickedMesh = null;
  59127. /** (See getTextureCoordinates) The barycentric U coordinate that is used when calulating the texture coordinates of the collision.*/
  59128. this.bu = 0;
  59129. /** (See getTextureCoordinates) The barycentric V coordinate that is used when calulating the texture coordinates of the collision.*/
  59130. this.bv = 0;
  59131. /** The index of the face on the mesh that was picked, or the index of the Line if the picked Mesh is a LinesMesh */
  59132. this.faceId = -1;
  59133. /** Id of the the submesh that was picked */
  59134. this.subMeshId = 0;
  59135. /** If a sprite was picked, this will be the sprite the pick collided with */
  59136. this.pickedSprite = null;
  59137. /**
  59138. * If a mesh was used to do the picking (eg. 6dof controller) this will be populated.
  59139. */
  59140. this.originMesh = null;
  59141. /**
  59142. * The ray that was used to perform the picking.
  59143. */
  59144. this.ray = null;
  59145. }
  59146. /**
  59147. * Gets the normal correspodning to the face the pick collided with
  59148. * @param useWorldCoordinates If the resulting normal should be relative to the world (default: false)
  59149. * @param useVerticesNormals If the vertices normals should be used to calculate the normal instead of the normal map
  59150. * @returns The normal correspodning to the face the pick collided with
  59151. */
  59152. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  59153. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  59154. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  59155. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  59156. return null;
  59157. }
  59158. var indices = this.pickedMesh.getIndices();
  59159. if (!indices) {
  59160. return null;
  59161. }
  59162. var result;
  59163. if (useVerticesNormals) {
  59164. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  59165. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  59166. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  59167. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  59168. normal0 = normal0.scale(this.bu);
  59169. normal1 = normal1.scale(this.bv);
  59170. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  59171. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  59172. }
  59173. else {
  59174. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  59175. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  59176. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  59177. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  59178. var p1p2 = vertex1.subtract(vertex2);
  59179. var p3p2 = vertex3.subtract(vertex2);
  59180. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  59181. }
  59182. if (useWorldCoordinates) {
  59183. var wm = this.pickedMesh.getWorldMatrix();
  59184. if (this.pickedMesh.nonUniformScaling) {
  59185. BABYLON.Tmp.Matrix[0].copyFrom(wm);
  59186. wm = BABYLON.Tmp.Matrix[0];
  59187. wm.setTranslationFromFloats(0, 0, 0);
  59188. wm.invert();
  59189. wm.transposeToRef(BABYLON.Tmp.Matrix[1]);
  59190. wm = BABYLON.Tmp.Matrix[1];
  59191. }
  59192. result = BABYLON.Vector3.TransformNormal(result, wm);
  59193. }
  59194. result.normalize();
  59195. return result;
  59196. };
  59197. /**
  59198. * Gets the texture coordinates of where the pick occured
  59199. * @returns the vector containing the coordnates of the texture
  59200. */
  59201. PickingInfo.prototype.getTextureCoordinates = function () {
  59202. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  59203. return null;
  59204. }
  59205. var indices = this.pickedMesh.getIndices();
  59206. if (!indices) {
  59207. return null;
  59208. }
  59209. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  59210. if (!uvs) {
  59211. return null;
  59212. }
  59213. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  59214. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  59215. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  59216. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  59217. uv1 = uv1.scale(this.bu);
  59218. uv2 = uv2.scale(this.bv);
  59219. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  59220. };
  59221. return PickingInfo;
  59222. }());
  59223. BABYLON.PickingInfo = PickingInfo;
  59224. })(BABYLON || (BABYLON = {}));
  59225. //# sourceMappingURL=babylon.pickingInfo.js.map
  59226. var BABYLON;
  59227. (function (BABYLON) {
  59228. /**
  59229. * Class representing a ray with position and direction
  59230. */
  59231. var Ray = /** @class */ (function () {
  59232. /**
  59233. * Creates a new ray
  59234. * @param origin origin point
  59235. * @param direction direction
  59236. * @param length length of the ray
  59237. */
  59238. function Ray(
  59239. /** origin point */
  59240. origin,
  59241. /** direction */
  59242. direction,
  59243. /** length of the ray */
  59244. length) {
  59245. if (length === void 0) { length = Number.MAX_VALUE; }
  59246. this.origin = origin;
  59247. this.direction = direction;
  59248. this.length = length;
  59249. }
  59250. // Methods
  59251. /**
  59252. * Checks if the ray intersects a box
  59253. * @param minimum bound of the box
  59254. * @param maximum bound of the box
  59255. * @param intersectionTreshold extra extend to be added to the box in all direction
  59256. * @returns if the box was hit
  59257. */
  59258. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum, intersectionTreshold) {
  59259. if (intersectionTreshold === void 0) { intersectionTreshold = 0; }
  59260. var newMinimum = Ray.TmpVector3[0].copyFromFloats(minimum.x - intersectionTreshold, minimum.y - intersectionTreshold, minimum.z - intersectionTreshold);
  59261. var newMaximum = Ray.TmpVector3[1].copyFromFloats(maximum.x + intersectionTreshold, maximum.y + intersectionTreshold, maximum.z + intersectionTreshold);
  59262. var d = 0.0;
  59263. var maxValue = Number.MAX_VALUE;
  59264. var inv;
  59265. var min;
  59266. var max;
  59267. var temp;
  59268. if (Math.abs(this.direction.x) < 0.0000001) {
  59269. if (this.origin.x < newMinimum.x || this.origin.x > newMaximum.x) {
  59270. return false;
  59271. }
  59272. }
  59273. else {
  59274. inv = 1.0 / this.direction.x;
  59275. min = (newMinimum.x - this.origin.x) * inv;
  59276. max = (newMaximum.x - this.origin.x) * inv;
  59277. if (max === -Infinity) {
  59278. max = Infinity;
  59279. }
  59280. if (min > max) {
  59281. temp = min;
  59282. min = max;
  59283. max = temp;
  59284. }
  59285. d = Math.max(min, d);
  59286. maxValue = Math.min(max, maxValue);
  59287. if (d > maxValue) {
  59288. return false;
  59289. }
  59290. }
  59291. if (Math.abs(this.direction.y) < 0.0000001) {
  59292. if (this.origin.y < newMinimum.y || this.origin.y > newMaximum.y) {
  59293. return false;
  59294. }
  59295. }
  59296. else {
  59297. inv = 1.0 / this.direction.y;
  59298. min = (newMinimum.y - this.origin.y) * inv;
  59299. max = (newMaximum.y - this.origin.y) * inv;
  59300. if (max === -Infinity) {
  59301. max = Infinity;
  59302. }
  59303. if (min > max) {
  59304. temp = min;
  59305. min = max;
  59306. max = temp;
  59307. }
  59308. d = Math.max(min, d);
  59309. maxValue = Math.min(max, maxValue);
  59310. if (d > maxValue) {
  59311. return false;
  59312. }
  59313. }
  59314. if (Math.abs(this.direction.z) < 0.0000001) {
  59315. if (this.origin.z < newMinimum.z || this.origin.z > newMaximum.z) {
  59316. return false;
  59317. }
  59318. }
  59319. else {
  59320. inv = 1.0 / this.direction.z;
  59321. min = (newMinimum.z - this.origin.z) * inv;
  59322. max = (newMaximum.z - this.origin.z) * inv;
  59323. if (max === -Infinity) {
  59324. max = Infinity;
  59325. }
  59326. if (min > max) {
  59327. temp = min;
  59328. min = max;
  59329. max = temp;
  59330. }
  59331. d = Math.max(min, d);
  59332. maxValue = Math.min(max, maxValue);
  59333. if (d > maxValue) {
  59334. return false;
  59335. }
  59336. }
  59337. return true;
  59338. };
  59339. /**
  59340. * Checks if the ray intersects a box
  59341. * @param box the bounding box to check
  59342. * @param intersectionTreshold extra extend to be added to the BoundingBox in all direction
  59343. * @returns if the box was hit
  59344. */
  59345. Ray.prototype.intersectsBox = function (box, intersectionTreshold) {
  59346. if (intersectionTreshold === void 0) { intersectionTreshold = 0; }
  59347. return this.intersectsBoxMinMax(box.minimum, box.maximum, intersectionTreshold);
  59348. };
  59349. /**
  59350. * If the ray hits a sphere
  59351. * @param sphere the bounding sphere to check
  59352. * @param intersectionTreshold extra extend to be added to the BoundingSphere in all direction
  59353. * @returns true if it hits the sphere
  59354. */
  59355. Ray.prototype.intersectsSphere = function (sphere, intersectionTreshold) {
  59356. if (intersectionTreshold === void 0) { intersectionTreshold = 0; }
  59357. var x = sphere.center.x - this.origin.x;
  59358. var y = sphere.center.y - this.origin.y;
  59359. var z = sphere.center.z - this.origin.z;
  59360. var pyth = (x * x) + (y * y) + (z * z);
  59361. var radius = sphere.radius + intersectionTreshold;
  59362. var rr = radius * radius;
  59363. if (pyth <= rr) {
  59364. return true;
  59365. }
  59366. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  59367. if (dot < 0.0) {
  59368. return false;
  59369. }
  59370. var temp = pyth - (dot * dot);
  59371. return temp <= rr;
  59372. };
  59373. /**
  59374. * If the ray hits a triange
  59375. * @param vertex0 triangle vertex
  59376. * @param vertex1 triangle vertex
  59377. * @param vertex2 triangle vertex
  59378. * @returns intersection information if hit
  59379. */
  59380. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  59381. var edge1 = Ray.TmpVector3[0];
  59382. var edge2 = Ray.TmpVector3[1];
  59383. var pvec = Ray.TmpVector3[2];
  59384. var tvec = Ray.TmpVector3[3];
  59385. var qvec = Ray.TmpVector3[4];
  59386. vertex1.subtractToRef(vertex0, edge1);
  59387. vertex2.subtractToRef(vertex0, edge2);
  59388. BABYLON.Vector3.CrossToRef(this.direction, edge2, pvec);
  59389. var det = BABYLON.Vector3.Dot(edge1, pvec);
  59390. if (det === 0) {
  59391. return null;
  59392. }
  59393. var invdet = 1 / det;
  59394. this.origin.subtractToRef(vertex0, tvec);
  59395. var bu = BABYLON.Vector3.Dot(tvec, pvec) * invdet;
  59396. if (bu < 0 || bu > 1.0) {
  59397. return null;
  59398. }
  59399. BABYLON.Vector3.CrossToRef(tvec, edge1, qvec);
  59400. var bv = BABYLON.Vector3.Dot(this.direction, qvec) * invdet;
  59401. if (bv < 0 || bu + bv > 1.0) {
  59402. return null;
  59403. }
  59404. //check if the distance is longer than the predefined length.
  59405. var distance = BABYLON.Vector3.Dot(edge2, qvec) * invdet;
  59406. if (distance > this.length) {
  59407. return null;
  59408. }
  59409. return new BABYLON.IntersectionInfo(bu, bv, distance);
  59410. };
  59411. /**
  59412. * Checks if ray intersects a plane
  59413. * @param plane the plane to check
  59414. * @returns the distance away it was hit
  59415. */
  59416. Ray.prototype.intersectsPlane = function (plane) {
  59417. var distance;
  59418. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  59419. if (Math.abs(result1) < 9.99999997475243E-07) {
  59420. return null;
  59421. }
  59422. else {
  59423. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  59424. distance = (-plane.d - result2) / result1;
  59425. if (distance < 0.0) {
  59426. if (distance < -9.99999997475243E-07) {
  59427. return null;
  59428. }
  59429. else {
  59430. return 0;
  59431. }
  59432. }
  59433. return distance;
  59434. }
  59435. };
  59436. /**
  59437. * Checks if ray intersects a mesh
  59438. * @param mesh the mesh to check
  59439. * @param fastCheck if only the bounding box should checked
  59440. * @returns picking info of the intersecton
  59441. */
  59442. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  59443. var tm = BABYLON.Tmp.Matrix[0];
  59444. mesh.getWorldMatrix().invertToRef(tm);
  59445. if (this._tmpRay) {
  59446. Ray.TransformToRef(this, tm, this._tmpRay);
  59447. }
  59448. else {
  59449. this._tmpRay = Ray.Transform(this, tm);
  59450. }
  59451. return mesh.intersects(this._tmpRay, fastCheck);
  59452. };
  59453. /**
  59454. * Checks if ray intersects a mesh
  59455. * @param meshes the meshes to check
  59456. * @param fastCheck if only the bounding box should checked
  59457. * @param results array to store result in
  59458. * @returns Array of picking infos
  59459. */
  59460. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  59461. if (results) {
  59462. results.length = 0;
  59463. }
  59464. else {
  59465. results = [];
  59466. }
  59467. for (var i = 0; i < meshes.length; i++) {
  59468. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  59469. if (pickInfo.hit) {
  59470. results.push(pickInfo);
  59471. }
  59472. }
  59473. results.sort(this._comparePickingInfo);
  59474. return results;
  59475. };
  59476. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  59477. if (pickingInfoA.distance < pickingInfoB.distance) {
  59478. return -1;
  59479. }
  59480. else if (pickingInfoA.distance > pickingInfoB.distance) {
  59481. return 1;
  59482. }
  59483. else {
  59484. return 0;
  59485. }
  59486. };
  59487. /**
  59488. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  59489. * @param sega the first point of the segment to test the intersection against
  59490. * @param segb the second point of the segment to test the intersection against
  59491. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  59492. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  59493. */
  59494. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  59495. var o = this.origin;
  59496. var u = BABYLON.Tmp.Vector3[0];
  59497. var rsegb = BABYLON.Tmp.Vector3[1];
  59498. var v = BABYLON.Tmp.Vector3[2];
  59499. var w = BABYLON.Tmp.Vector3[3];
  59500. segb.subtractToRef(sega, u);
  59501. this.direction.scaleToRef(Ray.rayl, v);
  59502. o.addToRef(v, rsegb);
  59503. sega.subtractToRef(o, w);
  59504. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  59505. var b = BABYLON.Vector3.Dot(u, v);
  59506. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  59507. var d = BABYLON.Vector3.Dot(u, w);
  59508. var e = BABYLON.Vector3.Dot(v, w);
  59509. var D = a * c - b * b; // always >= 0
  59510. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  59511. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  59512. // compute the line parameters of the two closest points
  59513. if (D < Ray.smallnum) { // the lines are almost parallel
  59514. sN = 0.0; // force using point P0 on segment S1
  59515. sD = 1.0; // to prevent possible division by 0.0 later
  59516. tN = e;
  59517. tD = c;
  59518. }
  59519. else { // get the closest points on the infinite lines
  59520. sN = (b * e - c * d);
  59521. tN = (a * e - b * d);
  59522. if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
  59523. sN = 0.0;
  59524. tN = e;
  59525. tD = c;
  59526. }
  59527. else if (sN > sD) { // sc > 1 => the s=1 edge is visible
  59528. sN = sD;
  59529. tN = e + b;
  59530. tD = c;
  59531. }
  59532. }
  59533. if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
  59534. tN = 0.0;
  59535. // recompute sc for this edge
  59536. if (-d < 0.0) {
  59537. sN = 0.0;
  59538. }
  59539. else if (-d > a) {
  59540. sN = sD;
  59541. }
  59542. else {
  59543. sN = -d;
  59544. sD = a;
  59545. }
  59546. }
  59547. else if (tN > tD) { // tc > 1 => the t=1 edge is visible
  59548. tN = tD;
  59549. // recompute sc for this edge
  59550. if ((-d + b) < 0.0) {
  59551. sN = 0;
  59552. }
  59553. else if ((-d + b) > a) {
  59554. sN = sD;
  59555. }
  59556. else {
  59557. sN = (-d + b);
  59558. sD = a;
  59559. }
  59560. }
  59561. // finally do the division to get sc and tc
  59562. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  59563. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  59564. // get the difference of the two closest points
  59565. var qtc = BABYLON.Tmp.Vector3[4];
  59566. v.scaleToRef(tc, qtc);
  59567. var qsc = BABYLON.Tmp.Vector3[5];
  59568. u.scaleToRef(sc, qsc);
  59569. qsc.addInPlace(w);
  59570. var dP = BABYLON.Tmp.Vector3[6];
  59571. qsc.subtractToRef(qtc, dP); // = S1(sc) - S2(tc)
  59572. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  59573. if (isIntersected) {
  59574. return qsc.length();
  59575. }
  59576. return -1;
  59577. };
  59578. /**
  59579. * Update the ray from viewport position
  59580. * @param x position
  59581. * @param y y position
  59582. * @param viewportWidth viewport width
  59583. * @param viewportHeight viewport height
  59584. * @param world world matrix
  59585. * @param view view matrix
  59586. * @param projection projection matrix
  59587. * @returns this ray updated
  59588. */
  59589. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  59590. BABYLON.Vector3.UnprojectRayToRef(x, y, viewportWidth, viewportHeight, world, view, projection, this);
  59591. return this;
  59592. };
  59593. // Statics
  59594. /**
  59595. * Creates a ray with origin and direction of 0,0,0
  59596. * @returns the new ray
  59597. */
  59598. Ray.Zero = function () {
  59599. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  59600. };
  59601. /**
  59602. * Creates a new ray from screen space and viewport
  59603. * @param x position
  59604. * @param y y position
  59605. * @param viewportWidth viewport width
  59606. * @param viewportHeight viewport height
  59607. * @param world world matrix
  59608. * @param view view matrix
  59609. * @param projection projection matrix
  59610. * @returns new ray
  59611. */
  59612. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  59613. var result = Ray.Zero();
  59614. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  59615. };
  59616. /**
  59617. * 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
  59618. * transformed to the given world matrix.
  59619. * @param origin The origin point
  59620. * @param end The end point
  59621. * @param world a matrix to transform the ray to. Default is the identity matrix.
  59622. * @returns the new ray
  59623. */
  59624. Ray.CreateNewFromTo = function (origin, end, world) {
  59625. if (world === void 0) { world = BABYLON.Matrix.IdentityReadOnly; }
  59626. var direction = end.subtract(origin);
  59627. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  59628. direction.normalize();
  59629. return Ray.Transform(new Ray(origin, direction, length), world);
  59630. };
  59631. /**
  59632. * Transforms a ray by a matrix
  59633. * @param ray ray to transform
  59634. * @param matrix matrix to apply
  59635. * @returns the resulting new ray
  59636. */
  59637. Ray.Transform = function (ray, matrix) {
  59638. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  59639. Ray.TransformToRef(ray, matrix, result);
  59640. return result;
  59641. };
  59642. /**
  59643. * Transforms a ray by a matrix
  59644. * @param ray ray to transform
  59645. * @param matrix matrix to apply
  59646. * @param result ray to store result in
  59647. */
  59648. Ray.TransformToRef = function (ray, matrix, result) {
  59649. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  59650. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  59651. result.length = ray.length;
  59652. var dir = result.direction;
  59653. var len = dir.length();
  59654. if (!(len === 0 || len === 1)) {
  59655. var num = 1.0 / len;
  59656. dir.x *= num;
  59657. dir.y *= num;
  59658. dir.z *= num;
  59659. result.length *= len;
  59660. }
  59661. };
  59662. Ray.TmpVector3 = BABYLON.Tools.BuildArray(6, BABYLON.Vector3.Zero);
  59663. Ray.smallnum = 0.00000001;
  59664. Ray.rayl = 10e8;
  59665. return Ray;
  59666. }());
  59667. BABYLON.Ray = Ray;
  59668. })(BABYLON || (BABYLON = {}));
  59669. //# sourceMappingURL=babylon.ray.js.map
  59670. var BABYLON;
  59671. (function (BABYLON) {
  59672. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  59673. if (boxMin.x > sphereCenter.x + sphereRadius) {
  59674. return false;
  59675. }
  59676. if (sphereCenter.x - sphereRadius > boxMax.x) {
  59677. return false;
  59678. }
  59679. if (boxMin.y > sphereCenter.y + sphereRadius) {
  59680. return false;
  59681. }
  59682. if (sphereCenter.y - sphereRadius > boxMax.y) {
  59683. return false;
  59684. }
  59685. if (boxMin.z > sphereCenter.z + sphereRadius) {
  59686. return false;
  59687. }
  59688. if (sphereCenter.z - sphereRadius > boxMax.z) {
  59689. return false;
  59690. }
  59691. return true;
  59692. };
  59693. var getLowestRoot = (function () {
  59694. var result = { root: 0, found: false };
  59695. return function (a, b, c, maxR) {
  59696. result.root = 0;
  59697. result.found = false;
  59698. var determinant = b * b - 4.0 * a * c;
  59699. if (determinant < 0) {
  59700. return result;
  59701. }
  59702. var sqrtD = Math.sqrt(determinant);
  59703. var r1 = (-b - sqrtD) / (2.0 * a);
  59704. var r2 = (-b + sqrtD) / (2.0 * a);
  59705. if (r1 > r2) {
  59706. var temp = r2;
  59707. r2 = r1;
  59708. r1 = temp;
  59709. }
  59710. if (r1 > 0 && r1 < maxR) {
  59711. result.root = r1;
  59712. result.found = true;
  59713. return result;
  59714. }
  59715. if (r2 > 0 && r2 < maxR) {
  59716. result.root = r2;
  59717. result.found = true;
  59718. return result;
  59719. }
  59720. return result;
  59721. };
  59722. })();
  59723. /** @hidden */
  59724. var Collider = /** @class */ (function () {
  59725. function Collider() {
  59726. this._collisionPoint = BABYLON.Vector3.Zero();
  59727. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  59728. this._tempVector = BABYLON.Vector3.Zero();
  59729. this._tempVector2 = BABYLON.Vector3.Zero();
  59730. this._tempVector3 = BABYLON.Vector3.Zero();
  59731. this._tempVector4 = BABYLON.Vector3.Zero();
  59732. this._edge = BABYLON.Vector3.Zero();
  59733. this._baseToVertex = BABYLON.Vector3.Zero();
  59734. this._destinationPoint = BABYLON.Vector3.Zero();
  59735. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  59736. this._displacementVector = BABYLON.Vector3.Zero();
  59737. /** @hidden */
  59738. this._radius = BABYLON.Vector3.One();
  59739. /** @hidden */
  59740. this._retry = 0;
  59741. /** @hidden */
  59742. this._basePointWorld = BABYLON.Vector3.Zero();
  59743. this._velocityWorld = BABYLON.Vector3.Zero();
  59744. this._normalizedVelocity = BABYLON.Vector3.Zero();
  59745. this._collisionMask = -1;
  59746. }
  59747. Object.defineProperty(Collider.prototype, "collisionMask", {
  59748. get: function () {
  59749. return this._collisionMask;
  59750. },
  59751. set: function (mask) {
  59752. this._collisionMask = !isNaN(mask) ? mask : -1;
  59753. },
  59754. enumerable: true,
  59755. configurable: true
  59756. });
  59757. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  59758. /**
  59759. * Gets the plane normal used to compute the sliding response (in local space)
  59760. */
  59761. get: function () {
  59762. return this._slidePlaneNormal;
  59763. },
  59764. enumerable: true,
  59765. configurable: true
  59766. });
  59767. // Methods
  59768. /** @hidden */
  59769. Collider.prototype._initialize = function (source, dir, e) {
  59770. this._velocity = dir;
  59771. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  59772. this._basePoint = source;
  59773. source.multiplyToRef(this._radius, this._basePointWorld);
  59774. dir.multiplyToRef(this._radius, this._velocityWorld);
  59775. this._velocityWorldLength = this._velocityWorld.length();
  59776. this._epsilon = e;
  59777. this.collisionFound = false;
  59778. };
  59779. /** @hidden */
  59780. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  59781. pa.subtractToRef(point, this._tempVector);
  59782. pb.subtractToRef(point, this._tempVector2);
  59783. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  59784. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  59785. if (d < 0) {
  59786. return false;
  59787. }
  59788. pc.subtractToRef(point, this._tempVector3);
  59789. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  59790. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  59791. if (d < 0) {
  59792. return false;
  59793. }
  59794. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  59795. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  59796. return d >= 0;
  59797. };
  59798. /** @hidden */
  59799. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  59800. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  59801. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  59802. if (distance > this._velocityWorldLength + max + sphereRadius) {
  59803. return false;
  59804. }
  59805. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max)) {
  59806. return false;
  59807. }
  59808. return true;
  59809. };
  59810. /** @hidden */
  59811. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  59812. var t0;
  59813. var embeddedInPlane = false;
  59814. //defensive programming, actually not needed.
  59815. if (!trianglePlaneArray) {
  59816. trianglePlaneArray = [];
  59817. }
  59818. if (!trianglePlaneArray[faceIndex]) {
  59819. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  59820. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  59821. }
  59822. var trianglePlane = trianglePlaneArray[faceIndex];
  59823. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0)) {
  59824. return;
  59825. }
  59826. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  59827. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  59828. if (normalDotVelocity == 0) {
  59829. if (Math.abs(signedDistToTrianglePlane) >= 1.0) {
  59830. return;
  59831. }
  59832. embeddedInPlane = true;
  59833. t0 = 0;
  59834. }
  59835. else {
  59836. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  59837. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  59838. if (t0 > t1) {
  59839. var temp = t1;
  59840. t1 = t0;
  59841. t0 = temp;
  59842. }
  59843. if (t0 > 1.0 || t1 < 0.0) {
  59844. return;
  59845. }
  59846. if (t0 < 0) {
  59847. t0 = 0;
  59848. }
  59849. if (t0 > 1.0) {
  59850. t0 = 1.0;
  59851. }
  59852. }
  59853. this._collisionPoint.copyFromFloats(0, 0, 0);
  59854. var found = false;
  59855. var t = 1.0;
  59856. if (!embeddedInPlane) {
  59857. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  59858. this._velocity.scaleToRef(t0, this._tempVector);
  59859. this._planeIntersectionPoint.addInPlace(this._tempVector);
  59860. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  59861. found = true;
  59862. t = t0;
  59863. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  59864. }
  59865. }
  59866. if (!found) {
  59867. var velocitySquaredLength = this._velocity.lengthSquared();
  59868. var a = velocitySquaredLength;
  59869. this._basePoint.subtractToRef(p1, this._tempVector);
  59870. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  59871. var c = this._tempVector.lengthSquared() - 1.0;
  59872. var lowestRoot = getLowestRoot(a, b, c, t);
  59873. if (lowestRoot.found) {
  59874. t = lowestRoot.root;
  59875. found = true;
  59876. this._collisionPoint.copyFrom(p1);
  59877. }
  59878. this._basePoint.subtractToRef(p2, this._tempVector);
  59879. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  59880. c = this._tempVector.lengthSquared() - 1.0;
  59881. lowestRoot = getLowestRoot(a, b, c, t);
  59882. if (lowestRoot.found) {
  59883. t = lowestRoot.root;
  59884. found = true;
  59885. this._collisionPoint.copyFrom(p2);
  59886. }
  59887. this._basePoint.subtractToRef(p3, this._tempVector);
  59888. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  59889. c = this._tempVector.lengthSquared() - 1.0;
  59890. lowestRoot = getLowestRoot(a, b, c, t);
  59891. if (lowestRoot.found) {
  59892. t = lowestRoot.root;
  59893. found = true;
  59894. this._collisionPoint.copyFrom(p3);
  59895. }
  59896. p2.subtractToRef(p1, this._edge);
  59897. p1.subtractToRef(this._basePoint, this._baseToVertex);
  59898. var edgeSquaredLength = this._edge.lengthSquared();
  59899. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  59900. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  59901. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  59902. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  59903. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  59904. lowestRoot = getLowestRoot(a, b, c, t);
  59905. if (lowestRoot.found) {
  59906. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  59907. if (f >= 0.0 && f <= 1.0) {
  59908. t = lowestRoot.root;
  59909. found = true;
  59910. this._edge.scaleInPlace(f);
  59911. p1.addToRef(this._edge, this._collisionPoint);
  59912. }
  59913. }
  59914. p3.subtractToRef(p2, this._edge);
  59915. p2.subtractToRef(this._basePoint, this._baseToVertex);
  59916. edgeSquaredLength = this._edge.lengthSquared();
  59917. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  59918. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  59919. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  59920. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  59921. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  59922. lowestRoot = getLowestRoot(a, b, c, t);
  59923. if (lowestRoot.found) {
  59924. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  59925. if (f >= 0.0 && f <= 1.0) {
  59926. t = lowestRoot.root;
  59927. found = true;
  59928. this._edge.scaleInPlace(f);
  59929. p2.addToRef(this._edge, this._collisionPoint);
  59930. }
  59931. }
  59932. p1.subtractToRef(p3, this._edge);
  59933. p3.subtractToRef(this._basePoint, this._baseToVertex);
  59934. edgeSquaredLength = this._edge.lengthSquared();
  59935. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  59936. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  59937. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  59938. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  59939. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  59940. lowestRoot = getLowestRoot(a, b, c, t);
  59941. if (lowestRoot.found) {
  59942. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  59943. if (f >= 0.0 && f <= 1.0) {
  59944. t = lowestRoot.root;
  59945. found = true;
  59946. this._edge.scaleInPlace(f);
  59947. p3.addToRef(this._edge, this._collisionPoint);
  59948. }
  59949. }
  59950. }
  59951. if (found) {
  59952. var distToCollision = t * this._velocity.length();
  59953. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  59954. if (!this.intersectionPoint) {
  59955. this.intersectionPoint = this._collisionPoint.clone();
  59956. }
  59957. else {
  59958. this.intersectionPoint.copyFrom(this._collisionPoint);
  59959. }
  59960. this._nearestDistance = distToCollision;
  59961. this.collisionFound = true;
  59962. }
  59963. }
  59964. };
  59965. /** @hidden */
  59966. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  59967. for (var i = indexStart; i < indexEnd; i += 3) {
  59968. var p1 = pts[indices[i] - decal];
  59969. var p2 = pts[indices[i + 1] - decal];
  59970. var p3 = pts[indices[i + 2] - decal];
  59971. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  59972. }
  59973. };
  59974. /** @hidden */
  59975. Collider.prototype._getResponse = function (pos, vel) {
  59976. pos.addToRef(vel, this._destinationPoint);
  59977. vel.scaleInPlace((this._nearestDistance / vel.length()));
  59978. this._basePoint.addToRef(vel, pos);
  59979. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  59980. this._slidePlaneNormal.normalize();
  59981. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  59982. pos.addInPlace(this._displacementVector);
  59983. this.intersectionPoint.addInPlace(this._displacementVector);
  59984. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  59985. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  59986. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  59987. };
  59988. return Collider;
  59989. }());
  59990. BABYLON.Collider = Collider;
  59991. })(BABYLON || (BABYLON = {}));
  59992. //# sourceMappingURL=babylon.collider.js.map
  59993. var BABYLON;
  59994. (function (BABYLON) {
  59995. //WebWorker code will be inserted to this variable.
  59996. /** @hidden */
  59997. BABYLON.CollisionWorker = "";
  59998. /** Defines supported task for worker process */
  59999. var WorkerTaskType;
  60000. (function (WorkerTaskType) {
  60001. /** Initialization */
  60002. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  60003. /** Update of geometry */
  60004. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  60005. /** Evaluate collision */
  60006. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  60007. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  60008. /** Defines kind of replies returned by worker */
  60009. var WorkerReplyType;
  60010. (function (WorkerReplyType) {
  60011. /** Success */
  60012. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  60013. /** Unkown error */
  60014. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  60015. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  60016. /** @hidden */
  60017. var CollisionCoordinatorWorker = /** @class */ (function () {
  60018. function CollisionCoordinatorWorker() {
  60019. var _this = this;
  60020. this._scaledPosition = BABYLON.Vector3.Zero();
  60021. this._scaledVelocity = BABYLON.Vector3.Zero();
  60022. this.onMeshUpdated = function (transformNode) {
  60023. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  60024. };
  60025. this.onGeometryUpdated = function (geometry) {
  60026. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  60027. };
  60028. this._afterRender = function () {
  60029. if (!_this._init) {
  60030. return;
  60031. }
  60032. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  60033. return;
  60034. }
  60035. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  60036. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  60037. if (_this._runningUpdated > 4) {
  60038. return;
  60039. }
  60040. ++_this._runningUpdated;
  60041. var payload = {
  60042. updatedMeshes: _this._addUpdateMeshesList,
  60043. updatedGeometries: _this._addUpdateGeometriesList,
  60044. removedGeometries: _this._toRemoveGeometryArray,
  60045. removedMeshes: _this._toRemoveMeshesArray
  60046. };
  60047. var message = {
  60048. payload: payload,
  60049. taskType: WorkerTaskType.UPDATE
  60050. };
  60051. var serializable = [];
  60052. for (var id in payload.updatedGeometries) {
  60053. if (payload.updatedGeometries.hasOwnProperty(id)) {
  60054. //prepare transferables
  60055. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  60056. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  60057. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  60058. }
  60059. }
  60060. _this._worker.postMessage(message, serializable);
  60061. _this._addUpdateMeshesList = {};
  60062. _this._addUpdateGeometriesList = {};
  60063. _this._toRemoveGeometryArray = [];
  60064. _this._toRemoveMeshesArray = [];
  60065. };
  60066. this._onMessageFromWorker = function (e) {
  60067. var returnData = e.data;
  60068. if (returnData.error != WorkerReplyType.SUCCESS) {
  60069. //TODO what errors can be returned from the worker?
  60070. BABYLON.Tools.Warn("error returned from worker!");
  60071. return;
  60072. }
  60073. switch (returnData.taskType) {
  60074. case WorkerTaskType.INIT:
  60075. _this._init = true;
  60076. //Update the worked with ALL of the scene's current state
  60077. _this._scene.meshes.forEach(function (mesh) {
  60078. _this.onMeshAdded(mesh);
  60079. });
  60080. _this._scene.getGeometries().forEach(function (geometry) {
  60081. _this.onGeometryAdded(geometry);
  60082. });
  60083. break;
  60084. case WorkerTaskType.UPDATE:
  60085. _this._runningUpdated--;
  60086. break;
  60087. case WorkerTaskType.COLLIDE:
  60088. var returnPayload = returnData.payload;
  60089. if (!_this._collisionsCallbackArray[returnPayload.collisionId]) {
  60090. return;
  60091. }
  60092. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  60093. if (callback) {
  60094. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  60095. if (mesh) {
  60096. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  60097. }
  60098. }
  60099. //cleanup
  60100. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  60101. break;
  60102. }
  60103. };
  60104. this._collisionsCallbackArray = [];
  60105. this._init = false;
  60106. this._runningUpdated = 0;
  60107. this._addUpdateMeshesList = {};
  60108. this._addUpdateGeometriesList = {};
  60109. this._toRemoveGeometryArray = [];
  60110. this._toRemoveMeshesArray = [];
  60111. }
  60112. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  60113. if (!this._init) {
  60114. return;
  60115. }
  60116. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000]) {
  60117. return;
  60118. }
  60119. position.divideToRef(collider._radius, this._scaledPosition);
  60120. displacement.divideToRef(collider._radius, this._scaledVelocity);
  60121. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  60122. var payload = {
  60123. collider: {
  60124. position: this._scaledPosition.asArray(),
  60125. velocity: this._scaledVelocity.asArray(),
  60126. radius: collider._radius.asArray()
  60127. },
  60128. collisionId: collisionIndex,
  60129. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  60130. maximumRetry: maximumRetry
  60131. };
  60132. var message = {
  60133. payload: payload,
  60134. taskType: WorkerTaskType.COLLIDE
  60135. };
  60136. this._worker.postMessage(message);
  60137. };
  60138. CollisionCoordinatorWorker.prototype.init = function (scene) {
  60139. this._scene = scene;
  60140. this._scene.registerAfterRender(this._afterRender);
  60141. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  60142. this._worker = new Worker(workerUrl);
  60143. this._worker.onmessage = this._onMessageFromWorker;
  60144. var message = {
  60145. payload: {},
  60146. taskType: WorkerTaskType.INIT
  60147. };
  60148. this._worker.postMessage(message);
  60149. };
  60150. CollisionCoordinatorWorker.prototype.destroy = function () {
  60151. this._scene.unregisterAfterRender(this._afterRender);
  60152. this._worker.terminate();
  60153. };
  60154. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  60155. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  60156. this.onMeshUpdated(mesh);
  60157. };
  60158. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  60159. this._toRemoveMeshesArray.push(mesh.uniqueId);
  60160. };
  60161. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  60162. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  60163. geometry.onGeometryUpdated = this.onGeometryUpdated;
  60164. this.onGeometryUpdated(geometry);
  60165. };
  60166. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  60167. this._toRemoveGeometryArray.push(geometry.id);
  60168. };
  60169. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  60170. var submeshes = [];
  60171. if (mesh.subMeshes) {
  60172. submeshes = mesh.subMeshes.map(function (sm, idx) {
  60173. var boundingInfo = sm.getBoundingInfo();
  60174. return {
  60175. position: idx,
  60176. verticesStart: sm.verticesStart,
  60177. verticesCount: sm.verticesCount,
  60178. indexStart: sm.indexStart,
  60179. indexCount: sm.indexCount,
  60180. hasMaterial: !!sm.getMaterial(),
  60181. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  60182. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  60183. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  60184. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  60185. };
  60186. });
  60187. }
  60188. var geometryId = null;
  60189. if (mesh instanceof BABYLON.Mesh) {
  60190. var geometry = mesh.geometry;
  60191. geometryId = geometry ? geometry.id : null;
  60192. }
  60193. else if (mesh instanceof BABYLON.InstancedMesh) {
  60194. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  60195. geometryId = geometry ? geometry.id : null;
  60196. }
  60197. var boundingInfo = mesh.getBoundingInfo();
  60198. return {
  60199. uniqueId: mesh.uniqueId,
  60200. id: mesh.id,
  60201. name: mesh.name,
  60202. geometryId: geometryId,
  60203. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  60204. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  60205. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  60206. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  60207. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  60208. subMeshes: submeshes,
  60209. checkCollisions: mesh.checkCollisions
  60210. };
  60211. };
  60212. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  60213. return {
  60214. id: geometry.id,
  60215. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  60216. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  60217. indices: new Uint32Array(geometry.getIndices() || []),
  60218. };
  60219. };
  60220. return CollisionCoordinatorWorker;
  60221. }());
  60222. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  60223. /** @hidden */
  60224. var CollisionCoordinatorLegacy = /** @class */ (function () {
  60225. function CollisionCoordinatorLegacy() {
  60226. this._scaledPosition = BABYLON.Vector3.Zero();
  60227. this._scaledVelocity = BABYLON.Vector3.Zero();
  60228. this._finalPosition = BABYLON.Vector3.Zero();
  60229. }
  60230. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  60231. position.divideToRef(collider._radius, this._scaledPosition);
  60232. displacement.divideToRef(collider._radius, this._scaledVelocity);
  60233. collider.collidedMesh = null;
  60234. collider._retry = 0;
  60235. collider._initialVelocity = this._scaledVelocity;
  60236. collider._initialPosition = this._scaledPosition;
  60237. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  60238. this._finalPosition.multiplyInPlace(collider._radius);
  60239. //run the callback
  60240. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  60241. };
  60242. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  60243. this._scene = scene;
  60244. };
  60245. CollisionCoordinatorLegacy.prototype.destroy = function () {
  60246. //Legacy need no destruction method.
  60247. };
  60248. //No update in legacy mode
  60249. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  60250. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  60251. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  60252. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  60253. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  60254. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  60255. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  60256. if (excludedMesh === void 0) { excludedMesh = null; }
  60257. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  60258. if (collider._retry >= maximumRetry) {
  60259. finalPosition.copyFrom(position);
  60260. return;
  60261. }
  60262. // Check if this is a mesh else camera or -1
  60263. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  60264. collider._initialize(position, velocity, closeDistance);
  60265. // Check all meshes
  60266. for (var index = 0; index < this._scene.meshes.length; index++) {
  60267. var mesh = this._scene.meshes[index];
  60268. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  60269. mesh._checkCollision(collider);
  60270. }
  60271. }
  60272. if (!collider.collisionFound) {
  60273. position.addToRef(velocity, finalPosition);
  60274. return;
  60275. }
  60276. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  60277. collider._getResponse(position, velocity);
  60278. }
  60279. if (velocity.length() <= closeDistance) {
  60280. finalPosition.copyFrom(position);
  60281. return;
  60282. }
  60283. collider._retry++;
  60284. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  60285. };
  60286. return CollisionCoordinatorLegacy;
  60287. }());
  60288. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  60289. })(BABYLON || (BABYLON = {}));
  60290. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  60291. var BABYLON;
  60292. (function (BABYLON) {
  60293. /**
  60294. * A particle represents one of the element emitted by a particle system.
  60295. * This is mainly define by its coordinates, direction, velocity and age.
  60296. */
  60297. var Particle = /** @class */ (function () {
  60298. /**
  60299. * Creates a new instance Particle
  60300. * @param particleSystem the particle system the particle belongs to
  60301. */
  60302. function Particle(
  60303. /**
  60304. * The particle system the particle belongs to.
  60305. */
  60306. particleSystem) {
  60307. this.particleSystem = particleSystem;
  60308. /**
  60309. * The world position of the particle in the scene.
  60310. */
  60311. this.position = BABYLON.Vector3.Zero();
  60312. /**
  60313. * The world direction of the particle in the scene.
  60314. */
  60315. this.direction = BABYLON.Vector3.Zero();
  60316. /**
  60317. * The color of the particle.
  60318. */
  60319. this.color = new BABYLON.Color4(0, 0, 0, 0);
  60320. /**
  60321. * The color change of the particle per step.
  60322. */
  60323. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  60324. /**
  60325. * Defines how long will the life of the particle be.
  60326. */
  60327. this.lifeTime = 1.0;
  60328. /**
  60329. * The current age of the particle.
  60330. */
  60331. this.age = 0;
  60332. /**
  60333. * The current size of the particle.
  60334. */
  60335. this.size = 0;
  60336. /**
  60337. * The current scale of the particle.
  60338. */
  60339. this.scale = new BABYLON.Vector2(1, 1);
  60340. /**
  60341. * The current angle of the particle.
  60342. */
  60343. this.angle = 0;
  60344. /**
  60345. * Defines how fast is the angle changing.
  60346. */
  60347. this.angularSpeed = 0;
  60348. /**
  60349. * Defines the cell index used by the particle to be rendered from a sprite.
  60350. */
  60351. this.cellIndex = 0;
  60352. /** @hidden */
  60353. this._attachedSubEmitters = null;
  60354. /** @hidden */
  60355. this._currentColor1 = new BABYLON.Color4(0, 0, 0, 0);
  60356. /** @hidden */
  60357. this._currentColor2 = new BABYLON.Color4(0, 0, 0, 0);
  60358. /** @hidden */
  60359. this._currentSize1 = 0;
  60360. /** @hidden */
  60361. this._currentSize2 = 0;
  60362. /** @hidden */
  60363. this._currentAngularSpeed1 = 0;
  60364. /** @hidden */
  60365. this._currentAngularSpeed2 = 0;
  60366. /** @hidden */
  60367. this._currentVelocity1 = 0;
  60368. /** @hidden */
  60369. this._currentVelocity2 = 0;
  60370. /** @hidden */
  60371. this._currentLimitVelocity1 = 0;
  60372. /** @hidden */
  60373. this._currentLimitVelocity2 = 0;
  60374. /** @hidden */
  60375. this._currentDrag1 = 0;
  60376. /** @hidden */
  60377. this._currentDrag2 = 0;
  60378. this.id = Particle._Count++;
  60379. if (!this.particleSystem.isAnimationSheetEnabled) {
  60380. return;
  60381. }
  60382. this.updateCellInfoFromSystem();
  60383. }
  60384. Particle.prototype.updateCellInfoFromSystem = function () {
  60385. this.cellIndex = this.particleSystem.startSpriteCellID;
  60386. };
  60387. /**
  60388. * Defines how the sprite cell index is updated for the particle
  60389. */
  60390. Particle.prototype.updateCellIndex = function () {
  60391. var offsetAge = this.age;
  60392. var changeSpeed = this.particleSystem.spriteCellChangeSpeed;
  60393. if (this.particleSystem.spriteRandomStartCell) {
  60394. if (this._randomCellOffset === undefined) {
  60395. this._randomCellOffset = Math.random() * this.lifeTime;
  60396. }
  60397. if (changeSpeed === 0) { // Special case when speed = 0 meaning we want to stay on initial cell
  60398. changeSpeed = 1;
  60399. offsetAge = this._randomCellOffset;
  60400. }
  60401. else {
  60402. offsetAge += this._randomCellOffset;
  60403. }
  60404. }
  60405. var dist = (this._initialEndSpriteCellID - this._initialStartSpriteCellID);
  60406. var ratio = BABYLON.Scalar.Clamp(((offsetAge * changeSpeed) % this.lifeTime) / this.lifeTime);
  60407. this.cellIndex = this._initialStartSpriteCellID + (ratio * dist) | 0;
  60408. };
  60409. /** @hidden */
  60410. Particle.prototype._inheritParticleInfoToSubEmitter = function (subEmitter) {
  60411. if (subEmitter.particleSystem.emitter.position) {
  60412. var emitterMesh = subEmitter.particleSystem.emitter;
  60413. emitterMesh.position.copyFrom(this.position);
  60414. if (subEmitter.inheritDirection) {
  60415. emitterMesh.position.subtractToRef(this.direction, BABYLON.Tmp.Vector3[0]);
  60416. // Look at using Y as forward
  60417. emitterMesh.lookAt(BABYLON.Tmp.Vector3[0], 0, Math.PI / 2);
  60418. }
  60419. }
  60420. else {
  60421. var emitterPosition = subEmitter.particleSystem.emitter;
  60422. emitterPosition.copyFrom(this.position);
  60423. }
  60424. // Set inheritedVelocityOffset to be used when new particles are created
  60425. this.direction.scaleToRef(subEmitter.inheritedVelocityAmount / 2, BABYLON.Tmp.Vector3[0]);
  60426. subEmitter.particleSystem._inheritedVelocityOffset.copyFrom(BABYLON.Tmp.Vector3[0]);
  60427. };
  60428. /** @hidden */
  60429. Particle.prototype._inheritParticleInfoToSubEmitters = function () {
  60430. var _this = this;
  60431. if (this._attachedSubEmitters && this._attachedSubEmitters.length > 0) {
  60432. this._attachedSubEmitters.forEach(function (subEmitter) {
  60433. _this._inheritParticleInfoToSubEmitter(subEmitter);
  60434. });
  60435. }
  60436. };
  60437. /** @hidden */
  60438. Particle.prototype._reset = function () {
  60439. this.age = 0;
  60440. this._currentColorGradient = null;
  60441. this._currentSizeGradient = null;
  60442. this._currentAngularSpeedGradient = null;
  60443. this._currentVelocityGradient = null;
  60444. this._currentLimitVelocityGradient = null;
  60445. this._currentDragGradient = null;
  60446. this.cellIndex = this.particleSystem.startSpriteCellID;
  60447. this._randomCellOffset = undefined;
  60448. };
  60449. /**
  60450. * Copy the properties of particle to another one.
  60451. * @param other the particle to copy the information to.
  60452. */
  60453. Particle.prototype.copyTo = function (other) {
  60454. other.position.copyFrom(this.position);
  60455. if (this._initialDirection) {
  60456. if (other._initialDirection) {
  60457. other._initialDirection.copyFrom(this._initialDirection);
  60458. }
  60459. else {
  60460. other._initialDirection = this._initialDirection.clone();
  60461. }
  60462. }
  60463. else {
  60464. other._initialDirection = null;
  60465. }
  60466. other.direction.copyFrom(this.direction);
  60467. other.color.copyFrom(this.color);
  60468. other.colorStep.copyFrom(this.colorStep);
  60469. other.lifeTime = this.lifeTime;
  60470. other.age = this.age;
  60471. other._randomCellOffset = this._randomCellOffset;
  60472. other.size = this.size;
  60473. other.scale.copyFrom(this.scale);
  60474. other.angle = this.angle;
  60475. other.angularSpeed = this.angularSpeed;
  60476. other.particleSystem = this.particleSystem;
  60477. other.cellIndex = this.cellIndex;
  60478. other.id = this.id;
  60479. other._attachedSubEmitters = this._attachedSubEmitters;
  60480. if (this._currentColorGradient) {
  60481. other._currentColorGradient = this._currentColorGradient;
  60482. other._currentColor1.copyFrom(this._currentColor1);
  60483. other._currentColor2.copyFrom(this._currentColor2);
  60484. }
  60485. if (this._currentSizeGradient) {
  60486. other._currentSizeGradient = this._currentSizeGradient;
  60487. other._currentSize1 = this._currentSize1;
  60488. other._currentSize2 = this._currentSize2;
  60489. }
  60490. if (this._currentAngularSpeedGradient) {
  60491. other._currentAngularSpeedGradient = this._currentAngularSpeedGradient;
  60492. other._currentAngularSpeed1 = this._currentAngularSpeed1;
  60493. other._currentAngularSpeed2 = this._currentAngularSpeed2;
  60494. }
  60495. if (this._currentVelocityGradient) {
  60496. other._currentVelocityGradient = this._currentVelocityGradient;
  60497. other._currentVelocity1 = this._currentVelocity1;
  60498. other._currentVelocity2 = this._currentVelocity2;
  60499. }
  60500. if (this._currentLimitVelocityGradient) {
  60501. other._currentLimitVelocityGradient = this._currentLimitVelocityGradient;
  60502. other._currentLimitVelocity1 = this._currentLimitVelocity1;
  60503. other._currentLimitVelocity2 = this._currentLimitVelocity2;
  60504. }
  60505. if (this._currentDragGradient) {
  60506. other._currentDragGradient = this._currentDragGradient;
  60507. other._currentDrag1 = this._currentDrag1;
  60508. other._currentDrag2 = this._currentDrag2;
  60509. }
  60510. if (this.particleSystem.isAnimationSheetEnabled) {
  60511. other._initialStartSpriteCellID = this._initialStartSpriteCellID;
  60512. other._initialEndSpriteCellID = this._initialEndSpriteCellID;
  60513. }
  60514. if (this.particleSystem.useRampGradients) {
  60515. other.remapData.copyFrom(this.remapData);
  60516. }
  60517. if (this._randomNoiseCoordinates1) {
  60518. if (other._randomNoiseCoordinates1) {
  60519. other._randomNoiseCoordinates1.copyFrom(this._randomNoiseCoordinates1);
  60520. other._randomNoiseCoordinates2.copyFrom(this._randomNoiseCoordinates2);
  60521. }
  60522. else {
  60523. other._randomNoiseCoordinates1 = this._randomNoiseCoordinates1.clone();
  60524. other._randomNoiseCoordinates2 = this._randomNoiseCoordinates2.clone();
  60525. }
  60526. }
  60527. };
  60528. Particle._Count = 0;
  60529. return Particle;
  60530. }());
  60531. BABYLON.Particle = Particle;
  60532. })(BABYLON || (BABYLON = {}));
  60533. //# sourceMappingURL=babylon.particle.js.map
  60534. var BABYLON;
  60535. (function (BABYLON) {
  60536. /**
  60537. * This represents the base class for particle system in Babylon.
  60538. * 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.
  60539. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  60540. * @example https://doc.babylonjs.com/babylon101/particles
  60541. */
  60542. var BaseParticleSystem = /** @class */ (function () {
  60543. /**
  60544. * Instantiates a particle system.
  60545. * 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.
  60546. * @param name The name of the particle system
  60547. */
  60548. function BaseParticleSystem(name) {
  60549. /**
  60550. * List of animations used by the particle system.
  60551. */
  60552. this.animations = [];
  60553. /**
  60554. * The rendering group used by the Particle system to chose when to render.
  60555. */
  60556. this.renderingGroupId = 0;
  60557. /**
  60558. * The emitter represents the Mesh or position we are attaching the particle system to.
  60559. */
  60560. this.emitter = null;
  60561. /**
  60562. * The maximum number of particles to emit per frame
  60563. */
  60564. this.emitRate = 10;
  60565. /**
  60566. * If you want to launch only a few particles at once, that can be done, as well.
  60567. */
  60568. this.manualEmitCount = -1;
  60569. /**
  60570. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  60571. */
  60572. this.updateSpeed = 0.01;
  60573. /**
  60574. * The amount of time the particle system is running (depends of the overall update speed).
  60575. */
  60576. this.targetStopDuration = 0;
  60577. /**
  60578. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  60579. */
  60580. this.disposeOnStop = false;
  60581. /**
  60582. * Minimum power of emitting particles.
  60583. */
  60584. this.minEmitPower = 1;
  60585. /**
  60586. * Maximum power of emitting particles.
  60587. */
  60588. this.maxEmitPower = 1;
  60589. /**
  60590. * Minimum life time of emitting particles.
  60591. */
  60592. this.minLifeTime = 1;
  60593. /**
  60594. * Maximum life time of emitting particles.
  60595. */
  60596. this.maxLifeTime = 1;
  60597. /**
  60598. * Minimum Size of emitting particles.
  60599. */
  60600. this.minSize = 1;
  60601. /**
  60602. * Maximum Size of emitting particles.
  60603. */
  60604. this.maxSize = 1;
  60605. /**
  60606. * Minimum scale of emitting particles on X axis.
  60607. */
  60608. this.minScaleX = 1;
  60609. /**
  60610. * Maximum scale of emitting particles on X axis.
  60611. */
  60612. this.maxScaleX = 1;
  60613. /**
  60614. * Minimum scale of emitting particles on Y axis.
  60615. */
  60616. this.minScaleY = 1;
  60617. /**
  60618. * Maximum scale of emitting particles on Y axis.
  60619. */
  60620. this.maxScaleY = 1;
  60621. /**
  60622. * Gets or sets the minimal initial rotation in radians.
  60623. */
  60624. this.minInitialRotation = 0;
  60625. /**
  60626. * Gets or sets the maximal initial rotation in radians.
  60627. */
  60628. this.maxInitialRotation = 0;
  60629. /**
  60630. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  60631. */
  60632. this.minAngularSpeed = 0;
  60633. /**
  60634. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  60635. */
  60636. this.maxAngularSpeed = 0;
  60637. /**
  60638. * The layer mask we are rendering the particles through.
  60639. */
  60640. this.layerMask = 0x0FFFFFFF;
  60641. /**
  60642. * This can help using your own shader to render the particle system.
  60643. * The according effect will be created
  60644. */
  60645. this.customShader = null;
  60646. /**
  60647. * By default particle system starts as soon as they are created. This prevents the
  60648. * automatic start to happen and let you decide when to start emitting particles.
  60649. */
  60650. this.preventAutoStart = false;
  60651. /** Gets or sets the strength to apply to the noise value (default is (10, 10, 10)) */
  60652. this.noiseStrength = new BABYLON.Vector3(10, 10, 10);
  60653. /**
  60654. * Callback triggered when the particle animation is ending.
  60655. */
  60656. this.onAnimationEnd = null;
  60657. /**
  60658. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  60659. */
  60660. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  60661. /**
  60662. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  60663. * to override the particles.
  60664. */
  60665. this.forceDepthWrite = false;
  60666. /** 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 */
  60667. this.preWarmCycles = 0;
  60668. /** Gets or sets a value indicating the time step multiplier to use in pre-warm mode (default is 1) */
  60669. this.preWarmStepOffset = 1;
  60670. /**
  60671. * 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)
  60672. */
  60673. this.spriteCellChangeSpeed = 1;
  60674. /**
  60675. * If using a spritesheet (isAnimationSheetEnabled) defines the first sprite cell to display
  60676. */
  60677. this.startSpriteCellID = 0;
  60678. /**
  60679. * If using a spritesheet (isAnimationSheetEnabled) defines the last sprite cell to display
  60680. */
  60681. this.endSpriteCellID = 0;
  60682. /**
  60683. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use
  60684. */
  60685. this.spriteCellWidth = 0;
  60686. /**
  60687. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use
  60688. */
  60689. this.spriteCellHeight = 0;
  60690. /**
  60691. * This allows the system to random pick the start cell ID between startSpriteCellID and endSpriteCellID
  60692. */
  60693. this.spriteRandomStartCell = false;
  60694. /** Gets or sets a Vector2 used to move the pivot (by default (0,0)) */
  60695. this.translationPivot = new BABYLON.Vector2(0, 0);
  60696. /**
  60697. * Gets or sets a boolean indicating that hosted animations (in the system.animations array) must be started when system.start() is called
  60698. */
  60699. this.beginAnimationOnStart = false;
  60700. /**
  60701. * Gets or sets the frame to start the animation from when beginAnimationOnStart is true
  60702. */
  60703. this.beginAnimationFrom = 0;
  60704. /**
  60705. * Gets or sets the frame to end the animation on when beginAnimationOnStart is true
  60706. */
  60707. this.beginAnimationTo = 60;
  60708. /**
  60709. * Gets or sets a boolean indicating if animations must loop when beginAnimationOnStart is true
  60710. */
  60711. this.beginAnimationLoop = false;
  60712. /**
  60713. * You can use gravity if you want to give an orientation to your particles.
  60714. */
  60715. this.gravity = BABYLON.Vector3.Zero();
  60716. this._colorGradients = null;
  60717. this._sizeGradients = null;
  60718. this._lifeTimeGradients = null;
  60719. this._angularSpeedGradients = null;
  60720. this._velocityGradients = null;
  60721. this._limitVelocityGradients = null;
  60722. this._dragGradients = null;
  60723. this._emitRateGradients = null;
  60724. this._startSizeGradients = null;
  60725. this._rampGradients = null;
  60726. this._colorRemapGradients = null;
  60727. this._alphaRemapGradients = null;
  60728. /**
  60729. * Defines the delay in milliseconds before starting the system (0 by default)
  60730. */
  60731. this.startDelay = 0;
  60732. /** Gets or sets a value indicating the damping to apply if the limit velocity factor is reached */
  60733. this.limitVelocityDamping = 0.4;
  60734. /**
  60735. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  60736. */
  60737. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  60738. /**
  60739. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  60740. */
  60741. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  60742. /**
  60743. * Color the particle will have at the end of its lifetime
  60744. */
  60745. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  60746. /**
  60747. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel
  60748. */
  60749. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  60750. /** @hidden */
  60751. this._isSubEmitter = false;
  60752. /**
  60753. * Gets or sets the billboard mode to use when isBillboardBased = true.
  60754. * Value can be: ParticleSystem.BILLBOARDMODE_ALL, ParticleSystem.BILLBOARDMODE_Y, ParticleSystem.BILLBOARDMODE_STRETCHED
  60755. */
  60756. this.billboardMode = BABYLON.ParticleSystem.BILLBOARDMODE_ALL;
  60757. this._isBillboardBased = true;
  60758. /**
  60759. * Local cache of defines for image processing.
  60760. */
  60761. this._imageProcessingConfigurationDefines = new BABYLON.ImageProcessingConfigurationDefines();
  60762. this.id = name;
  60763. this.name = name;
  60764. }
  60765. Object.defineProperty(BaseParticleSystem.prototype, "noiseTexture", {
  60766. /**
  60767. * Gets or sets a texture used to add random noise to particle positions
  60768. */
  60769. get: function () {
  60770. return this._noiseTexture;
  60771. },
  60772. set: function (value) {
  60773. if (this._noiseTexture === value) {
  60774. return;
  60775. }
  60776. this._noiseTexture = value;
  60777. this._reset();
  60778. },
  60779. enumerable: true,
  60780. configurable: true
  60781. });
  60782. Object.defineProperty(BaseParticleSystem.prototype, "isAnimationSheetEnabled", {
  60783. /**
  60784. * Gets or sets whether an animation sprite sheet is enabled or not on the particle system
  60785. */
  60786. get: function () {
  60787. return this._isAnimationSheetEnabled;
  60788. },
  60789. set: function (value) {
  60790. if (this._isAnimationSheetEnabled == value) {
  60791. return;
  60792. }
  60793. this._isAnimationSheetEnabled = value;
  60794. this._reset();
  60795. },
  60796. enumerable: true,
  60797. configurable: true
  60798. });
  60799. /**
  60800. * Get hosting scene
  60801. * @returns the scene
  60802. */
  60803. BaseParticleSystem.prototype.getScene = function () {
  60804. return this._scene;
  60805. };
  60806. BaseParticleSystem.prototype._hasTargetStopDurationDependantGradient = function () {
  60807. return (this._startSizeGradients && this._startSizeGradients.length > 0)
  60808. || (this._emitRateGradients && this._emitRateGradients.length > 0)
  60809. || (this._lifeTimeGradients && this._lifeTimeGradients.length > 0);
  60810. };
  60811. /**
  60812. * Gets the current list of drag gradients.
  60813. * You must use addDragGradient and removeDragGradient to udpate this list
  60814. * @returns the list of drag gradients
  60815. */
  60816. BaseParticleSystem.prototype.getDragGradients = function () {
  60817. return this._dragGradients;
  60818. };
  60819. /**
  60820. * Gets the current list of limit velocity gradients.
  60821. * You must use addLimitVelocityGradient and removeLimitVelocityGradient to udpate this list
  60822. * @returns the list of limit velocity gradients
  60823. */
  60824. BaseParticleSystem.prototype.getLimitVelocityGradients = function () {
  60825. return this._limitVelocityGradients;
  60826. };
  60827. /**
  60828. * Gets the current list of color gradients.
  60829. * You must use addColorGradient and removeColorGradient to udpate this list
  60830. * @returns the list of color gradients
  60831. */
  60832. BaseParticleSystem.prototype.getColorGradients = function () {
  60833. return this._colorGradients;
  60834. };
  60835. /**
  60836. * Gets the current list of size gradients.
  60837. * You must use addSizeGradient and removeSizeGradient to udpate this list
  60838. * @returns the list of size gradients
  60839. */
  60840. BaseParticleSystem.prototype.getSizeGradients = function () {
  60841. return this._sizeGradients;
  60842. };
  60843. /**
  60844. * Gets the current list of color remap gradients.
  60845. * You must use addColorRemapGradient and removeColorRemapGradient to udpate this list
  60846. * @returns the list of color remap gradients
  60847. */
  60848. BaseParticleSystem.prototype.getColorRemapGradients = function () {
  60849. return this._colorRemapGradients;
  60850. };
  60851. /**
  60852. * Gets the current list of alpha remap gradients.
  60853. * You must use addAlphaRemapGradient and removeAlphaRemapGradient to udpate this list
  60854. * @returns the list of alpha remap gradients
  60855. */
  60856. BaseParticleSystem.prototype.getAlphaRemapGradients = function () {
  60857. return this._alphaRemapGradients;
  60858. };
  60859. /**
  60860. * Gets the current list of life time gradients.
  60861. * You must use addLifeTimeGradient and removeLifeTimeGradient to udpate this list
  60862. * @returns the list of life time gradients
  60863. */
  60864. BaseParticleSystem.prototype.getLifeTimeGradients = function () {
  60865. return this._lifeTimeGradients;
  60866. };
  60867. /**
  60868. * Gets the current list of angular speed gradients.
  60869. * You must use addAngularSpeedGradient and removeAngularSpeedGradient to udpate this list
  60870. * @returns the list of angular speed gradients
  60871. */
  60872. BaseParticleSystem.prototype.getAngularSpeedGradients = function () {
  60873. return this._angularSpeedGradients;
  60874. };
  60875. /**
  60876. * Gets the current list of velocity gradients.
  60877. * You must use addVelocityGradient and removeVelocityGradient to udpate this list
  60878. * @returns the list of velocity gradients
  60879. */
  60880. BaseParticleSystem.prototype.getVelocityGradients = function () {
  60881. return this._velocityGradients;
  60882. };
  60883. /**
  60884. * Gets the current list of start size gradients.
  60885. * You must use addStartSizeGradient and removeStartSizeGradient to udpate this list
  60886. * @returns the list of start size gradients
  60887. */
  60888. BaseParticleSystem.prototype.getStartSizeGradients = function () {
  60889. return this._startSizeGradients;
  60890. };
  60891. /**
  60892. * Gets the current list of emit rate gradients.
  60893. * You must use addEmitRateGradient and removeEmitRateGradient to udpate this list
  60894. * @returns the list of emit rate gradients
  60895. */
  60896. BaseParticleSystem.prototype.getEmitRateGradients = function () {
  60897. return this._emitRateGradients;
  60898. };
  60899. Object.defineProperty(BaseParticleSystem.prototype, "direction1", {
  60900. /**
  60901. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  60902. * This only works when particleEmitterTyps is a BoxParticleEmitter
  60903. */
  60904. get: function () {
  60905. if (this.particleEmitterType.direction1) {
  60906. return this.particleEmitterType.direction1;
  60907. }
  60908. return BABYLON.Vector3.Zero();
  60909. },
  60910. set: function (value) {
  60911. if (this.particleEmitterType.direction1) {
  60912. this.particleEmitterType.direction1 = value;
  60913. }
  60914. },
  60915. enumerable: true,
  60916. configurable: true
  60917. });
  60918. Object.defineProperty(BaseParticleSystem.prototype, "direction2", {
  60919. /**
  60920. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  60921. * This only works when particleEmitterTyps is a BoxParticleEmitter
  60922. */
  60923. get: function () {
  60924. if (this.particleEmitterType.direction2) {
  60925. return this.particleEmitterType.direction2;
  60926. }
  60927. return BABYLON.Vector3.Zero();
  60928. },
  60929. set: function (value) {
  60930. if (this.particleEmitterType.direction2) {
  60931. this.particleEmitterType.direction2 = value;
  60932. }
  60933. },
  60934. enumerable: true,
  60935. configurable: true
  60936. });
  60937. Object.defineProperty(BaseParticleSystem.prototype, "minEmitBox", {
  60938. /**
  60939. * 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.
  60940. * This only works when particleEmitterTyps is a BoxParticleEmitter
  60941. */
  60942. get: function () {
  60943. if (this.particleEmitterType.minEmitBox) {
  60944. return this.particleEmitterType.minEmitBox;
  60945. }
  60946. return BABYLON.Vector3.Zero();
  60947. },
  60948. set: function (value) {
  60949. if (this.particleEmitterType.minEmitBox) {
  60950. this.particleEmitterType.minEmitBox = value;
  60951. }
  60952. },
  60953. enumerable: true,
  60954. configurable: true
  60955. });
  60956. Object.defineProperty(BaseParticleSystem.prototype, "maxEmitBox", {
  60957. /**
  60958. * 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.
  60959. * This only works when particleEmitterTyps is a BoxParticleEmitter
  60960. */
  60961. get: function () {
  60962. if (this.particleEmitterType.maxEmitBox) {
  60963. return this.particleEmitterType.maxEmitBox;
  60964. }
  60965. return BABYLON.Vector3.Zero();
  60966. },
  60967. set: function (value) {
  60968. if (this.particleEmitterType.maxEmitBox) {
  60969. this.particleEmitterType.maxEmitBox = value;
  60970. }
  60971. },
  60972. enumerable: true,
  60973. configurable: true
  60974. });
  60975. Object.defineProperty(BaseParticleSystem.prototype, "isBillboardBased", {
  60976. /**
  60977. * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction
  60978. */
  60979. get: function () {
  60980. return this._isBillboardBased;
  60981. },
  60982. set: function (value) {
  60983. if (this._isBillboardBased === value) {
  60984. return;
  60985. }
  60986. this._isBillboardBased = value;
  60987. this._reset();
  60988. },
  60989. enumerable: true,
  60990. configurable: true
  60991. });
  60992. Object.defineProperty(BaseParticleSystem.prototype, "imageProcessingConfiguration", {
  60993. /**
  60994. * Gets the image processing configuration used either in this material.
  60995. */
  60996. get: function () {
  60997. return this._imageProcessingConfiguration;
  60998. },
  60999. /**
  61000. * Sets the Default image processing configuration used either in the this material.
  61001. *
  61002. * If sets to null, the scene one is in use.
  61003. */
  61004. set: function (value) {
  61005. this._attachImageProcessingConfiguration(value);
  61006. },
  61007. enumerable: true,
  61008. configurable: true
  61009. });
  61010. /**
  61011. * Attaches a new image processing configuration to the Standard Material.
  61012. * @param configuration
  61013. */
  61014. BaseParticleSystem.prototype._attachImageProcessingConfiguration = function (configuration) {
  61015. if (configuration === this._imageProcessingConfiguration) {
  61016. return;
  61017. }
  61018. // Pick the scene configuration if needed.
  61019. if (!configuration) {
  61020. this._imageProcessingConfiguration = this._scene.imageProcessingConfiguration;
  61021. }
  61022. else {
  61023. this._imageProcessingConfiguration = configuration;
  61024. }
  61025. };
  61026. /** @hidden */
  61027. BaseParticleSystem.prototype._reset = function () {
  61028. };
  61029. /** @hidden */
  61030. BaseParticleSystem.prototype._removeGradientAndTexture = function (gradient, gradients, texture) {
  61031. if (!gradients) {
  61032. return this;
  61033. }
  61034. var index = 0;
  61035. for (var _i = 0, gradients_1 = gradients; _i < gradients_1.length; _i++) {
  61036. var valueGradient = gradients_1[_i];
  61037. if (valueGradient.gradient === gradient) {
  61038. gradients.splice(index, 1);
  61039. break;
  61040. }
  61041. index++;
  61042. }
  61043. if (texture) {
  61044. texture.dispose();
  61045. }
  61046. return this;
  61047. };
  61048. /**
  61049. * Creates a Point Emitter for the particle system (emits directly from the emitter position)
  61050. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  61051. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  61052. * @returns the emitter
  61053. */
  61054. BaseParticleSystem.prototype.createPointEmitter = function (direction1, direction2) {
  61055. var particleEmitter = new BABYLON.PointParticleEmitter();
  61056. particleEmitter.direction1 = direction1;
  61057. particleEmitter.direction2 = direction2;
  61058. this.particleEmitterType = particleEmitter;
  61059. return particleEmitter;
  61060. };
  61061. /**
  61062. * Creates a Hemisphere Emitter for the particle system (emits along the hemisphere radius)
  61063. * @param radius The radius of the hemisphere to emit from
  61064. * @param radiusRange The range of the hemisphere to emit from [0-1] 0 Surface Only, 1 Entire Radius
  61065. * @returns the emitter
  61066. */
  61067. BaseParticleSystem.prototype.createHemisphericEmitter = function (radius, radiusRange) {
  61068. if (radius === void 0) { radius = 1; }
  61069. if (radiusRange === void 0) { radiusRange = 1; }
  61070. var particleEmitter = new BABYLON.HemisphericParticleEmitter(radius, radiusRange);
  61071. this.particleEmitterType = particleEmitter;
  61072. return particleEmitter;
  61073. };
  61074. /**
  61075. * Creates a Sphere Emitter for the particle system (emits along the sphere radius)
  61076. * @param radius The radius of the sphere to emit from
  61077. * @param radiusRange The range of the sphere to emit from [0-1] 0 Surface Only, 1 Entire Radius
  61078. * @returns the emitter
  61079. */
  61080. BaseParticleSystem.prototype.createSphereEmitter = function (radius, radiusRange) {
  61081. if (radius === void 0) { radius = 1; }
  61082. if (radiusRange === void 0) { radiusRange = 1; }
  61083. var particleEmitter = new BABYLON.SphereParticleEmitter(radius, radiusRange);
  61084. this.particleEmitterType = particleEmitter;
  61085. return particleEmitter;
  61086. };
  61087. /**
  61088. * Creates a Directed Sphere Emitter for the particle system (emits between direction1 and direction2)
  61089. * @param radius The radius of the sphere to emit from
  61090. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  61091. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  61092. * @returns the emitter
  61093. */
  61094. BaseParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  61095. if (radius === void 0) { radius = 1; }
  61096. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  61097. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  61098. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  61099. this.particleEmitterType = particleEmitter;
  61100. return particleEmitter;
  61101. };
  61102. /**
  61103. * Creates a Cylinder Emitter for the particle system (emits from the cylinder to the particle position)
  61104. * @param radius The radius of the emission cylinder
  61105. * @param height The height of the emission cylinder
  61106. * @param radiusRange The range of emission [0-1] 0 Surface only, 1 Entire Radius
  61107. * @param directionRandomizer How much to randomize the particle direction [0-1]
  61108. * @returns the emitter
  61109. */
  61110. BaseParticleSystem.prototype.createCylinderEmitter = function (radius, height, radiusRange, directionRandomizer) {
  61111. if (radius === void 0) { radius = 1; }
  61112. if (height === void 0) { height = 1; }
  61113. if (radiusRange === void 0) { radiusRange = 1; }
  61114. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  61115. var particleEmitter = new BABYLON.CylinderParticleEmitter(radius, height, radiusRange, directionRandomizer);
  61116. this.particleEmitterType = particleEmitter;
  61117. return particleEmitter;
  61118. };
  61119. /**
  61120. * Creates a Directed Cylinder Emitter for the particle system (emits between direction1 and direction2)
  61121. * @param radius The radius of the cylinder to emit from
  61122. * @param height The height of the emission cylinder
  61123. * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  61124. * @param direction1 Particles are emitted between the direction1 and direction2 from within the cylinder
  61125. * @param direction2 Particles are emitted between the direction1 and direction2 from within the cylinder
  61126. * @returns the emitter
  61127. */
  61128. BaseParticleSystem.prototype.createDirectedCylinderEmitter = function (radius, height, radiusRange, direction1, direction2) {
  61129. if (radius === void 0) { radius = 1; }
  61130. if (height === void 0) { height = 1; }
  61131. if (radiusRange === void 0) { radiusRange = 1; }
  61132. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  61133. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  61134. var particleEmitter = new BABYLON.CylinderDirectedParticleEmitter(radius, height, radiusRange, direction1, direction2);
  61135. this.particleEmitterType = particleEmitter;
  61136. return particleEmitter;
  61137. };
  61138. /**
  61139. * Creates a Cone Emitter for the particle system (emits from the cone to the particle position)
  61140. * @param radius The radius of the cone to emit from
  61141. * @param angle The base angle of the cone
  61142. * @returns the emitter
  61143. */
  61144. BaseParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  61145. if (radius === void 0) { radius = 1; }
  61146. if (angle === void 0) { angle = Math.PI / 4; }
  61147. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  61148. this.particleEmitterType = particleEmitter;
  61149. return particleEmitter;
  61150. };
  61151. /**
  61152. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  61153. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  61154. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  61155. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  61156. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  61157. * @returns the emitter
  61158. */
  61159. BaseParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  61160. var particleEmitter = new BABYLON.BoxParticleEmitter();
  61161. this.particleEmitterType = particleEmitter;
  61162. this.direction1 = direction1;
  61163. this.direction2 = direction2;
  61164. this.minEmitBox = minEmitBox;
  61165. this.maxEmitBox = maxEmitBox;
  61166. return particleEmitter;
  61167. };
  61168. /**
  61169. * Source color is added to the destination color without alpha affecting the result
  61170. */
  61171. BaseParticleSystem.BLENDMODE_ONEONE = 0;
  61172. /**
  61173. * Blend current color and particle color using particle’s alpha
  61174. */
  61175. BaseParticleSystem.BLENDMODE_STANDARD = 1;
  61176. /**
  61177. * Add current color and particle color multiplied by particle’s alpha
  61178. */
  61179. BaseParticleSystem.BLENDMODE_ADD = 2;
  61180. /**
  61181. * Multiply current color with particle color
  61182. */
  61183. BaseParticleSystem.BLENDMODE_MULTIPLY = 3;
  61184. /**
  61185. * Multiply current color with particle color then add current color and particle color multiplied by particle’s alpha
  61186. */
  61187. BaseParticleSystem.BLENDMODE_MULTIPLYADD = 4;
  61188. return BaseParticleSystem;
  61189. }());
  61190. BABYLON.BaseParticleSystem = BaseParticleSystem;
  61191. })(BABYLON || (BABYLON = {}));
  61192. //# sourceMappingURL=babylon.baseParticleSystem.js.map
  61193. var BABYLON;
  61194. (function (BABYLON) {
  61195. /**
  61196. * This represents a particle system in Babylon.
  61197. * 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.
  61198. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  61199. * @example https://doc.babylonjs.com/babylon101/particles
  61200. */
  61201. var ParticleSystem = /** @class */ (function (_super) {
  61202. __extends(ParticleSystem, _super);
  61203. /**
  61204. * Instantiates a particle system.
  61205. * 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.
  61206. * @param name The name of the particle system
  61207. * @param capacity The max number of particles alive at the same time
  61208. * @param scene The scene the particle system belongs to
  61209. * @param customEffect a custom effect used to change the way particles are rendered by default
  61210. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  61211. * @param epsilon Offset used to render the particles
  61212. */
  61213. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  61214. if (customEffect === void 0) { customEffect = null; }
  61215. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  61216. if (epsilon === void 0) { epsilon = 0.01; }
  61217. var _this = _super.call(this, name) || this;
  61218. /**
  61219. * @hidden
  61220. */
  61221. _this._inheritedVelocityOffset = new BABYLON.Vector3();
  61222. /**
  61223. * An event triggered when the system is disposed
  61224. */
  61225. _this.onDisposeObservable = new BABYLON.Observable();
  61226. _this._particles = new Array();
  61227. _this._stockParticles = new Array();
  61228. _this._newPartsExcess = 0;
  61229. _this._vertexBuffers = {};
  61230. _this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  61231. _this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  61232. _this._scaledDirection = BABYLON.Vector3.Zero();
  61233. _this._scaledGravity = BABYLON.Vector3.Zero();
  61234. _this._currentRenderId = -1;
  61235. _this._useInstancing = false;
  61236. _this._started = false;
  61237. _this._stopped = false;
  61238. _this._actualFrame = 0;
  61239. /** @hidden */
  61240. _this._currentEmitRate1 = 0;
  61241. /** @hidden */
  61242. _this._currentEmitRate2 = 0;
  61243. /** @hidden */
  61244. _this._currentStartSize1 = 0;
  61245. /** @hidden */
  61246. _this._currentStartSize2 = 0;
  61247. _this._rawTextureWidth = 256;
  61248. _this._useRampGradients = false;
  61249. /**
  61250. * @hidden
  61251. * If the particle systems emitter should be disposed when the particle system is disposed
  61252. */
  61253. _this._disposeEmitterOnDispose = false;
  61254. // start of sub system methods
  61255. /**
  61256. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  61257. * Its lifetime will start back at 0.
  61258. */
  61259. _this.recycleParticle = function (particle) {
  61260. // move particle from activeParticle list to stock particles
  61261. var lastParticle = _this._particles.pop();
  61262. if (lastParticle !== particle) {
  61263. lastParticle.copyTo(particle);
  61264. }
  61265. _this._stockParticles.push(lastParticle);
  61266. };
  61267. _this._createParticle = function () {
  61268. var particle;
  61269. if (_this._stockParticles.length !== 0) {
  61270. particle = _this._stockParticles.pop();
  61271. particle._reset();
  61272. }
  61273. else {
  61274. particle = new BABYLON.Particle(_this);
  61275. }
  61276. // Attach emitters
  61277. if (_this._subEmitters && _this._subEmitters.length > 0) {
  61278. var subEmitters = _this._subEmitters[Math.floor(Math.random() * _this._subEmitters.length)];
  61279. particle._attachedSubEmitters = [];
  61280. subEmitters.forEach(function (subEmitter) {
  61281. if (subEmitter.type === BABYLON.SubEmitterType.ATTACHED) {
  61282. var newEmitter = subEmitter.clone();
  61283. particle._attachedSubEmitters.push(newEmitter);
  61284. newEmitter.particleSystem.start();
  61285. }
  61286. });
  61287. }
  61288. return particle;
  61289. };
  61290. _this._emitFromParticle = function (particle) {
  61291. if (!_this._subEmitters || _this._subEmitters.length === 0) {
  61292. return;
  61293. }
  61294. var templateIndex = Math.floor(Math.random() * _this._subEmitters.length);
  61295. _this._subEmitters[templateIndex].forEach(function (subEmitter) {
  61296. if (subEmitter.type === BABYLON.SubEmitterType.END) {
  61297. var subSystem = subEmitter.clone();
  61298. particle._inheritParticleInfoToSubEmitter(subSystem);
  61299. subSystem.particleSystem._rootParticleSystem = _this;
  61300. _this.activeSubSystems.push(subSystem.particleSystem);
  61301. subSystem.particleSystem.start();
  61302. }
  61303. });
  61304. };
  61305. _this._capacity = capacity;
  61306. _this._epsilon = epsilon;
  61307. _this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  61308. _this._scene = scene || BABYLON.Engine.LastCreatedScene;
  61309. // Setup the default processing configuration to the scene.
  61310. _this._attachImageProcessingConfiguration(null);
  61311. _this._customEffect = customEffect;
  61312. _this._scene.particleSystems.push(_this);
  61313. _this._useInstancing = _this._scene.getEngine().getCaps().instancedArrays;
  61314. _this._createIndexBuffer();
  61315. _this._createVertexBuffers();
  61316. // Default emitter type
  61317. _this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  61318. // Update
  61319. _this.updateFunction = function (particles) {
  61320. var noiseTextureSize = null;
  61321. var noiseTextureData = null;
  61322. if (_this.noiseTexture) { // We need to get texture data back to CPU
  61323. noiseTextureSize = _this.noiseTexture.getSize();
  61324. noiseTextureData = (_this.noiseTexture.getContent());
  61325. }
  61326. var _loop_1 = function () {
  61327. particle = particles[index];
  61328. var scaledUpdateSpeed = _this._scaledUpdateSpeed;
  61329. var previousAge = particle.age;
  61330. particle.age += scaledUpdateSpeed;
  61331. // Evaluate step to death
  61332. if (particle.age > particle.lifeTime) {
  61333. var diff = particle.age - previousAge;
  61334. var oldDiff = particle.lifeTime - previousAge;
  61335. scaledUpdateSpeed = (oldDiff * scaledUpdateSpeed) / diff;
  61336. particle.age = particle.lifeTime;
  61337. }
  61338. var ratio = particle.age / particle.lifeTime;
  61339. // Color
  61340. if (_this._colorGradients && _this._colorGradients.length > 0) {
  61341. BABYLON.Tools.GetCurrentGradient(ratio, _this._colorGradients, function (currentGradient, nextGradient, scale) {
  61342. if (currentGradient !== particle._currentColorGradient) {
  61343. particle._currentColor1.copyFrom(particle._currentColor2);
  61344. nextGradient.getColorToRef(particle._currentColor2);
  61345. particle._currentColorGradient = currentGradient;
  61346. }
  61347. BABYLON.Color4.LerpToRef(particle._currentColor1, particle._currentColor2, scale, particle.color);
  61348. });
  61349. }
  61350. else {
  61351. particle.colorStep.scaleToRef(scaledUpdateSpeed, _this._scaledColorStep);
  61352. particle.color.addInPlace(_this._scaledColorStep);
  61353. if (particle.color.a < 0) {
  61354. particle.color.a = 0;
  61355. }
  61356. }
  61357. // Angular speed
  61358. if (_this._angularSpeedGradients && _this._angularSpeedGradients.length > 0) {
  61359. BABYLON.Tools.GetCurrentGradient(ratio, _this._angularSpeedGradients, function (currentGradient, nextGradient, scale) {
  61360. if (currentGradient !== particle._currentAngularSpeedGradient) {
  61361. particle._currentAngularSpeed1 = particle._currentAngularSpeed2;
  61362. particle._currentAngularSpeed2 = nextGradient.getFactor();
  61363. particle._currentAngularSpeedGradient = currentGradient;
  61364. }
  61365. particle.angularSpeed = BABYLON.Scalar.Lerp(particle._currentAngularSpeed1, particle._currentAngularSpeed2, scale);
  61366. });
  61367. }
  61368. particle.angle += particle.angularSpeed * scaledUpdateSpeed;
  61369. // Direction
  61370. var directionScale = scaledUpdateSpeed;
  61371. /// Velocity
  61372. if (_this._velocityGradients && _this._velocityGradients.length > 0) {
  61373. BABYLON.Tools.GetCurrentGradient(ratio, _this._velocityGradients, function (currentGradient, nextGradient, scale) {
  61374. if (currentGradient !== particle._currentVelocityGradient) {
  61375. particle._currentVelocity1 = particle._currentVelocity2;
  61376. particle._currentVelocity2 = nextGradient.getFactor();
  61377. particle._currentVelocityGradient = currentGradient;
  61378. }
  61379. directionScale *= BABYLON.Scalar.Lerp(particle._currentVelocity1, particle._currentVelocity2, scale);
  61380. });
  61381. }
  61382. particle.direction.scaleToRef(directionScale, _this._scaledDirection);
  61383. /// Limit velocity
  61384. if (_this._limitVelocityGradients && _this._limitVelocityGradients.length > 0) {
  61385. BABYLON.Tools.GetCurrentGradient(ratio, _this._limitVelocityGradients, function (currentGradient, nextGradient, scale) {
  61386. if (currentGradient !== particle._currentLimitVelocityGradient) {
  61387. particle._currentLimitVelocity1 = particle._currentLimitVelocity2;
  61388. particle._currentLimitVelocity2 = nextGradient.getFactor();
  61389. particle._currentLimitVelocityGradient = currentGradient;
  61390. }
  61391. var limitVelocity = BABYLON.Scalar.Lerp(particle._currentLimitVelocity1, particle._currentLimitVelocity2, scale);
  61392. var currentVelocity = particle.direction.length();
  61393. if (currentVelocity > limitVelocity) {
  61394. particle.direction.scaleInPlace(_this.limitVelocityDamping);
  61395. }
  61396. });
  61397. }
  61398. /// Drag
  61399. if (_this._dragGradients && _this._dragGradients.length > 0) {
  61400. BABYLON.Tools.GetCurrentGradient(ratio, _this._dragGradients, function (currentGradient, nextGradient, scale) {
  61401. if (currentGradient !== particle._currentDragGradient) {
  61402. particle._currentDrag1 = particle._currentDrag2;
  61403. particle._currentDrag2 = nextGradient.getFactor();
  61404. particle._currentDragGradient = currentGradient;
  61405. }
  61406. var drag = BABYLON.Scalar.Lerp(particle._currentDrag1, particle._currentDrag2, scale);
  61407. _this._scaledDirection.scaleInPlace(1.0 - drag);
  61408. });
  61409. }
  61410. particle.position.addInPlace(_this._scaledDirection);
  61411. // Noise
  61412. if (noiseTextureData && noiseTextureSize && particle._randomNoiseCoordinates1) {
  61413. var fetchedColorR = _this._fetchR(particle._randomNoiseCoordinates1.x, particle._randomNoiseCoordinates1.y, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  61414. var fetchedColorG = _this._fetchR(particle._randomNoiseCoordinates1.z, particle._randomNoiseCoordinates2.x, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  61415. var fetchedColorB = _this._fetchR(particle._randomNoiseCoordinates2.y, particle._randomNoiseCoordinates2.z, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  61416. var force = BABYLON.Tmp.Vector3[0];
  61417. var scaledForce = BABYLON.Tmp.Vector3[1];
  61418. force.copyFromFloats((2 * fetchedColorR - 1) * _this.noiseStrength.x, (2 * fetchedColorG - 1) * _this.noiseStrength.y, (2 * fetchedColorB - 1) * _this.noiseStrength.z);
  61419. force.scaleToRef(scaledUpdateSpeed, scaledForce);
  61420. particle.direction.addInPlace(scaledForce);
  61421. }
  61422. // Gravity
  61423. _this.gravity.scaleToRef(scaledUpdateSpeed, _this._scaledGravity);
  61424. particle.direction.addInPlace(_this._scaledGravity);
  61425. // Size
  61426. if (_this._sizeGradients && _this._sizeGradients.length > 0) {
  61427. BABYLON.Tools.GetCurrentGradient(ratio, _this._sizeGradients, function (currentGradient, nextGradient, scale) {
  61428. if (currentGradient !== particle._currentSizeGradient) {
  61429. particle._currentSize1 = particle._currentSize2;
  61430. particle._currentSize2 = nextGradient.getFactor();
  61431. particle._currentSizeGradient = currentGradient;
  61432. }
  61433. particle.size = BABYLON.Scalar.Lerp(particle._currentSize1, particle._currentSize2, scale);
  61434. });
  61435. }
  61436. // Remap data
  61437. if (_this._useRampGradients) {
  61438. if (_this._colorRemapGradients && _this._colorRemapGradients.length > 0) {
  61439. BABYLON.Tools.GetCurrentGradient(ratio, _this._colorRemapGradients, function (currentGradient, nextGradient, scale) {
  61440. var min = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  61441. var max = BABYLON.Scalar.Lerp(currentGradient.factor2, nextGradient.factor2, scale);
  61442. particle.remapData.x = min;
  61443. particle.remapData.y = max - min;
  61444. });
  61445. }
  61446. if (_this._alphaRemapGradients && _this._alphaRemapGradients.length > 0) {
  61447. BABYLON.Tools.GetCurrentGradient(ratio, _this._alphaRemapGradients, function (currentGradient, nextGradient, scale) {
  61448. var min = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  61449. var max = BABYLON.Scalar.Lerp(currentGradient.factor2, nextGradient.factor2, scale);
  61450. particle.remapData.z = min;
  61451. particle.remapData.w = max - min;
  61452. });
  61453. }
  61454. }
  61455. if (_this._isAnimationSheetEnabled) {
  61456. particle.updateCellIndex();
  61457. }
  61458. // Update the position of the attached sub-emitters to match their attached particle
  61459. particle._inheritParticleInfoToSubEmitters();
  61460. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  61461. _this._emitFromParticle(particle);
  61462. if (particle._attachedSubEmitters) {
  61463. particle._attachedSubEmitters.forEach(function (subEmitter) {
  61464. subEmitter.particleSystem.disposeOnStop = true;
  61465. subEmitter.particleSystem.stop();
  61466. });
  61467. particle._attachedSubEmitters = null;
  61468. }
  61469. _this.recycleParticle(particle);
  61470. index--;
  61471. return "continue";
  61472. }
  61473. };
  61474. var particle;
  61475. for (var index = 0; index < particles.length; index++) {
  61476. _loop_1();
  61477. }
  61478. };
  61479. return _this;
  61480. }
  61481. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  61482. /**
  61483. * Sets a callback that will be triggered when the system is disposed
  61484. */
  61485. set: function (callback) {
  61486. if (this._onDisposeObserver) {
  61487. this.onDisposeObservable.remove(this._onDisposeObserver);
  61488. }
  61489. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  61490. },
  61491. enumerable: true,
  61492. configurable: true
  61493. });
  61494. Object.defineProperty(ParticleSystem.prototype, "useRampGradients", {
  61495. /** Gets or sets a boolean indicating that ramp gradients must be used
  61496. * @see http://doc.babylonjs.com/babylon101/particles#ramp-gradients
  61497. */
  61498. get: function () {
  61499. return this._useRampGradients;
  61500. },
  61501. set: function (value) {
  61502. if (this._useRampGradients === value) {
  61503. return;
  61504. }
  61505. this._useRampGradients = value;
  61506. this._resetEffect();
  61507. },
  61508. enumerable: true,
  61509. configurable: true
  61510. });
  61511. Object.defineProperty(ParticleSystem.prototype, "particles", {
  61512. //end of Sub-emitter
  61513. /**
  61514. * Gets the current list of active particles
  61515. */
  61516. get: function () {
  61517. return this._particles;
  61518. },
  61519. enumerable: true,
  61520. configurable: true
  61521. });
  61522. /**
  61523. * Returns the string "ParticleSystem"
  61524. * @returns a string containing the class name
  61525. */
  61526. ParticleSystem.prototype.getClassName = function () {
  61527. return "ParticleSystem";
  61528. };
  61529. ParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor, factor2) {
  61530. var newGradient = new BABYLON.FactorGradient();
  61531. newGradient.gradient = gradient;
  61532. newGradient.factor1 = factor;
  61533. newGradient.factor2 = factor2;
  61534. factorGradients.push(newGradient);
  61535. factorGradients.sort(function (a, b) {
  61536. if (a.gradient < b.gradient) {
  61537. return -1;
  61538. }
  61539. else if (a.gradient > b.gradient) {
  61540. return 1;
  61541. }
  61542. return 0;
  61543. });
  61544. };
  61545. ParticleSystem.prototype._removeFactorGradient = function (factorGradients, gradient) {
  61546. if (!factorGradients) {
  61547. return;
  61548. }
  61549. var index = 0;
  61550. for (var _i = 0, factorGradients_1 = factorGradients; _i < factorGradients_1.length; _i++) {
  61551. var factorGradient = factorGradients_1[_i];
  61552. if (factorGradient.gradient === gradient) {
  61553. factorGradients.splice(index, 1);
  61554. break;
  61555. }
  61556. index++;
  61557. }
  61558. };
  61559. /**
  61560. * Adds a new life time gradient
  61561. * @param gradient defines the gradient to use (between 0 and 1)
  61562. * @param factor defines the life time factor to affect to the specified gradient
  61563. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  61564. * @returns the current particle system
  61565. */
  61566. ParticleSystem.prototype.addLifeTimeGradient = function (gradient, factor, factor2) {
  61567. if (!this._lifeTimeGradients) {
  61568. this._lifeTimeGradients = [];
  61569. }
  61570. this._addFactorGradient(this._lifeTimeGradients, gradient, factor, factor2);
  61571. return this;
  61572. };
  61573. /**
  61574. * Remove a specific life time gradient
  61575. * @param gradient defines the gradient to remove
  61576. * @returns the current particle system
  61577. */
  61578. ParticleSystem.prototype.removeLifeTimeGradient = function (gradient) {
  61579. this._removeFactorGradient(this._lifeTimeGradients, gradient);
  61580. return this;
  61581. };
  61582. /**
  61583. * Adds a new size gradient
  61584. * @param gradient defines the gradient to use (between 0 and 1)
  61585. * @param factor defines the size factor to affect to the specified gradient
  61586. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  61587. * @returns the current particle system
  61588. */
  61589. ParticleSystem.prototype.addSizeGradient = function (gradient, factor, factor2) {
  61590. if (!this._sizeGradients) {
  61591. this._sizeGradients = [];
  61592. }
  61593. this._addFactorGradient(this._sizeGradients, gradient, factor, factor2);
  61594. return this;
  61595. };
  61596. /**
  61597. * Remove a specific size gradient
  61598. * @param gradient defines the gradient to remove
  61599. * @returns the current particle system
  61600. */
  61601. ParticleSystem.prototype.removeSizeGradient = function (gradient) {
  61602. this._removeFactorGradient(this._sizeGradients, gradient);
  61603. return this;
  61604. };
  61605. /**
  61606. * Adds a new color remap gradient
  61607. * @param gradient defines the gradient to use (between 0 and 1)
  61608. * @param min defines the color remap minimal range
  61609. * @param max defines the color remap maximal range
  61610. * @returns the current particle system
  61611. */
  61612. ParticleSystem.prototype.addColorRemapGradient = function (gradient, min, max) {
  61613. if (!this._colorRemapGradients) {
  61614. this._colorRemapGradients = [];
  61615. }
  61616. this._addFactorGradient(this._colorRemapGradients, gradient, min, max);
  61617. return this;
  61618. };
  61619. /**
  61620. * Remove a specific color remap gradient
  61621. * @param gradient defines the gradient to remove
  61622. * @returns the current particle system
  61623. */
  61624. ParticleSystem.prototype.removeColorRemapGradient = function (gradient) {
  61625. this._removeFactorGradient(this._colorRemapGradients, gradient);
  61626. return this;
  61627. };
  61628. /**
  61629. * Adds a new alpha remap gradient
  61630. * @param gradient defines the gradient to use (between 0 and 1)
  61631. * @param min defines the alpha remap minimal range
  61632. * @param max defines the alpha remap maximal range
  61633. * @returns the current particle system
  61634. */
  61635. ParticleSystem.prototype.addAlphaRemapGradient = function (gradient, min, max) {
  61636. if (!this._alphaRemapGradients) {
  61637. this._alphaRemapGradients = [];
  61638. }
  61639. this._addFactorGradient(this._alphaRemapGradients, gradient, min, max);
  61640. return this;
  61641. };
  61642. /**
  61643. * Remove a specific alpha remap gradient
  61644. * @param gradient defines the gradient to remove
  61645. * @returns the current particle system
  61646. */
  61647. ParticleSystem.prototype.removeAlphaRemapGradient = function (gradient) {
  61648. this._removeFactorGradient(this._alphaRemapGradients, gradient);
  61649. return this;
  61650. };
  61651. /**
  61652. * Adds a new angular speed gradient
  61653. * @param gradient defines the gradient to use (between 0 and 1)
  61654. * @param factor defines the angular speed to affect to the specified gradient
  61655. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  61656. * @returns the current particle system
  61657. */
  61658. ParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor, factor2) {
  61659. if (!this._angularSpeedGradients) {
  61660. this._angularSpeedGradients = [];
  61661. }
  61662. this._addFactorGradient(this._angularSpeedGradients, gradient, factor, factor2);
  61663. return this;
  61664. };
  61665. /**
  61666. * Remove a specific angular speed gradient
  61667. * @param gradient defines the gradient to remove
  61668. * @returns the current particle system
  61669. */
  61670. ParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  61671. this._removeFactorGradient(this._angularSpeedGradients, gradient);
  61672. return this;
  61673. };
  61674. /**
  61675. * Adds a new velocity gradient
  61676. * @param gradient defines the gradient to use (between 0 and 1)
  61677. * @param factor defines the velocity to affect to the specified gradient
  61678. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  61679. * @returns the current particle system
  61680. */
  61681. ParticleSystem.prototype.addVelocityGradient = function (gradient, factor, factor2) {
  61682. if (!this._velocityGradients) {
  61683. this._velocityGradients = [];
  61684. }
  61685. this._addFactorGradient(this._velocityGradients, gradient, factor, factor2);
  61686. return this;
  61687. };
  61688. /**
  61689. * Remove a specific velocity gradient
  61690. * @param gradient defines the gradient to remove
  61691. * @returns the current particle system
  61692. */
  61693. ParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  61694. this._removeFactorGradient(this._velocityGradients, gradient);
  61695. return this;
  61696. };
  61697. /**
  61698. * Adds a new limit velocity gradient
  61699. * @param gradient defines the gradient to use (between 0 and 1)
  61700. * @param factor defines the limit velocity value to affect to the specified gradient
  61701. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  61702. * @returns the current particle system
  61703. */
  61704. ParticleSystem.prototype.addLimitVelocityGradient = function (gradient, factor, factor2) {
  61705. if (!this._limitVelocityGradients) {
  61706. this._limitVelocityGradients = [];
  61707. }
  61708. this._addFactorGradient(this._limitVelocityGradients, gradient, factor, factor2);
  61709. return this;
  61710. };
  61711. /**
  61712. * Remove a specific limit velocity gradient
  61713. * @param gradient defines the gradient to remove
  61714. * @returns the current particle system
  61715. */
  61716. ParticleSystem.prototype.removeLimitVelocityGradient = function (gradient) {
  61717. this._removeFactorGradient(this._limitVelocityGradients, gradient);
  61718. return this;
  61719. };
  61720. /**
  61721. * Adds a new drag gradient
  61722. * @param gradient defines the gradient to use (between 0 and 1)
  61723. * @param factor defines the drag value to affect to the specified gradient
  61724. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  61725. * @returns the current particle system
  61726. */
  61727. ParticleSystem.prototype.addDragGradient = function (gradient, factor, factor2) {
  61728. if (!this._dragGradients) {
  61729. this._dragGradients = [];
  61730. }
  61731. this._addFactorGradient(this._dragGradients, gradient, factor, factor2);
  61732. return this;
  61733. };
  61734. /**
  61735. * Remove a specific drag gradient
  61736. * @param gradient defines the gradient to remove
  61737. * @returns the current particle system
  61738. */
  61739. ParticleSystem.prototype.removeDragGradient = function (gradient) {
  61740. this._removeFactorGradient(this._dragGradients, gradient);
  61741. return this;
  61742. };
  61743. /**
  61744. * Adds a new emit rate gradient (please note that this will only work if you set the targetStopDuration property)
  61745. * @param gradient defines the gradient to use (between 0 and 1)
  61746. * @param factor defines the emit rate value to affect to the specified gradient
  61747. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  61748. * @returns the current particle system
  61749. */
  61750. ParticleSystem.prototype.addEmitRateGradient = function (gradient, factor, factor2) {
  61751. if (!this._emitRateGradients) {
  61752. this._emitRateGradients = [];
  61753. }
  61754. this._addFactorGradient(this._emitRateGradients, gradient, factor, factor2);
  61755. return this;
  61756. };
  61757. /**
  61758. * Remove a specific emit rate gradient
  61759. * @param gradient defines the gradient to remove
  61760. * @returns the current particle system
  61761. */
  61762. ParticleSystem.prototype.removeEmitRateGradient = function (gradient) {
  61763. this._removeFactorGradient(this._emitRateGradients, gradient);
  61764. return this;
  61765. };
  61766. /**
  61767. * Adds a new start size gradient (please note that this will only work if you set the targetStopDuration property)
  61768. * @param gradient defines the gradient to use (between 0 and 1)
  61769. * @param factor defines the start size value to affect to the specified gradient
  61770. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  61771. * @returns the current particle system
  61772. */
  61773. ParticleSystem.prototype.addStartSizeGradient = function (gradient, factor, factor2) {
  61774. if (!this._startSizeGradients) {
  61775. this._startSizeGradients = [];
  61776. }
  61777. this._addFactorGradient(this._startSizeGradients, gradient, factor, factor2);
  61778. return this;
  61779. };
  61780. /**
  61781. * Remove a specific start size gradient
  61782. * @param gradient defines the gradient to remove
  61783. * @returns the current particle system
  61784. */
  61785. ParticleSystem.prototype.removeStartSizeGradient = function (gradient) {
  61786. this._removeFactorGradient(this._emitRateGradients, gradient);
  61787. return this;
  61788. };
  61789. ParticleSystem.prototype._createRampGradientTexture = function () {
  61790. if (!this._rampGradients || !this._rampGradients.length || this._rampGradientsTexture) {
  61791. return;
  61792. }
  61793. var data = new Uint8Array(this._rawTextureWidth * 4);
  61794. var tmpColor = BABYLON.Tmp.Color3[0];
  61795. for (var x = 0; x < this._rawTextureWidth; x++) {
  61796. var ratio = x / this._rawTextureWidth;
  61797. BABYLON.Tools.GetCurrentGradient(ratio, this._rampGradients, function (currentGradient, nextGradient, scale) {
  61798. BABYLON.Color3.LerpToRef(currentGradient.color, nextGradient.color, scale, tmpColor);
  61799. data[x * 4] = tmpColor.r * 255;
  61800. data[x * 4 + 1] = tmpColor.g * 255;
  61801. data[x * 4 + 2] = tmpColor.b * 255;
  61802. data[x * 4 + 3] = 255;
  61803. });
  61804. }
  61805. this._rampGradientsTexture = BABYLON.RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  61806. };
  61807. /**
  61808. * Gets the current list of ramp gradients.
  61809. * You must use addRampGradient and removeRampGradient to udpate this list
  61810. * @returns the list of ramp gradients
  61811. */
  61812. ParticleSystem.prototype.getRampGradients = function () {
  61813. return this._rampGradients;
  61814. };
  61815. /**
  61816. * Adds a new ramp gradient used to remap particle colors
  61817. * @param gradient defines the gradient to use (between 0 and 1)
  61818. * @param color defines the color to affect to the specified gradient
  61819. * @returns the current particle system
  61820. */
  61821. ParticleSystem.prototype.addRampGradient = function (gradient, color) {
  61822. if (!this._rampGradients) {
  61823. this._rampGradients = [];
  61824. }
  61825. var rampGradient = new BABYLON.Color3Gradient();
  61826. rampGradient.gradient = gradient;
  61827. rampGradient.color = color;
  61828. this._rampGradients.push(rampGradient);
  61829. this._rampGradients.sort(function (a, b) {
  61830. if (a.gradient < b.gradient) {
  61831. return -1;
  61832. }
  61833. else if (a.gradient > b.gradient) {
  61834. return 1;
  61835. }
  61836. return 0;
  61837. });
  61838. if (this._rampGradientsTexture) {
  61839. this._rampGradientsTexture.dispose();
  61840. this._rampGradientsTexture = null;
  61841. }
  61842. this._createRampGradientTexture();
  61843. return this;
  61844. };
  61845. /**
  61846. * Remove a specific ramp gradient
  61847. * @param gradient defines the gradient to remove
  61848. * @returns the current particle system
  61849. */
  61850. ParticleSystem.prototype.removeRampGradient = function (gradient) {
  61851. this._removeGradientAndTexture(gradient, this._rampGradients, this._rampGradientsTexture);
  61852. this._rampGradientsTexture = null;
  61853. if (this._rampGradients && this._rampGradients.length > 0) {
  61854. this._createRampGradientTexture();
  61855. }
  61856. return this;
  61857. };
  61858. /**
  61859. * Adds a new color gradient
  61860. * @param gradient defines the gradient to use (between 0 and 1)
  61861. * @param color1 defines the color to affect to the specified gradient
  61862. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  61863. * @returns this particle system
  61864. */
  61865. ParticleSystem.prototype.addColorGradient = function (gradient, color1, color2) {
  61866. if (!this._colorGradients) {
  61867. this._colorGradients = [];
  61868. }
  61869. var colorGradient = new BABYLON.ColorGradient();
  61870. colorGradient.gradient = gradient;
  61871. colorGradient.color1 = color1;
  61872. colorGradient.color2 = color2;
  61873. this._colorGradients.push(colorGradient);
  61874. this._colorGradients.sort(function (a, b) {
  61875. if (a.gradient < b.gradient) {
  61876. return -1;
  61877. }
  61878. else if (a.gradient > b.gradient) {
  61879. return 1;
  61880. }
  61881. return 0;
  61882. });
  61883. return this;
  61884. };
  61885. /**
  61886. * Remove a specific color gradient
  61887. * @param gradient defines the gradient to remove
  61888. * @returns this particle system
  61889. */
  61890. ParticleSystem.prototype.removeColorGradient = function (gradient) {
  61891. if (!this._colorGradients) {
  61892. return this;
  61893. }
  61894. var index = 0;
  61895. for (var _i = 0, _a = this._colorGradients; _i < _a.length; _i++) {
  61896. var colorGradient = _a[_i];
  61897. if (colorGradient.gradient === gradient) {
  61898. this._colorGradients.splice(index, 1);
  61899. break;
  61900. }
  61901. index++;
  61902. }
  61903. return this;
  61904. };
  61905. ParticleSystem.prototype._fetchR = function (u, v, width, height, pixels) {
  61906. u = Math.abs(u) * 0.5 + 0.5;
  61907. v = Math.abs(v) * 0.5 + 0.5;
  61908. var wrappedU = ((u * width) % width) | 0;
  61909. var wrappedV = ((v * height) % height) | 0;
  61910. var position = (wrappedU + wrappedV * width) * 4;
  61911. return pixels[position] / 255;
  61912. };
  61913. ParticleSystem.prototype._reset = function () {
  61914. this._resetEffect();
  61915. };
  61916. ParticleSystem.prototype._resetEffect = function () {
  61917. if (this._vertexBuffer) {
  61918. this._vertexBuffer.dispose();
  61919. this._vertexBuffer = null;
  61920. }
  61921. if (this._spriteBuffer) {
  61922. this._spriteBuffer.dispose();
  61923. this._spriteBuffer = null;
  61924. }
  61925. this._createVertexBuffers();
  61926. };
  61927. ParticleSystem.prototype._createVertexBuffers = function () {
  61928. this._vertexBufferSize = this._useInstancing ? 10 : 12;
  61929. if (this._isAnimationSheetEnabled) {
  61930. this._vertexBufferSize += 1;
  61931. }
  61932. if (!this._isBillboardBased || this.billboardMode === ParticleSystem.BILLBOARDMODE_STRETCHED) {
  61933. this._vertexBufferSize += 3;
  61934. }
  61935. if (this._useRampGradients) {
  61936. this._vertexBufferSize += 4;
  61937. }
  61938. var engine = this._scene.getEngine();
  61939. this._vertexData = new Float32Array(this._capacity * this._vertexBufferSize * (this._useInstancing ? 1 : 4));
  61940. this._vertexBuffer = new BABYLON.Buffer(engine, this._vertexData, true, this._vertexBufferSize);
  61941. var dataOffset = 0;
  61942. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  61943. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  61944. dataOffset += 3;
  61945. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, dataOffset, 4, this._vertexBufferSize, this._useInstancing);
  61946. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  61947. dataOffset += 4;
  61948. var options = this._vertexBuffer.createVertexBuffer("angle", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  61949. this._vertexBuffers["angle"] = options;
  61950. dataOffset += 1;
  61951. var size = this._vertexBuffer.createVertexBuffer("size", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  61952. this._vertexBuffers["size"] = size;
  61953. dataOffset += 2;
  61954. if (this._isAnimationSheetEnabled) {
  61955. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  61956. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  61957. dataOffset += 1;
  61958. }
  61959. if (!this._isBillboardBased || this.billboardMode === ParticleSystem.BILLBOARDMODE_STRETCHED) {
  61960. var directionBuffer = this._vertexBuffer.createVertexBuffer("direction", dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  61961. this._vertexBuffers["direction"] = directionBuffer;
  61962. dataOffset += 3;
  61963. }
  61964. if (this._useRampGradients) {
  61965. var rampDataBuffer = this._vertexBuffer.createVertexBuffer("remapData", dataOffset, 4, this._vertexBufferSize, this._useInstancing);
  61966. this._vertexBuffers["remapData"] = rampDataBuffer;
  61967. dataOffset += 4;
  61968. }
  61969. var offsets;
  61970. if (this._useInstancing) {
  61971. var spriteData = new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]);
  61972. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 2);
  61973. offsets = this._spriteBuffer.createVertexBuffer("offset", 0, 2);
  61974. }
  61975. else {
  61976. offsets = this._vertexBuffer.createVertexBuffer("offset", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  61977. dataOffset += 2;
  61978. }
  61979. this._vertexBuffers["offset"] = offsets;
  61980. };
  61981. ParticleSystem.prototype._createIndexBuffer = function () {
  61982. if (this._useInstancing) {
  61983. return;
  61984. }
  61985. var indices = [];
  61986. var index = 0;
  61987. for (var count = 0; count < this._capacity; count++) {
  61988. indices.push(index);
  61989. indices.push(index + 1);
  61990. indices.push(index + 2);
  61991. indices.push(index);
  61992. indices.push(index + 2);
  61993. indices.push(index + 3);
  61994. index += 4;
  61995. }
  61996. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  61997. };
  61998. /**
  61999. * Gets the maximum number of particles active at the same time.
  62000. * @returns The max number of active particles.
  62001. */
  62002. ParticleSystem.prototype.getCapacity = function () {
  62003. return this._capacity;
  62004. };
  62005. /**
  62006. * Gets whether there are still active particles in the system.
  62007. * @returns True if it is alive, otherwise false.
  62008. */
  62009. ParticleSystem.prototype.isAlive = function () {
  62010. return this._alive;
  62011. };
  62012. /**
  62013. * Gets if the system has been started. (Note: this will still be true after stop is called)
  62014. * @returns True if it has been started, otherwise false.
  62015. */
  62016. ParticleSystem.prototype.isStarted = function () {
  62017. return this._started;
  62018. };
  62019. ParticleSystem.prototype._prepareSubEmitterInternalArray = function () {
  62020. var _this = this;
  62021. this._subEmitters = new Array();
  62022. if (this.subEmitters) {
  62023. this.subEmitters.forEach(function (subEmitter) {
  62024. if (subEmitter instanceof ParticleSystem) {
  62025. _this._subEmitters.push([new BABYLON.SubEmitter(subEmitter)]);
  62026. }
  62027. else if (subEmitter instanceof BABYLON.SubEmitter) {
  62028. _this._subEmitters.push([subEmitter]);
  62029. }
  62030. else if (subEmitter instanceof Array) {
  62031. _this._subEmitters.push(subEmitter);
  62032. }
  62033. });
  62034. }
  62035. };
  62036. /**
  62037. * Starts the particle system and begins to emit
  62038. * @param delay defines the delay in milliseconds before starting the system (this.startDelay by default)
  62039. */
  62040. ParticleSystem.prototype.start = function (delay) {
  62041. var _this = this;
  62042. if (delay === void 0) { delay = this.startDelay; }
  62043. if (!this.targetStopDuration && this._hasTargetStopDurationDependantGradient()) {
  62044. throw "Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set";
  62045. }
  62046. if (delay) {
  62047. setTimeout(function () {
  62048. _this.start(0);
  62049. }, delay);
  62050. return;
  62051. }
  62052. // Convert the subEmitters field to the constant type field _subEmitters
  62053. this._prepareSubEmitterInternalArray();
  62054. this._started = true;
  62055. this._stopped = false;
  62056. this._actualFrame = 0;
  62057. if (this._subEmitters && this._subEmitters.length != 0) {
  62058. this.activeSubSystems = new Array();
  62059. }
  62060. // Reset emit gradient so it acts the same on every start
  62061. if (this._emitRateGradients) {
  62062. if (this._emitRateGradients.length > 0) {
  62063. this._currentEmitRateGradient = this._emitRateGradients[0];
  62064. this._currentEmitRate1 = this._currentEmitRateGradient.getFactor();
  62065. this._currentEmitRate2 = this._currentEmitRate1;
  62066. }
  62067. if (this._emitRateGradients.length > 1) {
  62068. this._currentEmitRate2 = this._emitRateGradients[1].getFactor();
  62069. }
  62070. }
  62071. // Reset start size gradient so it acts the same on every start
  62072. if (this._startSizeGradients) {
  62073. if (this._startSizeGradients.length > 0) {
  62074. this._currentStartSizeGradient = this._startSizeGradients[0];
  62075. this._currentStartSize1 = this._currentStartSizeGradient.getFactor();
  62076. this._currentStartSize2 = this._currentStartSize1;
  62077. }
  62078. if (this._startSizeGradients.length > 1) {
  62079. this._currentStartSize2 = this._startSizeGradients[1].getFactor();
  62080. }
  62081. }
  62082. if (this.preWarmCycles) {
  62083. if (this.emitter instanceof BABYLON.AbstractMesh) {
  62084. this.emitter.computeWorldMatrix(true);
  62085. }
  62086. var noiseTextureAsProcedural_1 = this.noiseTexture;
  62087. if (noiseTextureAsProcedural_1 && noiseTextureAsProcedural_1.onGeneratedObservable) {
  62088. noiseTextureAsProcedural_1.onGeneratedObservable.addOnce(function () {
  62089. setTimeout(function () {
  62090. for (var index = 0; index < _this.preWarmCycles; index++) {
  62091. _this.animate(true);
  62092. noiseTextureAsProcedural_1.render();
  62093. }
  62094. });
  62095. });
  62096. }
  62097. else {
  62098. for (var index = 0; index < this.preWarmCycles; index++) {
  62099. this.animate(true);
  62100. }
  62101. }
  62102. }
  62103. // Animations
  62104. if (this.beginAnimationOnStart && this.animations && this.animations.length > 0) {
  62105. this.getScene().beginAnimation(this, this.beginAnimationFrom, this.beginAnimationTo, this.beginAnimationLoop);
  62106. }
  62107. };
  62108. /**
  62109. * Stops the particle system.
  62110. * @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.
  62111. */
  62112. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  62113. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  62114. this._stopped = true;
  62115. if (stopSubEmitters) {
  62116. this._stopSubEmitters();
  62117. }
  62118. };
  62119. // animation sheet
  62120. /**
  62121. * Remove all active particles
  62122. */
  62123. ParticleSystem.prototype.reset = function () {
  62124. this._stockParticles = [];
  62125. this._particles = [];
  62126. };
  62127. /**
  62128. * @hidden (for internal use only)
  62129. */
  62130. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  62131. var offset = index * this._vertexBufferSize;
  62132. this._vertexData[offset++] = particle.position.x;
  62133. this._vertexData[offset++] = particle.position.y;
  62134. this._vertexData[offset++] = particle.position.z;
  62135. this._vertexData[offset++] = particle.color.r;
  62136. this._vertexData[offset++] = particle.color.g;
  62137. this._vertexData[offset++] = particle.color.b;
  62138. this._vertexData[offset++] = particle.color.a;
  62139. this._vertexData[offset++] = particle.angle;
  62140. this._vertexData[offset++] = particle.scale.x * particle.size;
  62141. this._vertexData[offset++] = particle.scale.y * particle.size;
  62142. if (this._isAnimationSheetEnabled) {
  62143. this._vertexData[offset++] = particle.cellIndex;
  62144. }
  62145. if (!this._isBillboardBased) {
  62146. if (particle._initialDirection) {
  62147. this._vertexData[offset++] = particle._initialDirection.x;
  62148. this._vertexData[offset++] = particle._initialDirection.y;
  62149. this._vertexData[offset++] = particle._initialDirection.z;
  62150. }
  62151. else {
  62152. this._vertexData[offset++] = particle.direction.x;
  62153. this._vertexData[offset++] = particle.direction.y;
  62154. this._vertexData[offset++] = particle.direction.z;
  62155. }
  62156. }
  62157. else if (this.billboardMode === ParticleSystem.BILLBOARDMODE_STRETCHED) {
  62158. this._vertexData[offset++] = particle.direction.x;
  62159. this._vertexData[offset++] = particle.direction.y;
  62160. this._vertexData[offset++] = particle.direction.z;
  62161. }
  62162. if (this._useRampGradients) {
  62163. this._vertexData[offset++] = particle.remapData.x;
  62164. this._vertexData[offset++] = particle.remapData.y;
  62165. this._vertexData[offset++] = particle.remapData.z;
  62166. this._vertexData[offset++] = particle.remapData.w;
  62167. }
  62168. if (!this._useInstancing) {
  62169. if (this._isAnimationSheetEnabled) {
  62170. if (offsetX === 0) {
  62171. offsetX = this._epsilon;
  62172. }
  62173. else if (offsetX === 1) {
  62174. offsetX = 1 - this._epsilon;
  62175. }
  62176. if (offsetY === 0) {
  62177. offsetY = this._epsilon;
  62178. }
  62179. else if (offsetY === 1) {
  62180. offsetY = 1 - this._epsilon;
  62181. }
  62182. }
  62183. this._vertexData[offset++] = offsetX;
  62184. this._vertexData[offset++] = offsetY;
  62185. }
  62186. };
  62187. ParticleSystem.prototype._stopSubEmitters = function () {
  62188. if (!this.activeSubSystems) {
  62189. return;
  62190. }
  62191. this.activeSubSystems.forEach(function (subSystem) {
  62192. subSystem.stop(true);
  62193. });
  62194. this.activeSubSystems = new Array();
  62195. };
  62196. ParticleSystem.prototype._removeFromRoot = function () {
  62197. if (!this._rootParticleSystem) {
  62198. return;
  62199. }
  62200. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  62201. if (index !== -1) {
  62202. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  62203. }
  62204. this._rootParticleSystem = null;
  62205. };
  62206. // End of sub system methods
  62207. ParticleSystem.prototype._update = function (newParticles) {
  62208. var _this = this;
  62209. // Update current
  62210. this._alive = this._particles.length > 0;
  62211. if (this.emitter.position) {
  62212. var emitterMesh = this.emitter;
  62213. this._emitterWorldMatrix = emitterMesh.getWorldMatrix();
  62214. }
  62215. else {
  62216. var emitterPosition = this.emitter;
  62217. this._emitterWorldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  62218. }
  62219. this.updateFunction(this._particles);
  62220. // Add new ones
  62221. var particle;
  62222. var _loop_2 = function () {
  62223. if (this_1._particles.length === this_1._capacity) {
  62224. return "break";
  62225. }
  62226. particle = this_1._createParticle();
  62227. this_1._particles.push(particle);
  62228. // Emitter
  62229. var emitPower = BABYLON.Scalar.RandomRange(this_1.minEmitPower, this_1.maxEmitPower);
  62230. if (this_1.startPositionFunction) {
  62231. this_1.startPositionFunction(this_1._emitterWorldMatrix, particle.position, particle);
  62232. }
  62233. else {
  62234. this_1.particleEmitterType.startPositionFunction(this_1._emitterWorldMatrix, particle.position, particle);
  62235. }
  62236. if (this_1.startDirectionFunction) {
  62237. this_1.startDirectionFunction(this_1._emitterWorldMatrix, particle.direction, particle);
  62238. }
  62239. else {
  62240. this_1.particleEmitterType.startDirectionFunction(this_1._emitterWorldMatrix, particle.direction, particle);
  62241. }
  62242. if (emitPower === 0) {
  62243. if (!particle._initialDirection) {
  62244. particle._initialDirection = particle.direction.clone();
  62245. }
  62246. else {
  62247. particle._initialDirection.copyFrom(particle.direction);
  62248. }
  62249. }
  62250. else {
  62251. particle._initialDirection = null;
  62252. }
  62253. particle.direction.scaleInPlace(emitPower);
  62254. // Life time
  62255. if (this_1.targetStopDuration && this_1._lifeTimeGradients && this_1._lifeTimeGradients.length > 0) {
  62256. var ratio_1 = BABYLON.Scalar.Clamp(this_1._actualFrame / this_1.targetStopDuration);
  62257. BABYLON.Tools.GetCurrentGradient(ratio_1, this_1._lifeTimeGradients, function (currentGradient, nextGradient, scale) {
  62258. var factorGradient1 = currentGradient;
  62259. var factorGradient2 = nextGradient;
  62260. var lifeTime1 = factorGradient1.getFactor();
  62261. var lifeTime2 = factorGradient2.getFactor();
  62262. var gradient = (ratio_1 - factorGradient1.gradient) / (factorGradient2.gradient - factorGradient1.gradient);
  62263. particle.lifeTime = BABYLON.Scalar.Lerp(lifeTime1, lifeTime2, gradient);
  62264. });
  62265. }
  62266. else {
  62267. particle.lifeTime = BABYLON.Scalar.RandomRange(this_1.minLifeTime, this_1.maxLifeTime);
  62268. }
  62269. // Size
  62270. if (!this_1._sizeGradients || this_1._sizeGradients.length === 0) {
  62271. particle.size = BABYLON.Scalar.RandomRange(this_1.minSize, this_1.maxSize);
  62272. }
  62273. else {
  62274. particle._currentSizeGradient = this_1._sizeGradients[0];
  62275. particle._currentSize1 = particle._currentSizeGradient.getFactor();
  62276. particle.size = particle._currentSize1;
  62277. if (this_1._sizeGradients.length > 1) {
  62278. particle._currentSize2 = this_1._sizeGradients[1].getFactor();
  62279. }
  62280. else {
  62281. particle._currentSize2 = particle._currentSize1;
  62282. }
  62283. }
  62284. // Size and scale
  62285. particle.scale.copyFromFloats(BABYLON.Scalar.RandomRange(this_1.minScaleX, this_1.maxScaleX), BABYLON.Scalar.RandomRange(this_1.minScaleY, this_1.maxScaleY));
  62286. // Adjust scale by start size
  62287. if (this_1._startSizeGradients && this_1._startSizeGradients[0] && this_1.targetStopDuration) {
  62288. var ratio = this_1._actualFrame / this_1.targetStopDuration;
  62289. BABYLON.Tools.GetCurrentGradient(ratio, this_1._startSizeGradients, function (currentGradient, nextGradient, scale) {
  62290. if (currentGradient !== _this._currentStartSizeGradient) {
  62291. _this._currentStartSize1 = _this._currentStartSize2;
  62292. _this._currentStartSize2 = nextGradient.getFactor();
  62293. _this._currentStartSizeGradient = currentGradient;
  62294. }
  62295. var value = BABYLON.Scalar.Lerp(_this._currentStartSize1, _this._currentStartSize2, scale);
  62296. particle.scale.scaleInPlace(value);
  62297. });
  62298. }
  62299. // Angle
  62300. if (!this_1._angularSpeedGradients || this_1._angularSpeedGradients.length === 0) {
  62301. particle.angularSpeed = BABYLON.Scalar.RandomRange(this_1.minAngularSpeed, this_1.maxAngularSpeed);
  62302. }
  62303. else {
  62304. particle._currentAngularSpeedGradient = this_1._angularSpeedGradients[0];
  62305. particle.angularSpeed = particle._currentAngularSpeedGradient.getFactor();
  62306. particle._currentAngularSpeed1 = particle.angularSpeed;
  62307. if (this_1._angularSpeedGradients.length > 1) {
  62308. particle._currentAngularSpeed2 = this_1._angularSpeedGradients[1].getFactor();
  62309. }
  62310. else {
  62311. particle._currentAngularSpeed2 = particle._currentAngularSpeed1;
  62312. }
  62313. }
  62314. particle.angle = BABYLON.Scalar.RandomRange(this_1.minInitialRotation, this_1.maxInitialRotation);
  62315. // Velocity
  62316. if (this_1._velocityGradients && this_1._velocityGradients.length > 0) {
  62317. particle._currentVelocityGradient = this_1._velocityGradients[0];
  62318. particle._currentVelocity1 = particle._currentVelocityGradient.getFactor();
  62319. if (this_1._velocityGradients.length > 1) {
  62320. particle._currentVelocity2 = this_1._velocityGradients[1].getFactor();
  62321. }
  62322. else {
  62323. particle._currentVelocity2 = particle._currentVelocity1;
  62324. }
  62325. }
  62326. // Limit velocity
  62327. if (this_1._limitVelocityGradients && this_1._limitVelocityGradients.length > 0) {
  62328. particle._currentLimitVelocityGradient = this_1._limitVelocityGradients[0];
  62329. particle._currentLimitVelocity1 = particle._currentLimitVelocityGradient.getFactor();
  62330. if (this_1._limitVelocityGradients.length > 1) {
  62331. particle._currentLimitVelocity2 = this_1._limitVelocityGradients[1].getFactor();
  62332. }
  62333. else {
  62334. particle._currentLimitVelocity2 = particle._currentLimitVelocity1;
  62335. }
  62336. }
  62337. // Drag
  62338. if (this_1._dragGradients && this_1._dragGradients.length > 0) {
  62339. particle._currentDragGradient = this_1._dragGradients[0];
  62340. particle._currentDrag1 = particle._currentDragGradient.getFactor();
  62341. if (this_1._dragGradients.length > 1) {
  62342. particle._currentDrag2 = this_1._dragGradients[1].getFactor();
  62343. }
  62344. else {
  62345. particle._currentDrag2 = particle._currentDrag1;
  62346. }
  62347. }
  62348. // Color
  62349. if (!this_1._colorGradients || this_1._colorGradients.length === 0) {
  62350. step = BABYLON.Scalar.RandomRange(0, 1.0);
  62351. BABYLON.Color4.LerpToRef(this_1.color1, this_1.color2, step, particle.color);
  62352. this_1.colorDead.subtractToRef(particle.color, this_1._colorDiff);
  62353. this_1._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  62354. }
  62355. else {
  62356. particle._currentColorGradient = this_1._colorGradients[0];
  62357. particle._currentColorGradient.getColorToRef(particle.color);
  62358. particle._currentColor1.copyFrom(particle.color);
  62359. if (this_1._colorGradients.length > 1) {
  62360. this_1._colorGradients[1].getColorToRef(particle._currentColor2);
  62361. }
  62362. else {
  62363. particle._currentColor2.copyFrom(particle.color);
  62364. }
  62365. }
  62366. // Sheet
  62367. if (this_1._isAnimationSheetEnabled) {
  62368. particle._initialStartSpriteCellID = this_1.startSpriteCellID;
  62369. particle._initialEndSpriteCellID = this_1.endSpriteCellID;
  62370. }
  62371. // Inherited Velocity
  62372. particle.direction.addInPlace(this_1._inheritedVelocityOffset);
  62373. // Ramp
  62374. if (this_1._useRampGradients) {
  62375. particle.remapData = new BABYLON.Vector4(0, 1, 0, 1);
  62376. }
  62377. // Noise texture coordinates
  62378. if (this_1.noiseTexture) {
  62379. if (particle._randomNoiseCoordinates1) {
  62380. particle._randomNoiseCoordinates1.copyFromFloats(Math.random(), Math.random(), Math.random());
  62381. particle._randomNoiseCoordinates2.copyFromFloats(Math.random(), Math.random(), Math.random());
  62382. }
  62383. else {
  62384. particle._randomNoiseCoordinates1 = new BABYLON.Vector3(Math.random(), Math.random(), Math.random());
  62385. particle._randomNoiseCoordinates2 = new BABYLON.Vector3(Math.random(), Math.random(), Math.random());
  62386. }
  62387. }
  62388. // Update the position of the attached sub-emitters to match their attached particle
  62389. particle._inheritParticleInfoToSubEmitters();
  62390. };
  62391. var this_1 = this, step;
  62392. for (var index = 0; index < newParticles; index++) {
  62393. var state_1 = _loop_2();
  62394. if (state_1 === "break")
  62395. break;
  62396. }
  62397. };
  62398. /** @hidden */
  62399. ParticleSystem._GetAttributeNamesOrOptions = function (isAnimationSheetEnabled, isBillboardBased, useRampGradients) {
  62400. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  62401. if (isBillboardBased === void 0) { isBillboardBased = false; }
  62402. if (useRampGradients === void 0) { useRampGradients = false; }
  62403. var attributeNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "angle", "offset", "size"];
  62404. if (isAnimationSheetEnabled) {
  62405. attributeNamesOrOptions.push("cellIndex");
  62406. }
  62407. if (!isBillboardBased) {
  62408. attributeNamesOrOptions.push("direction");
  62409. }
  62410. if (useRampGradients) {
  62411. attributeNamesOrOptions.push("remapData");
  62412. }
  62413. return attributeNamesOrOptions;
  62414. };
  62415. /** @hidden */
  62416. ParticleSystem._GetEffectCreationOptions = function (isAnimationSheetEnabled) {
  62417. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  62418. var effectCreationOption = ["invView", "view", "projection", "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "textureMask", "translationPivot", "eyePosition"];
  62419. if (isAnimationSheetEnabled) {
  62420. effectCreationOption.push("particlesInfos");
  62421. }
  62422. return effectCreationOption;
  62423. };
  62424. /** @hidden */
  62425. ParticleSystem.prototype._getEffect = function (blendMode) {
  62426. if (this._customEffect) {
  62427. return this._customEffect;
  62428. }
  62429. var defines = [];
  62430. if (this._scene.clipPlane) {
  62431. defines.push("#define CLIPPLANE");
  62432. }
  62433. if (this._scene.clipPlane2) {
  62434. defines.push("#define CLIPPLANE2");
  62435. }
  62436. if (this._scene.clipPlane3) {
  62437. defines.push("#define CLIPPLANE3");
  62438. }
  62439. if (this._scene.clipPlane4) {
  62440. defines.push("#define CLIPPLANE4");
  62441. }
  62442. if (this._isAnimationSheetEnabled) {
  62443. defines.push("#define ANIMATESHEET");
  62444. }
  62445. if (blendMode === ParticleSystem.BLENDMODE_MULTIPLY) {
  62446. defines.push("#define BLENDMULTIPLYMODE");
  62447. }
  62448. if (this._useRampGradients) {
  62449. defines.push("#define RAMPGRADIENT");
  62450. }
  62451. if (this._isBillboardBased) {
  62452. defines.push("#define BILLBOARD");
  62453. switch (this.billboardMode) {
  62454. case ParticleSystem.BILLBOARDMODE_Y:
  62455. defines.push("#define BILLBOARDY");
  62456. break;
  62457. case ParticleSystem.BILLBOARDMODE_STRETCHED:
  62458. defines.push("#define BILLBOARDSTRETCHED");
  62459. break;
  62460. case ParticleSystem.BILLBOARDMODE_ALL:
  62461. default:
  62462. break;
  62463. }
  62464. }
  62465. if (this._imageProcessingConfiguration) {
  62466. this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines);
  62467. defines.push(this._imageProcessingConfigurationDefines.toString());
  62468. }
  62469. // Effect
  62470. var join = defines.join("\n");
  62471. if (this._cachedDefines !== join) {
  62472. this._cachedDefines = join;
  62473. var attributesNamesOrOptions = ParticleSystem._GetAttributeNamesOrOptions(this._isAnimationSheetEnabled, this._isBillboardBased && this.billboardMode !== ParticleSystem.BILLBOARDMODE_STRETCHED, this._useRampGradients);
  62474. var effectCreationOption = ParticleSystem._GetEffectCreationOptions(this._isAnimationSheetEnabled);
  62475. var samplers = ["diffuseSampler", "rampSampler"];
  62476. if (BABYLON.ImageProcessingConfiguration) {
  62477. BABYLON.ImageProcessingConfiguration.PrepareUniforms(effectCreationOption, this._imageProcessingConfigurationDefines);
  62478. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._imageProcessingConfigurationDefines);
  62479. }
  62480. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, samplers, join);
  62481. }
  62482. return this._effect;
  62483. };
  62484. /**
  62485. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  62486. * @param preWarmOnly will prevent the system from updating the vertex buffer (default is false)
  62487. */
  62488. ParticleSystem.prototype.animate = function (preWarmOnly) {
  62489. var _this = this;
  62490. if (preWarmOnly === void 0) { preWarmOnly = false; }
  62491. if (!this._started) {
  62492. return;
  62493. }
  62494. if (!preWarmOnly) {
  62495. // Check
  62496. if (!this.isReady()) {
  62497. return;
  62498. }
  62499. if (this._currentRenderId === this._scene.getFrameId()) {
  62500. return;
  62501. }
  62502. this._currentRenderId = this._scene.getFrameId();
  62503. }
  62504. this._scaledUpdateSpeed = this.updateSpeed * (preWarmOnly ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  62505. // Determine the number of particles we need to create
  62506. var newParticles;
  62507. if (this.manualEmitCount > -1) {
  62508. newParticles = this.manualEmitCount;
  62509. this._newPartsExcess = 0;
  62510. this.manualEmitCount = 0;
  62511. }
  62512. else {
  62513. var rate_1 = this.emitRate;
  62514. if (this._emitRateGradients && this._emitRateGradients.length > 0 && this.targetStopDuration) {
  62515. var ratio = this._actualFrame / this.targetStopDuration;
  62516. BABYLON.Tools.GetCurrentGradient(ratio, this._emitRateGradients, function (currentGradient, nextGradient, scale) {
  62517. if (currentGradient !== _this._currentEmitRateGradient) {
  62518. _this._currentEmitRate1 = _this._currentEmitRate2;
  62519. _this._currentEmitRate2 = nextGradient.getFactor();
  62520. _this._currentEmitRateGradient = currentGradient;
  62521. }
  62522. rate_1 = BABYLON.Scalar.Lerp(_this._currentEmitRate1, _this._currentEmitRate2, scale);
  62523. });
  62524. }
  62525. newParticles = ((rate_1 * this._scaledUpdateSpeed) >> 0);
  62526. this._newPartsExcess += rate_1 * this._scaledUpdateSpeed - newParticles;
  62527. }
  62528. if (this._newPartsExcess > 1.0) {
  62529. newParticles += this._newPartsExcess >> 0;
  62530. this._newPartsExcess -= this._newPartsExcess >> 0;
  62531. }
  62532. this._alive = false;
  62533. if (!this._stopped) {
  62534. this._actualFrame += this._scaledUpdateSpeed;
  62535. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  62536. this.stop();
  62537. }
  62538. }
  62539. else {
  62540. newParticles = 0;
  62541. }
  62542. this._update(newParticles);
  62543. // Stopped?
  62544. if (this._stopped) {
  62545. if (!this._alive) {
  62546. this._started = false;
  62547. if (this.onAnimationEnd) {
  62548. this.onAnimationEnd();
  62549. }
  62550. if (this.disposeOnStop) {
  62551. this._scene._toBeDisposed.push(this);
  62552. }
  62553. }
  62554. }
  62555. if (!preWarmOnly) {
  62556. // Update VBO
  62557. var offset = 0;
  62558. for (var index = 0; index < this._particles.length; index++) {
  62559. var particle = this._particles[index];
  62560. this._appendParticleVertices(offset, particle);
  62561. offset += this._useInstancing ? 1 : 4;
  62562. }
  62563. if (this._vertexBuffer) {
  62564. this._vertexBuffer.update(this._vertexData);
  62565. }
  62566. }
  62567. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  62568. this.stop();
  62569. }
  62570. };
  62571. ParticleSystem.prototype._appendParticleVertices = function (offset, particle) {
  62572. this._appendParticleVertex(offset++, particle, 0, 0);
  62573. if (!this._useInstancing) {
  62574. this._appendParticleVertex(offset++, particle, 1, 0);
  62575. this._appendParticleVertex(offset++, particle, 1, 1);
  62576. this._appendParticleVertex(offset++, particle, 0, 1);
  62577. }
  62578. };
  62579. /**
  62580. * Rebuilds the particle system.
  62581. */
  62582. ParticleSystem.prototype.rebuild = function () {
  62583. this._createIndexBuffer();
  62584. if (this._vertexBuffer) {
  62585. this._vertexBuffer._rebuild();
  62586. }
  62587. };
  62588. /**
  62589. * Is this system ready to be used/rendered
  62590. * @return true if the system is ready
  62591. */
  62592. ParticleSystem.prototype.isReady = function () {
  62593. if (!this.emitter || !this._imageProcessingConfiguration.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  62594. return false;
  62595. }
  62596. if (this.blendMode !== ParticleSystem.BLENDMODE_MULTIPLYADD) {
  62597. if (!this._getEffect(this.blendMode).isReady()) {
  62598. return false;
  62599. }
  62600. }
  62601. else {
  62602. if (!this._getEffect(ParticleSystem.BLENDMODE_MULTIPLY).isReady()) {
  62603. return false;
  62604. }
  62605. if (!this._getEffect(ParticleSystem.BLENDMODE_ADD).isReady()) {
  62606. return false;
  62607. }
  62608. }
  62609. return true;
  62610. };
  62611. ParticleSystem.prototype._render = function (blendMode) {
  62612. var effect = this._getEffect(blendMode);
  62613. var engine = this._scene.getEngine();
  62614. // Render
  62615. engine.enableEffect(effect);
  62616. var viewMatrix = this._scene.getViewMatrix();
  62617. effect.setTexture("diffuseSampler", this.particleTexture);
  62618. effect.setMatrix("view", viewMatrix);
  62619. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  62620. if (this._isAnimationSheetEnabled && this.particleTexture) {
  62621. var baseSize = this.particleTexture.getBaseSize();
  62622. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  62623. }
  62624. effect.setVector2("translationPivot", this.translationPivot);
  62625. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  62626. if (this._isBillboardBased) {
  62627. var camera = this._scene.activeCamera;
  62628. effect.setVector3("eyePosition", camera.globalPosition);
  62629. }
  62630. if (this._rampGradientsTexture) {
  62631. effect.setTexture("rampSampler", this._rampGradientsTexture);
  62632. }
  62633. if (this._scene.clipPlane || this._scene.clipPlane2 || this._scene.clipPlane3 || this._scene.clipPlane4) {
  62634. var invView = viewMatrix.clone();
  62635. invView.invert();
  62636. effect.setMatrix("invView", invView);
  62637. BABYLON.MaterialHelper.BindClipPlane(effect, this._scene);
  62638. }
  62639. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  62640. // image processing
  62641. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  62642. this._imageProcessingConfiguration.bind(effect);
  62643. }
  62644. // Draw order
  62645. switch (blendMode) {
  62646. case ParticleSystem.BLENDMODE_ADD:
  62647. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  62648. break;
  62649. case ParticleSystem.BLENDMODE_ONEONE:
  62650. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  62651. break;
  62652. case ParticleSystem.BLENDMODE_STANDARD:
  62653. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  62654. break;
  62655. case ParticleSystem.BLENDMODE_MULTIPLY:
  62656. engine.setAlphaMode(BABYLON.Engine.ALPHA_MULTIPLY);
  62657. break;
  62658. }
  62659. if (this._useInstancing) {
  62660. engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._particles.length);
  62661. }
  62662. else {
  62663. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  62664. }
  62665. return this._particles.length;
  62666. };
  62667. /**
  62668. * Renders the particle system in its current state.
  62669. * @returns the current number of particles
  62670. */
  62671. ParticleSystem.prototype.render = function () {
  62672. // Check
  62673. if (!this.isReady() || !this._particles.length) {
  62674. return 0;
  62675. }
  62676. var engine = this._scene.getEngine();
  62677. engine.setState(false);
  62678. if (this.forceDepthWrite) {
  62679. engine.setDepthWrite(true);
  62680. }
  62681. var outparticles = 0;
  62682. if (this.blendMode === ParticleSystem.BLENDMODE_MULTIPLYADD) {
  62683. outparticles = this._render(ParticleSystem.BLENDMODE_MULTIPLY) + this._render(ParticleSystem.BLENDMODE_ADD);
  62684. }
  62685. outparticles = this._render(this.blendMode);
  62686. engine.unbindInstanceAttributes();
  62687. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  62688. return outparticles;
  62689. };
  62690. /**
  62691. * Disposes the particle system and free the associated resources
  62692. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  62693. */
  62694. ParticleSystem.prototype.dispose = function (disposeTexture) {
  62695. if (disposeTexture === void 0) { disposeTexture = true; }
  62696. if (this._vertexBuffer) {
  62697. this._vertexBuffer.dispose();
  62698. this._vertexBuffer = null;
  62699. }
  62700. if (this._spriteBuffer) {
  62701. this._spriteBuffer.dispose();
  62702. this._spriteBuffer = null;
  62703. }
  62704. if (this._indexBuffer) {
  62705. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  62706. this._indexBuffer = null;
  62707. }
  62708. if (disposeTexture && this.particleTexture) {
  62709. this.particleTexture.dispose();
  62710. this.particleTexture = null;
  62711. }
  62712. if (disposeTexture && this.noiseTexture) {
  62713. this.noiseTexture.dispose();
  62714. this.noiseTexture = null;
  62715. }
  62716. if (this._rampGradientsTexture) {
  62717. this._rampGradientsTexture.dispose();
  62718. this._rampGradientsTexture = null;
  62719. }
  62720. this._removeFromRoot();
  62721. if (this._subEmitters && this._subEmitters.length) {
  62722. for (var index = 0; index < this._subEmitters.length; index++) {
  62723. for (var _i = 0, _a = this._subEmitters[index]; _i < _a.length; _i++) {
  62724. var subEmitter = _a[_i];
  62725. subEmitter.dispose();
  62726. }
  62727. }
  62728. this._subEmitters = [];
  62729. this.subEmitters = [];
  62730. }
  62731. if (this._disposeEmitterOnDispose && this.emitter && this.emitter.dispose) {
  62732. this.emitter.dispose(true);
  62733. }
  62734. // Remove from scene
  62735. var index = this._scene.particleSystems.indexOf(this);
  62736. if (index > -1) {
  62737. this._scene.particleSystems.splice(index, 1);
  62738. }
  62739. this._scene._activeParticleSystems.dispose();
  62740. // Callback
  62741. this.onDisposeObservable.notifyObservers(this);
  62742. this.onDisposeObservable.clear();
  62743. this.reset();
  62744. };
  62745. // Clone
  62746. /**
  62747. * Clones the particle system.
  62748. * @param name The name of the cloned object
  62749. * @param newEmitter The new emitter to use
  62750. * @returns the cloned particle system
  62751. */
  62752. ParticleSystem.prototype.clone = function (name, newEmitter) {
  62753. var custom = null;
  62754. var program = null;
  62755. if (this.customShader != null) {
  62756. program = this.customShader;
  62757. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  62758. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  62759. }
  62760. else if (this._customEffect) {
  62761. custom = this._customEffect;
  62762. }
  62763. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  62764. result.customShader = program;
  62765. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader", "noiseTexture"]);
  62766. if (newEmitter === undefined) {
  62767. newEmitter = this.emitter;
  62768. }
  62769. result.noiseTexture = this.noiseTexture;
  62770. result.emitter = newEmitter;
  62771. if (this.particleTexture) {
  62772. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  62773. }
  62774. // Clone gradients
  62775. if (this._colorGradients) {
  62776. this._colorGradients.forEach(function (v) {
  62777. result.addColorGradient(v.gradient, v.color1, v.color2);
  62778. });
  62779. }
  62780. if (this._dragGradients) {
  62781. this._dragGradients.forEach(function (v) {
  62782. result.addDragGradient(v.gradient, v.factor1, v.factor2);
  62783. });
  62784. }
  62785. if (this._angularSpeedGradients) {
  62786. this._angularSpeedGradients.forEach(function (v) {
  62787. result.addAngularSpeedGradient(v.gradient, v.factor1, v.factor2);
  62788. });
  62789. }
  62790. if (this._emitRateGradients) {
  62791. this._emitRateGradients.forEach(function (v) {
  62792. result.addEmitRateGradient(v.gradient, v.factor1, v.factor2);
  62793. });
  62794. }
  62795. if (this._lifeTimeGradients) {
  62796. this._lifeTimeGradients.forEach(function (v) {
  62797. result.addLifeTimeGradient(v.gradient, v.factor1, v.factor2);
  62798. });
  62799. }
  62800. if (this._limitVelocityGradients) {
  62801. this._limitVelocityGradients.forEach(function (v) {
  62802. result.addLimitVelocityGradient(v.gradient, v.factor1, v.factor2);
  62803. });
  62804. }
  62805. if (this._sizeGradients) {
  62806. this._sizeGradients.forEach(function (v) {
  62807. result.addSizeGradient(v.gradient, v.factor1, v.factor2);
  62808. });
  62809. }
  62810. if (this._startSizeGradients) {
  62811. this._startSizeGradients.forEach(function (v) {
  62812. result.addStartSizeGradient(v.gradient, v.factor1, v.factor2);
  62813. });
  62814. }
  62815. if (this._velocityGradients) {
  62816. this._velocityGradients.forEach(function (v) {
  62817. result.addVelocityGradient(v.gradient, v.factor1, v.factor2);
  62818. });
  62819. }
  62820. if (this._rampGradients) {
  62821. this._rampGradients.forEach(function (v) {
  62822. result.addRampGradient(v.gradient, v.color);
  62823. });
  62824. }
  62825. if (this._colorRemapGradients) {
  62826. this._colorRemapGradients.forEach(function (v) {
  62827. result.addColorRemapGradient(v.gradient, v.factor1, v.factor2);
  62828. });
  62829. }
  62830. if (this._alphaRemapGradients) {
  62831. this._alphaRemapGradients.forEach(function (v) {
  62832. result.addAlphaRemapGradient(v.gradient, v.factor1, v.factor2);
  62833. });
  62834. }
  62835. if (!this.preventAutoStart) {
  62836. result.start();
  62837. }
  62838. return result;
  62839. };
  62840. /**
  62841. * Serializes the particle system to a JSON object.
  62842. * @returns the JSON object
  62843. */
  62844. ParticleSystem.prototype.serialize = function () {
  62845. var serializationObject = {};
  62846. ParticleSystem._Serialize(serializationObject, this);
  62847. serializationObject.textureMask = this.textureMask.asArray();
  62848. serializationObject.customShader = this.customShader;
  62849. serializationObject.preventAutoStart = this.preventAutoStart;
  62850. // SubEmitters
  62851. if (this.subEmitters) {
  62852. serializationObject.subEmitters = [];
  62853. if (!this._subEmitters) {
  62854. this._prepareSubEmitterInternalArray();
  62855. }
  62856. for (var _i = 0, _a = this._subEmitters; _i < _a.length; _i++) {
  62857. var subs = _a[_i];
  62858. var cell = [];
  62859. for (var _b = 0, subs_1 = subs; _b < subs_1.length; _b++) {
  62860. var sub = subs_1[_b];
  62861. cell.push(sub.serialize());
  62862. }
  62863. serializationObject.subEmitters.push(cell);
  62864. }
  62865. }
  62866. return serializationObject;
  62867. };
  62868. /** @hidden */
  62869. ParticleSystem._Serialize = function (serializationObject, particleSystem) {
  62870. serializationObject.name = particleSystem.name;
  62871. serializationObject.id = particleSystem.id;
  62872. serializationObject.capacity = particleSystem.getCapacity();
  62873. // Emitter
  62874. if (particleSystem.emitter.position) {
  62875. var emitterMesh = particleSystem.emitter;
  62876. serializationObject.emitterId = emitterMesh.id;
  62877. }
  62878. else {
  62879. var emitterPosition = particleSystem.emitter;
  62880. serializationObject.emitter = emitterPosition.asArray();
  62881. }
  62882. // Emitter
  62883. if (particleSystem.particleEmitterType) {
  62884. serializationObject.particleEmitterType = particleSystem.particleEmitterType.serialize();
  62885. }
  62886. if (particleSystem.particleTexture) {
  62887. serializationObject.textureName = particleSystem.particleTexture.name;
  62888. serializationObject.invertY = particleSystem.particleTexture._invertY;
  62889. }
  62890. // Animations
  62891. BABYLON.Animation.AppendSerializedAnimations(particleSystem, serializationObject);
  62892. serializationObject.beginAnimationOnStart = particleSystem.beginAnimationOnStart;
  62893. serializationObject.beginAnimationFrom = particleSystem.beginAnimationFrom;
  62894. serializationObject.beginAnimationTo = particleSystem.beginAnimationTo;
  62895. serializationObject.beginAnimationLoop = particleSystem.beginAnimationLoop;
  62896. // Particle system
  62897. serializationObject.startDelay = particleSystem.startDelay;
  62898. serializationObject.renderingGroupId = particleSystem.renderingGroupId;
  62899. serializationObject.isBillboardBased = particleSystem.isBillboardBased;
  62900. serializationObject.billboardMode = particleSystem.billboardMode;
  62901. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  62902. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  62903. serializationObject.minSize = particleSystem.minSize;
  62904. serializationObject.maxSize = particleSystem.maxSize;
  62905. serializationObject.minScaleX = particleSystem.minScaleX;
  62906. serializationObject.maxScaleX = particleSystem.maxScaleX;
  62907. serializationObject.minScaleY = particleSystem.minScaleY;
  62908. serializationObject.maxScaleY = particleSystem.maxScaleY;
  62909. serializationObject.minEmitPower = particleSystem.minEmitPower;
  62910. serializationObject.maxEmitPower = particleSystem.maxEmitPower;
  62911. serializationObject.minLifeTime = particleSystem.minLifeTime;
  62912. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  62913. serializationObject.emitRate = particleSystem.emitRate;
  62914. serializationObject.gravity = particleSystem.gravity.asArray();
  62915. serializationObject.noiseStrength = particleSystem.noiseStrength.asArray();
  62916. serializationObject.color1 = particleSystem.color1.asArray();
  62917. serializationObject.color2 = particleSystem.color2.asArray();
  62918. serializationObject.colorDead = particleSystem.colorDead.asArray();
  62919. serializationObject.updateSpeed = particleSystem.updateSpeed;
  62920. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  62921. serializationObject.blendMode = particleSystem.blendMode;
  62922. serializationObject.preWarmCycles = particleSystem.preWarmCycles;
  62923. serializationObject.preWarmStepOffset = particleSystem.preWarmStepOffset;
  62924. serializationObject.minInitialRotation = particleSystem.minInitialRotation;
  62925. serializationObject.maxInitialRotation = particleSystem.maxInitialRotation;
  62926. serializationObject.startSpriteCellID = particleSystem.startSpriteCellID;
  62927. serializationObject.endSpriteCellID = particleSystem.endSpriteCellID;
  62928. serializationObject.spriteCellChangeSpeed = particleSystem.spriteCellChangeSpeed;
  62929. serializationObject.spriteCellWidth = particleSystem.spriteCellWidth;
  62930. serializationObject.spriteCellHeight = particleSystem.spriteCellHeight;
  62931. serializationObject.spriteRandomStartCell = particleSystem.spriteRandomStartCell;
  62932. serializationObject.isAnimationSheetEnabled = particleSystem.isAnimationSheetEnabled;
  62933. var colorGradients = particleSystem.getColorGradients();
  62934. if (colorGradients) {
  62935. serializationObject.colorGradients = [];
  62936. for (var _i = 0, colorGradients_1 = colorGradients; _i < colorGradients_1.length; _i++) {
  62937. var colorGradient = colorGradients_1[_i];
  62938. var serializedGradient = {
  62939. gradient: colorGradient.gradient,
  62940. color1: colorGradient.color1.asArray()
  62941. };
  62942. if (colorGradient.color2) {
  62943. serializedGradient.color2 = colorGradient.color2.asArray();
  62944. }
  62945. serializationObject.colorGradients.push(serializedGradient);
  62946. }
  62947. }
  62948. var rampGradients = particleSystem.getRampGradients();
  62949. if (rampGradients) {
  62950. serializationObject.rampGradients = [];
  62951. for (var _a = 0, rampGradients_1 = rampGradients; _a < rampGradients_1.length; _a++) {
  62952. var rampGradient = rampGradients_1[_a];
  62953. var serializedGradient = {
  62954. gradient: rampGradient.gradient,
  62955. color: rampGradient.color.asArray()
  62956. };
  62957. serializationObject.rampGradients.push(serializedGradient);
  62958. }
  62959. serializationObject.useRampGradients = particleSystem.useRampGradients;
  62960. }
  62961. var colorRemapGradients = particleSystem.getColorRemapGradients();
  62962. if (colorRemapGradients) {
  62963. serializationObject.colorRemapGradients = [];
  62964. for (var _b = 0, colorRemapGradients_1 = colorRemapGradients; _b < colorRemapGradients_1.length; _b++) {
  62965. var colorRemapGradient = colorRemapGradients_1[_b];
  62966. var serializedGradient = {
  62967. gradient: colorRemapGradient.gradient,
  62968. factor1: colorRemapGradient.factor1
  62969. };
  62970. if (colorRemapGradient.factor2 !== undefined) {
  62971. serializedGradient.factor2 = colorRemapGradient.factor2;
  62972. }
  62973. serializationObject.colorRemapGradients.push(serializedGradient);
  62974. }
  62975. }
  62976. var alphaRemapGradients = particleSystem.getAlphaRemapGradients();
  62977. if (alphaRemapGradients) {
  62978. serializationObject.alphaRemapGradients = [];
  62979. for (var _c = 0, alphaRemapGradients_1 = alphaRemapGradients; _c < alphaRemapGradients_1.length; _c++) {
  62980. var alphaRemapGradient = alphaRemapGradients_1[_c];
  62981. var serializedGradient = {
  62982. gradient: alphaRemapGradient.gradient,
  62983. factor1: alphaRemapGradient.factor1
  62984. };
  62985. if (alphaRemapGradient.factor2 !== undefined) {
  62986. serializedGradient.factor2 = alphaRemapGradient.factor2;
  62987. }
  62988. serializationObject.alphaRemapGradients.push(serializedGradient);
  62989. }
  62990. }
  62991. var sizeGradients = particleSystem.getSizeGradients();
  62992. if (sizeGradients) {
  62993. serializationObject.sizeGradients = [];
  62994. for (var _d = 0, sizeGradients_1 = sizeGradients; _d < sizeGradients_1.length; _d++) {
  62995. var sizeGradient = sizeGradients_1[_d];
  62996. var serializedGradient = {
  62997. gradient: sizeGradient.gradient,
  62998. factor1: sizeGradient.factor1
  62999. };
  63000. if (sizeGradient.factor2 !== undefined) {
  63001. serializedGradient.factor2 = sizeGradient.factor2;
  63002. }
  63003. serializationObject.sizeGradients.push(serializedGradient);
  63004. }
  63005. }
  63006. var angularSpeedGradients = particleSystem.getAngularSpeedGradients();
  63007. if (angularSpeedGradients) {
  63008. serializationObject.angularSpeedGradients = [];
  63009. for (var _e = 0, angularSpeedGradients_1 = angularSpeedGradients; _e < angularSpeedGradients_1.length; _e++) {
  63010. var angularSpeedGradient = angularSpeedGradients_1[_e];
  63011. var serializedGradient = {
  63012. gradient: angularSpeedGradient.gradient,
  63013. factor1: angularSpeedGradient.factor1
  63014. };
  63015. if (angularSpeedGradient.factor2 !== undefined) {
  63016. serializedGradient.factor2 = angularSpeedGradient.factor2;
  63017. }
  63018. serializationObject.angularSpeedGradients.push(serializedGradient);
  63019. }
  63020. }
  63021. var velocityGradients = particleSystem.getVelocityGradients();
  63022. if (velocityGradients) {
  63023. serializationObject.velocityGradients = [];
  63024. for (var _f = 0, velocityGradients_1 = velocityGradients; _f < velocityGradients_1.length; _f++) {
  63025. var velocityGradient = velocityGradients_1[_f];
  63026. var serializedGradient = {
  63027. gradient: velocityGradient.gradient,
  63028. factor1: velocityGradient.factor1
  63029. };
  63030. if (velocityGradient.factor2 !== undefined) {
  63031. serializedGradient.factor2 = velocityGradient.factor2;
  63032. }
  63033. serializationObject.velocityGradients.push(serializedGradient);
  63034. }
  63035. }
  63036. var dragGradients = particleSystem.getDragGradients();
  63037. if (dragGradients) {
  63038. serializationObject.dragyGradients = [];
  63039. for (var _g = 0, dragGradients_1 = dragGradients; _g < dragGradients_1.length; _g++) {
  63040. var dragGradient = dragGradients_1[_g];
  63041. var serializedGradient = {
  63042. gradient: dragGradient.gradient,
  63043. factor1: dragGradient.factor1
  63044. };
  63045. if (dragGradient.factor2 !== undefined) {
  63046. serializedGradient.factor2 = dragGradient.factor2;
  63047. }
  63048. serializationObject.dragGradients.push(serializedGradient);
  63049. }
  63050. }
  63051. var emitRateGradients = particleSystem.getEmitRateGradients();
  63052. if (emitRateGradients) {
  63053. serializationObject.emitRateGradients = [];
  63054. for (var _h = 0, emitRateGradients_1 = emitRateGradients; _h < emitRateGradients_1.length; _h++) {
  63055. var emitRateGradient = emitRateGradients_1[_h];
  63056. var serializedGradient = {
  63057. gradient: emitRateGradient.gradient,
  63058. factor1: emitRateGradient.factor1
  63059. };
  63060. if (emitRateGradient.factor2 !== undefined) {
  63061. serializedGradient.factor2 = emitRateGradient.factor2;
  63062. }
  63063. serializationObject.emitRateGradients.push(serializedGradient);
  63064. }
  63065. }
  63066. var startSizeGradients = particleSystem.getStartSizeGradients();
  63067. if (startSizeGradients) {
  63068. serializationObject.startSizeGradients = [];
  63069. for (var _j = 0, startSizeGradients_1 = startSizeGradients; _j < startSizeGradients_1.length; _j++) {
  63070. var startSizeGradient = startSizeGradients_1[_j];
  63071. var serializedGradient = {
  63072. gradient: startSizeGradient.gradient,
  63073. factor1: startSizeGradient.factor1
  63074. };
  63075. if (startSizeGradient.factor2 !== undefined) {
  63076. serializedGradient.factor2 = startSizeGradient.factor2;
  63077. }
  63078. serializationObject.startSizeGradients.push(serializedGradient);
  63079. }
  63080. }
  63081. var lifeTimeGradients = particleSystem.getLifeTimeGradients();
  63082. if (lifeTimeGradients) {
  63083. serializationObject.lifeTimeGradients = [];
  63084. for (var _k = 0, lifeTimeGradients_1 = lifeTimeGradients; _k < lifeTimeGradients_1.length; _k++) {
  63085. var lifeTimeGradient = lifeTimeGradients_1[_k];
  63086. var serializedGradient = {
  63087. gradient: lifeTimeGradient.gradient,
  63088. factor1: lifeTimeGradient.factor1
  63089. };
  63090. if (lifeTimeGradient.factor2 !== undefined) {
  63091. serializedGradient.factor2 = lifeTimeGradient.factor2;
  63092. }
  63093. serializationObject.lifeTimeGradients.push(serializedGradient);
  63094. }
  63095. }
  63096. var limitVelocityGradients = particleSystem.getLimitVelocityGradients();
  63097. if (limitVelocityGradients) {
  63098. serializationObject.limitVelocityGradients = [];
  63099. for (var _l = 0, limitVelocityGradients_1 = limitVelocityGradients; _l < limitVelocityGradients_1.length; _l++) {
  63100. var limitVelocityGradient = limitVelocityGradients_1[_l];
  63101. var serializedGradient = {
  63102. gradient: limitVelocityGradient.gradient,
  63103. factor1: limitVelocityGradient.factor1
  63104. };
  63105. if (limitVelocityGradient.factor2 !== undefined) {
  63106. serializedGradient.factor2 = limitVelocityGradient.factor2;
  63107. }
  63108. serializationObject.limitVelocityGradients.push(serializedGradient);
  63109. }
  63110. serializationObject.limitVelocityDamping = particleSystem.limitVelocityDamping;
  63111. }
  63112. if (particleSystem.noiseTexture) {
  63113. serializationObject.noiseTexture = particleSystem.noiseTexture.serialize();
  63114. }
  63115. };
  63116. /** @hidden */
  63117. ParticleSystem._Parse = function (parsedParticleSystem, particleSystem, scene, rootUrl) {
  63118. // Texture
  63119. if (parsedParticleSystem.textureName) {
  63120. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene, false, parsedParticleSystem.invertY !== undefined ? parsedParticleSystem.invertY : true);
  63121. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  63122. }
  63123. // Emitter
  63124. if (!parsedParticleSystem.emitterId && parsedParticleSystem.emitterId !== 0 && parsedParticleSystem.emitter === undefined) {
  63125. particleSystem.emitter = BABYLON.Vector3.Zero();
  63126. }
  63127. else if (parsedParticleSystem.emitterId) {
  63128. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  63129. }
  63130. else {
  63131. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  63132. }
  63133. // Misc.
  63134. if (parsedParticleSystem.renderingGroupId !== undefined) {
  63135. particleSystem.renderingGroupId = parsedParticleSystem.renderingGroupId;
  63136. }
  63137. if (parsedParticleSystem.isBillboardBased !== undefined) {
  63138. particleSystem.isBillboardBased = parsedParticleSystem.isBillboardBased;
  63139. }
  63140. if (parsedParticleSystem.billboardMode !== undefined) {
  63141. particleSystem.billboardMode = parsedParticleSystem.billboardMode;
  63142. }
  63143. // Animations
  63144. if (parsedParticleSystem.animations) {
  63145. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  63146. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  63147. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  63148. }
  63149. particleSystem.beginAnimationOnStart = parsedParticleSystem.beginAnimationOnStart;
  63150. particleSystem.beginAnimationFrom = parsedParticleSystem.beginAnimationFrom;
  63151. particleSystem.beginAnimationTo = parsedParticleSystem.beginAnimationTo;
  63152. particleSystem.beginAnimationLoop = parsedParticleSystem.beginAnimationLoop;
  63153. }
  63154. if (parsedParticleSystem.autoAnimate) {
  63155. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  63156. }
  63157. // Particle system
  63158. particleSystem.startDelay = parsedParticleSystem.startDelay | 0;
  63159. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  63160. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  63161. particleSystem.minSize = parsedParticleSystem.minSize;
  63162. particleSystem.maxSize = parsedParticleSystem.maxSize;
  63163. if (parsedParticleSystem.minScaleX) {
  63164. particleSystem.minScaleX = parsedParticleSystem.minScaleX;
  63165. particleSystem.maxScaleX = parsedParticleSystem.maxScaleX;
  63166. particleSystem.minScaleY = parsedParticleSystem.minScaleY;
  63167. particleSystem.maxScaleY = parsedParticleSystem.maxScaleY;
  63168. }
  63169. if (parsedParticleSystem.preWarmCycles !== undefined) {
  63170. particleSystem.preWarmCycles = parsedParticleSystem.preWarmCycles;
  63171. particleSystem.preWarmStepOffset = parsedParticleSystem.preWarmStepOffset;
  63172. }
  63173. if (parsedParticleSystem.minInitialRotation !== undefined) {
  63174. particleSystem.minInitialRotation = parsedParticleSystem.minInitialRotation;
  63175. particleSystem.maxInitialRotation = parsedParticleSystem.maxInitialRotation;
  63176. }
  63177. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  63178. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  63179. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  63180. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  63181. particleSystem.emitRate = parsedParticleSystem.emitRate;
  63182. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  63183. if (parsedParticleSystem.noiseStrength) {
  63184. particleSystem.noiseStrength = BABYLON.Vector3.FromArray(parsedParticleSystem.noiseStrength);
  63185. }
  63186. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  63187. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  63188. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  63189. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  63190. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  63191. particleSystem.blendMode = parsedParticleSystem.blendMode;
  63192. if (parsedParticleSystem.colorGradients) {
  63193. for (var _i = 0, _a = parsedParticleSystem.colorGradients; _i < _a.length; _i++) {
  63194. var colorGradient = _a[_i];
  63195. particleSystem.addColorGradient(colorGradient.gradient, BABYLON.Color4.FromArray(colorGradient.color1), colorGradient.color2 ? BABYLON.Color4.FromArray(colorGradient.color2) : undefined);
  63196. }
  63197. }
  63198. if (parsedParticleSystem.rampGradients) {
  63199. for (var _b = 0, _c = parsedParticleSystem.rampGradients; _b < _c.length; _b++) {
  63200. var rampGradient = _c[_b];
  63201. particleSystem.addRampGradient(rampGradient.gradient, BABYLON.Color3.FromArray(rampGradient.color));
  63202. }
  63203. particleSystem.useRampGradients = parsedParticleSystem.useRampGradients;
  63204. }
  63205. if (parsedParticleSystem.colorRemapGradients) {
  63206. for (var _d = 0, _e = parsedParticleSystem.colorRemapGradients; _d < _e.length; _d++) {
  63207. var colorRemapGradient = _e[_d];
  63208. particleSystem.addColorRemapGradient(colorRemapGradient.gradient, colorRemapGradient.factor1 !== undefined ? colorRemapGradient.factor1 : colorRemapGradient.factor, colorRemapGradient.factor2);
  63209. }
  63210. }
  63211. if (parsedParticleSystem.alphaRemapGradients) {
  63212. for (var _f = 0, _g = parsedParticleSystem.alphaRemapGradients; _f < _g.length; _f++) {
  63213. var alphaRemapGradient = _g[_f];
  63214. particleSystem.addAlphaRemapGradient(alphaRemapGradient.gradient, alphaRemapGradient.factor1 !== undefined ? alphaRemapGradient.factor1 : alphaRemapGradient.factor, alphaRemapGradient.factor2);
  63215. }
  63216. }
  63217. if (parsedParticleSystem.sizeGradients) {
  63218. for (var _h = 0, _j = parsedParticleSystem.sizeGradients; _h < _j.length; _h++) {
  63219. var sizeGradient = _j[_h];
  63220. particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor1 !== undefined ? sizeGradient.factor1 : sizeGradient.factor, sizeGradient.factor2);
  63221. }
  63222. }
  63223. if (parsedParticleSystem.sizeGradients) {
  63224. for (var _k = 0, _l = parsedParticleSystem.sizeGradients; _k < _l.length; _k++) {
  63225. var sizeGradient = _l[_k];
  63226. particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor1 !== undefined ? sizeGradient.factor1 : sizeGradient.factor, sizeGradient.factor2);
  63227. }
  63228. }
  63229. if (parsedParticleSystem.angularSpeedGradients) {
  63230. for (var _m = 0, _o = parsedParticleSystem.angularSpeedGradients; _m < _o.length; _m++) {
  63231. var angularSpeedGradient = _o[_m];
  63232. particleSystem.addAngularSpeedGradient(angularSpeedGradient.gradient, angularSpeedGradient.factor1 !== undefined ? angularSpeedGradient.factor1 : angularSpeedGradient.factor, angularSpeedGradient.factor2);
  63233. }
  63234. }
  63235. if (parsedParticleSystem.velocityGradients) {
  63236. for (var _p = 0, _q = parsedParticleSystem.velocityGradients; _p < _q.length; _p++) {
  63237. var velocityGradient = _q[_p];
  63238. particleSystem.addVelocityGradient(velocityGradient.gradient, velocityGradient.factor1 !== undefined ? velocityGradient.factor1 : velocityGradient.factor, velocityGradient.factor2);
  63239. }
  63240. }
  63241. if (parsedParticleSystem.dragGradients) {
  63242. for (var _r = 0, _s = parsedParticleSystem.dragGradients; _r < _s.length; _r++) {
  63243. var dragGradient = _s[_r];
  63244. particleSystem.addDragGradient(dragGradient.gradient, dragGradient.factor1 !== undefined ? dragGradient.factor1 : dragGradient.factor, dragGradient.factor2);
  63245. }
  63246. }
  63247. if (parsedParticleSystem.emitRateGradients) {
  63248. for (var _t = 0, _u = parsedParticleSystem.emitRateGradients; _t < _u.length; _t++) {
  63249. var emitRateGradient = _u[_t];
  63250. particleSystem.addEmitRateGradient(emitRateGradient.gradient, emitRateGradient.factor1 !== undefined ? emitRateGradient.factor1 : emitRateGradient.factor, emitRateGradient.factor2);
  63251. }
  63252. }
  63253. if (parsedParticleSystem.startSizeGradients) {
  63254. for (var _v = 0, _w = parsedParticleSystem.startSizeGradients; _v < _w.length; _v++) {
  63255. var startSizeGradient = _w[_v];
  63256. particleSystem.addStartSizeGradient(startSizeGradient.gradient, startSizeGradient.factor1 !== undefined ? startSizeGradient.factor1 : startSizeGradient.factor, startSizeGradient.factor2);
  63257. }
  63258. }
  63259. if (parsedParticleSystem.lifeTimeGradients) {
  63260. for (var _x = 0, _y = parsedParticleSystem.lifeTimeGradients; _x < _y.length; _x++) {
  63261. var lifeTimeGradient = _y[_x];
  63262. particleSystem.addLifeTimeGradient(lifeTimeGradient.gradient, lifeTimeGradient.factor1 !== undefined ? lifeTimeGradient.factor1 : lifeTimeGradient.factor, lifeTimeGradient.factor2);
  63263. }
  63264. }
  63265. if (parsedParticleSystem.limitVelocityGradients) {
  63266. for (var _z = 0, _0 = parsedParticleSystem.limitVelocityGradients; _z < _0.length; _z++) {
  63267. var limitVelocityGradient = _0[_z];
  63268. particleSystem.addLimitVelocityGradient(limitVelocityGradient.gradient, limitVelocityGradient.factor1 !== undefined ? limitVelocityGradient.factor1 : limitVelocityGradient.factor, limitVelocityGradient.factor2);
  63269. }
  63270. particleSystem.limitVelocityDamping = parsedParticleSystem.limitVelocityDamping;
  63271. }
  63272. if (parsedParticleSystem.noiseTexture) {
  63273. particleSystem.noiseTexture = BABYLON.ProceduralTexture.Parse(parsedParticleSystem.noiseTexture, scene, rootUrl);
  63274. }
  63275. // Emitter
  63276. var emitterType;
  63277. if (parsedParticleSystem.particleEmitterType) {
  63278. switch (parsedParticleSystem.particleEmitterType.type) {
  63279. case "SphereParticleEmitter":
  63280. emitterType = new BABYLON.SphereParticleEmitter();
  63281. break;
  63282. case "SphereDirectedParticleEmitter":
  63283. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  63284. break;
  63285. case "ConeEmitter":
  63286. case "ConeParticleEmitter":
  63287. emitterType = new BABYLON.ConeParticleEmitter();
  63288. break;
  63289. case "CylinderParticleEmitter":
  63290. emitterType = new BABYLON.CylinderParticleEmitter();
  63291. break;
  63292. case "HemisphericParticleEmitter":
  63293. emitterType = new BABYLON.HemisphericParticleEmitter();
  63294. break;
  63295. case "BoxEmitter":
  63296. case "BoxParticleEmitter":
  63297. default:
  63298. emitterType = new BABYLON.BoxParticleEmitter();
  63299. break;
  63300. }
  63301. emitterType.parse(parsedParticleSystem.particleEmitterType);
  63302. }
  63303. else {
  63304. emitterType = new BABYLON.BoxParticleEmitter();
  63305. emitterType.parse(parsedParticleSystem);
  63306. }
  63307. particleSystem.particleEmitterType = emitterType;
  63308. // Animation sheet
  63309. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  63310. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  63311. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  63312. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  63313. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  63314. particleSystem.spriteRandomStartCell = parsedParticleSystem.spriteRandomStartCell;
  63315. };
  63316. /**
  63317. * Parses a JSON object to create a particle system.
  63318. * @param parsedParticleSystem The JSON object to parse
  63319. * @param scene The scene to create the particle system in
  63320. * @param rootUrl The root url to use to load external dependencies like texture
  63321. * @param doNotStart Ignore the preventAutoStart attribute and does not start
  63322. * @returns the Parsed particle system
  63323. */
  63324. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl, doNotStart) {
  63325. if (doNotStart === void 0) { doNotStart = false; }
  63326. var name = parsedParticleSystem.name;
  63327. var custom = null;
  63328. var program = null;
  63329. if (parsedParticleSystem.customShader) {
  63330. program = parsedParticleSystem.customShader;
  63331. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  63332. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  63333. }
  63334. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  63335. particleSystem.customShader = program;
  63336. if (parsedParticleSystem.id) {
  63337. particleSystem.id = parsedParticleSystem.id;
  63338. }
  63339. // SubEmitters
  63340. if (parsedParticleSystem.subEmitters) {
  63341. particleSystem.subEmitters = [];
  63342. for (var _i = 0, _a = parsedParticleSystem.subEmitters; _i < _a.length; _i++) {
  63343. var cell = _a[_i];
  63344. var cellArray = [];
  63345. for (var _b = 0, cell_1 = cell; _b < cell_1.length; _b++) {
  63346. var sub = cell_1[_b];
  63347. cellArray.push(BABYLON.SubEmitter.Parse(sub, scene, rootUrl));
  63348. }
  63349. particleSystem.subEmitters.push(cellArray);
  63350. }
  63351. }
  63352. ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  63353. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  63354. // Auto start
  63355. if (parsedParticleSystem.preventAutoStart) {
  63356. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  63357. }
  63358. if (!doNotStart && !particleSystem.preventAutoStart) {
  63359. particleSystem.start();
  63360. }
  63361. return particleSystem;
  63362. };
  63363. /**
  63364. * Billboard mode will only apply to Y axis
  63365. */
  63366. ParticleSystem.BILLBOARDMODE_Y = 2;
  63367. /**
  63368. * Billboard mode will apply to all axes
  63369. */
  63370. ParticleSystem.BILLBOARDMODE_ALL = 7;
  63371. /**
  63372. * Special billboard mode where the particle will be biilboard to the camera but rotated to align with direction
  63373. */
  63374. ParticleSystem.BILLBOARDMODE_STRETCHED = 8;
  63375. return ParticleSystem;
  63376. }(BABYLON.BaseParticleSystem));
  63377. BABYLON.ParticleSystem = ParticleSystem;
  63378. })(BABYLON || (BABYLON = {}));
  63379. //# sourceMappingURL=babylon.particleSystem.js.map
  63380. var BABYLON;
  63381. (function (BABYLON) {
  63382. /**
  63383. * Particle emitter emitting particles from the inside of a box.
  63384. * It emits the particles randomly between 2 given directions.
  63385. */
  63386. var BoxParticleEmitter = /** @class */ (function () {
  63387. /**
  63388. * Creates a new instance BoxParticleEmitter
  63389. */
  63390. function BoxParticleEmitter() {
  63391. /**
  63392. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  63393. */
  63394. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  63395. /**
  63396. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  63397. */
  63398. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  63399. /**
  63400. * 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.
  63401. */
  63402. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  63403. /**
  63404. * 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.
  63405. */
  63406. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  63407. }
  63408. /**
  63409. * Called by the particle System when the direction is computed for the created particle.
  63410. * @param worldMatrix is the world matrix of the particle system
  63411. * @param directionToUpdate is the direction vector to update with the result
  63412. * @param particle is the particle we are computed the direction for
  63413. */
  63414. BoxParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  63415. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  63416. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  63417. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  63418. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  63419. };
  63420. /**
  63421. * Called by the particle System when the position is computed for the created particle.
  63422. * @param worldMatrix is the world matrix of the particle system
  63423. * @param positionToUpdate is the position vector to update with the result
  63424. * @param particle is the particle we are computed the position for
  63425. */
  63426. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  63427. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  63428. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  63429. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  63430. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  63431. };
  63432. /**
  63433. * Clones the current emitter and returns a copy of it
  63434. * @returns the new emitter
  63435. */
  63436. BoxParticleEmitter.prototype.clone = function () {
  63437. var newOne = new BoxParticleEmitter();
  63438. BABYLON.Tools.DeepCopy(this, newOne);
  63439. return newOne;
  63440. };
  63441. /**
  63442. * Called by the GPUParticleSystem to setup the update shader
  63443. * @param effect defines the update shader
  63444. */
  63445. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  63446. effect.setVector3("direction1", this.direction1);
  63447. effect.setVector3("direction2", this.direction2);
  63448. effect.setVector3("minEmitBox", this.minEmitBox);
  63449. effect.setVector3("maxEmitBox", this.maxEmitBox);
  63450. };
  63451. /**
  63452. * Returns a string to use to update the GPU particles update shader
  63453. * @returns a string containng the defines string
  63454. */
  63455. BoxParticleEmitter.prototype.getEffectDefines = function () {
  63456. return "#define BOXEMITTER";
  63457. };
  63458. /**
  63459. * Returns the string "BoxParticleEmitter"
  63460. * @returns a string containing the class name
  63461. */
  63462. BoxParticleEmitter.prototype.getClassName = function () {
  63463. return "BoxParticleEmitter";
  63464. };
  63465. /**
  63466. * Serializes the particle system to a JSON object.
  63467. * @returns the JSON object
  63468. */
  63469. BoxParticleEmitter.prototype.serialize = function () {
  63470. var serializationObject = {};
  63471. serializationObject.type = this.getClassName();
  63472. serializationObject.direction1 = this.direction1.asArray();
  63473. serializationObject.direction2 = this.direction2.asArray();
  63474. serializationObject.minEmitBox = this.minEmitBox.asArray();
  63475. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  63476. return serializationObject;
  63477. };
  63478. /**
  63479. * Parse properties from a JSON object
  63480. * @param serializationObject defines the JSON object
  63481. */
  63482. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  63483. BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
  63484. BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  63485. BABYLON.Vector3.FromArrayToRef(serializationObject.minEmitBox, 0, this.minEmitBox);
  63486. BABYLON.Vector3.FromArrayToRef(serializationObject.maxEmitBox, 0, this.maxEmitBox);
  63487. };
  63488. return BoxParticleEmitter;
  63489. }());
  63490. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  63491. })(BABYLON || (BABYLON = {}));
  63492. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  63493. var BABYLON;
  63494. (function (BABYLON) {
  63495. /**
  63496. * Particle emitter emitting particles from the inside of a cylinder.
  63497. * It emits the particles alongside the cylinder radius. The emission direction might be randomized.
  63498. */
  63499. var CylinderParticleEmitter = /** @class */ (function () {
  63500. /**
  63501. * Creates a new instance CylinderParticleEmitter
  63502. * @param radius the radius of the emission cylinder (1 by default)
  63503. * @param height the height of the emission cylinder (1 by default)
  63504. * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  63505. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  63506. */
  63507. function CylinderParticleEmitter(
  63508. /**
  63509. * The radius of the emission cylinder.
  63510. */
  63511. radius,
  63512. /**
  63513. * The height of the emission cylinder.
  63514. */
  63515. height,
  63516. /**
  63517. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  63518. */
  63519. radiusRange,
  63520. /**
  63521. * How much to randomize the particle direction [0-1].
  63522. */
  63523. directionRandomizer) {
  63524. if (radius === void 0) { radius = 1; }
  63525. if (height === void 0) { height = 1; }
  63526. if (radiusRange === void 0) { radiusRange = 1; }
  63527. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  63528. this.radius = radius;
  63529. this.height = height;
  63530. this.radiusRange = radiusRange;
  63531. this.directionRandomizer = directionRandomizer;
  63532. }
  63533. /**
  63534. * Called by the particle System when the direction is computed for the created particle.
  63535. * @param worldMatrix is the world matrix of the particle system
  63536. * @param directionToUpdate is the direction vector to update with the result
  63537. * @param particle is the particle we are computed the direction for
  63538. */
  63539. CylinderParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  63540. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  63541. var randY = BABYLON.Scalar.RandomRange(-this.directionRandomizer / 2, this.directionRandomizer / 2);
  63542. var angle = Math.atan2(direction.x, direction.z);
  63543. angle += BABYLON.Scalar.RandomRange(-Math.PI / 2, Math.PI / 2) * this.directionRandomizer;
  63544. direction.y = randY; // set direction y to rand y to mirror normal of cylinder surface
  63545. direction.x = Math.sin(angle);
  63546. direction.z = Math.cos(angle);
  63547. direction.normalize();
  63548. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  63549. };
  63550. /**
  63551. * Called by the particle System when the position is computed for the created particle.
  63552. * @param worldMatrix is the world matrix of the particle system
  63553. * @param positionToUpdate is the position vector to update with the result
  63554. * @param particle is the particle we are computed the position for
  63555. */
  63556. CylinderParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  63557. var yPos = BABYLON.Scalar.RandomRange(-this.height / 2, this.height / 2);
  63558. var angle = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  63559. // Pick a properly distributed point within the circle https://programming.guide/random-point-within-circle.html
  63560. var radiusDistribution = BABYLON.Scalar.RandomRange((1 - this.radiusRange) * (1 - this.radiusRange), 1);
  63561. var positionRadius = Math.sqrt(radiusDistribution) * this.radius;
  63562. var xPos = positionRadius * Math.cos(angle);
  63563. var zPos = positionRadius * Math.sin(angle);
  63564. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(xPos, yPos, zPos, worldMatrix, positionToUpdate);
  63565. };
  63566. /**
  63567. * Clones the current emitter and returns a copy of it
  63568. * @returns the new emitter
  63569. */
  63570. CylinderParticleEmitter.prototype.clone = function () {
  63571. var newOne = new CylinderParticleEmitter(this.radius, this.directionRandomizer);
  63572. BABYLON.Tools.DeepCopy(this, newOne);
  63573. return newOne;
  63574. };
  63575. /**
  63576. * Called by the GPUParticleSystem to setup the update shader
  63577. * @param effect defines the update shader
  63578. */
  63579. CylinderParticleEmitter.prototype.applyToShader = function (effect) {
  63580. effect.setFloat("radius", this.radius);
  63581. effect.setFloat("height", this.height);
  63582. effect.setFloat("radiusRange", this.radiusRange);
  63583. effect.setFloat("directionRandomizer", this.directionRandomizer);
  63584. };
  63585. /**
  63586. * Returns a string to use to update the GPU particles update shader
  63587. * @returns a string containng the defines string
  63588. */
  63589. CylinderParticleEmitter.prototype.getEffectDefines = function () {
  63590. return "#define CYLINDEREMITTER";
  63591. };
  63592. /**
  63593. * Returns the string "CylinderParticleEmitter"
  63594. * @returns a string containing the class name
  63595. */
  63596. CylinderParticleEmitter.prototype.getClassName = function () {
  63597. return "CylinderParticleEmitter";
  63598. };
  63599. /**
  63600. * Serializes the particle system to a JSON object.
  63601. * @returns the JSON object
  63602. */
  63603. CylinderParticleEmitter.prototype.serialize = function () {
  63604. var serializationObject = {};
  63605. serializationObject.type = this.getClassName();
  63606. serializationObject.radius = this.radius;
  63607. serializationObject.height = this.height;
  63608. serializationObject.radiusRange = this.radiusRange;
  63609. serializationObject.directionRandomizer = this.directionRandomizer;
  63610. return serializationObject;
  63611. };
  63612. /**
  63613. * Parse properties from a JSON object
  63614. * @param serializationObject defines the JSON object
  63615. */
  63616. CylinderParticleEmitter.prototype.parse = function (serializationObject) {
  63617. this.radius = serializationObject.radius;
  63618. this.height = serializationObject.height;
  63619. this.radiusRange = serializationObject.radiusRange;
  63620. this.directionRandomizer = serializationObject.directionRandomizer;
  63621. };
  63622. return CylinderParticleEmitter;
  63623. }());
  63624. BABYLON.CylinderParticleEmitter = CylinderParticleEmitter;
  63625. /**
  63626. * Particle emitter emitting particles from the inside of a cylinder.
  63627. * It emits the particles randomly between two vectors.
  63628. */
  63629. var CylinderDirectedParticleEmitter = /** @class */ (function (_super) {
  63630. __extends(CylinderDirectedParticleEmitter, _super);
  63631. /**
  63632. * Creates a new instance CylinderDirectedParticleEmitter
  63633. * @param radius the radius of the emission cylinder (1 by default)
  63634. * @param height the height of the emission cylinder (1 by default)
  63635. * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  63636. * @param direction1 the min limit of the emission direction (up vector by default)
  63637. * @param direction2 the max limit of the emission direction (up vector by default)
  63638. */
  63639. function CylinderDirectedParticleEmitter(radius, height, radiusRange,
  63640. /**
  63641. * The min limit of the emission direction.
  63642. */
  63643. direction1,
  63644. /**
  63645. * The max limit of the emission direction.
  63646. */
  63647. direction2) {
  63648. if (radius === void 0) { radius = 1; }
  63649. if (height === void 0) { height = 1; }
  63650. if (radiusRange === void 0) { radiusRange = 1; }
  63651. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  63652. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  63653. var _this = _super.call(this, radius, height, radiusRange) || this;
  63654. _this.direction1 = direction1;
  63655. _this.direction2 = direction2;
  63656. return _this;
  63657. }
  63658. /**
  63659. * Called by the particle System when the direction is computed for the created particle.
  63660. * @param worldMatrix is the world matrix of the particle system
  63661. * @param directionToUpdate is the direction vector to update with the result
  63662. * @param particle is the particle we are computed the direction for
  63663. */
  63664. CylinderDirectedParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  63665. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  63666. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  63667. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  63668. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  63669. };
  63670. /**
  63671. * Clones the current emitter and returns a copy of it
  63672. * @returns the new emitter
  63673. */
  63674. CylinderDirectedParticleEmitter.prototype.clone = function () {
  63675. var newOne = new CylinderDirectedParticleEmitter(this.radius, this.height, this.radiusRange, this.direction1, this.direction2);
  63676. BABYLON.Tools.DeepCopy(this, newOne);
  63677. return newOne;
  63678. };
  63679. /**
  63680. * Called by the GPUParticleSystem to setup the update shader
  63681. * @param effect defines the update shader
  63682. */
  63683. CylinderDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  63684. effect.setFloat("radius", this.radius);
  63685. effect.setFloat("height", this.height);
  63686. effect.setFloat("radiusRange", this.radiusRange);
  63687. effect.setVector3("direction1", this.direction1);
  63688. effect.setVector3("direction2", this.direction2);
  63689. };
  63690. /**
  63691. * Returns a string to use to update the GPU particles update shader
  63692. * @returns a string containng the defines string
  63693. */
  63694. CylinderDirectedParticleEmitter.prototype.getEffectDefines = function () {
  63695. return "#define CYLINDEREMITTER\n#define DIRECTEDCYLINDEREMITTER";
  63696. };
  63697. /**
  63698. * Returns the string "CylinderDirectedParticleEmitter"
  63699. * @returns a string containing the class name
  63700. */
  63701. CylinderDirectedParticleEmitter.prototype.getClassName = function () {
  63702. return "CylinderDirectedParticleEmitter";
  63703. };
  63704. /**
  63705. * Serializes the particle system to a JSON object.
  63706. * @returns the JSON object
  63707. */
  63708. CylinderDirectedParticleEmitter.prototype.serialize = function () {
  63709. var serializationObject = _super.prototype.serialize.call(this);
  63710. serializationObject.direction1 = this.direction1.asArray();
  63711. serializationObject.direction2 = this.direction2.asArray();
  63712. return serializationObject;
  63713. };
  63714. /**
  63715. * Parse properties from a JSON object
  63716. * @param serializationObject defines the JSON object
  63717. */
  63718. CylinderDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  63719. _super.prototype.parse.call(this, serializationObject);
  63720. this.direction1.copyFrom(serializationObject.direction1);
  63721. this.direction2.copyFrom(serializationObject.direction2);
  63722. };
  63723. return CylinderDirectedParticleEmitter;
  63724. }(CylinderParticleEmitter));
  63725. BABYLON.CylinderDirectedParticleEmitter = CylinderDirectedParticleEmitter;
  63726. })(BABYLON || (BABYLON = {}));
  63727. //# sourceMappingURL=babylon.cylinderParticleEmitter.js.map
  63728. var BABYLON;
  63729. (function (BABYLON) {
  63730. /**
  63731. * Particle emitter emitting particles from the inside of a cone.
  63732. * It emits the particles alongside the cone volume from the base to the particle.
  63733. * The emission direction might be randomized.
  63734. */
  63735. var ConeParticleEmitter = /** @class */ (function () {
  63736. /**
  63737. * Creates a new instance ConeParticleEmitter
  63738. * @param radius the radius of the emission cone (1 by default)
  63739. * @param angles the cone base angle (PI by default)
  63740. * @param directionRandomizer defines how much to randomize the particle direction [0-1] (default is 0)
  63741. */
  63742. function ConeParticleEmitter(radius, angle,
  63743. /** defines how much to randomize the particle direction [0-1] (default is 0) */
  63744. directionRandomizer) {
  63745. if (radius === void 0) { radius = 1; }
  63746. if (angle === void 0) { angle = Math.PI; }
  63747. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  63748. this.directionRandomizer = directionRandomizer;
  63749. /**
  63750. * Gets or sets a value indicating where on the radius the start position should be picked (1 = everywhere, 0 = only surface)
  63751. */
  63752. this.radiusRange = 1;
  63753. /**
  63754. * Gets or sets a value indicating where on the height the start position should be picked (1 = everywhere, 0 = only surface)
  63755. */
  63756. this.heightRange = 1;
  63757. /**
  63758. * Gets or sets a value indicating if all the particles should be emitted from the spawn point only (the base of the cone)
  63759. */
  63760. this.emitFromSpawnPointOnly = false;
  63761. this.angle = angle;
  63762. this.radius = radius;
  63763. }
  63764. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  63765. /**
  63766. * Gets or sets the radius of the emission cone
  63767. */
  63768. get: function () {
  63769. return this._radius;
  63770. },
  63771. set: function (value) {
  63772. this._radius = value;
  63773. this._buildHeight();
  63774. },
  63775. enumerable: true,
  63776. configurable: true
  63777. });
  63778. Object.defineProperty(ConeParticleEmitter.prototype, "angle", {
  63779. /**
  63780. * Gets or sets the angle of the emission cone
  63781. */
  63782. get: function () {
  63783. return this._angle;
  63784. },
  63785. set: function (value) {
  63786. this._angle = value;
  63787. this._buildHeight();
  63788. },
  63789. enumerable: true,
  63790. configurable: true
  63791. });
  63792. ConeParticleEmitter.prototype._buildHeight = function () {
  63793. if (this._angle !== 0) {
  63794. this._height = this._radius / Math.tan(this._angle / 2);
  63795. }
  63796. else {
  63797. this._height = 1;
  63798. }
  63799. };
  63800. /**
  63801. * Called by the particle System when the direction is computed for the created particle.
  63802. * @param worldMatrix is the world matrix of the particle system
  63803. * @param directionToUpdate is the direction vector to update with the result
  63804. * @param particle is the particle we are computed the direction for
  63805. */
  63806. ConeParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  63807. if (Math.abs(Math.cos(this._angle)) === 1.0) {
  63808. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, 1.0, 0, worldMatrix, directionToUpdate);
  63809. }
  63810. else {
  63811. // measure the direction Vector from the emitter to the particle.
  63812. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  63813. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  63814. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  63815. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  63816. direction.x += randX;
  63817. direction.y += randY;
  63818. direction.z += randZ;
  63819. direction.normalize();
  63820. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  63821. }
  63822. };
  63823. /**
  63824. * Called by the particle System when the position is computed for the created particle.
  63825. * @param worldMatrix is the world matrix of the particle system
  63826. * @param positionToUpdate is the position vector to update with the result
  63827. * @param particle is the particle we are computed the position for
  63828. */
  63829. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  63830. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  63831. var h;
  63832. if (!this.emitFromSpawnPointOnly) {
  63833. h = BABYLON.Scalar.RandomRange(0, this.heightRange);
  63834. // Better distribution in a cone at normal angles.
  63835. h = 1 - h * h;
  63836. }
  63837. else {
  63838. h = 0.0001;
  63839. }
  63840. var radius = this._radius - BABYLON.Scalar.RandomRange(0, this._radius * this.radiusRange);
  63841. radius = radius * h;
  63842. var randX = radius * Math.sin(s);
  63843. var randZ = radius * Math.cos(s);
  63844. var randY = h * this._height;
  63845. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  63846. };
  63847. /**
  63848. * Clones the current emitter and returns a copy of it
  63849. * @returns the new emitter
  63850. */
  63851. ConeParticleEmitter.prototype.clone = function () {
  63852. var newOne = new ConeParticleEmitter(this._radius, this._angle, this.directionRandomizer);
  63853. BABYLON.Tools.DeepCopy(this, newOne);
  63854. return newOne;
  63855. };
  63856. /**
  63857. * Called by the GPUParticleSystem to setup the update shader
  63858. * @param effect defines the update shader
  63859. */
  63860. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  63861. effect.setFloat2("radius", this._radius, this.radiusRange);
  63862. effect.setFloat("coneAngle", this._angle);
  63863. effect.setFloat2("height", this._height, this.heightRange);
  63864. effect.setFloat("directionRandomizer", this.directionRandomizer);
  63865. };
  63866. /**
  63867. * Returns a string to use to update the GPU particles update shader
  63868. * @returns a string containng the defines string
  63869. */
  63870. ConeParticleEmitter.prototype.getEffectDefines = function () {
  63871. var defines = "#define CONEEMITTER";
  63872. if (this.emitFromSpawnPointOnly) {
  63873. defines += "\n#define CONEEMITTERSPAWNPOINT";
  63874. }
  63875. return defines;
  63876. };
  63877. /**
  63878. * Returns the string "ConeParticleEmitter"
  63879. * @returns a string containing the class name
  63880. */
  63881. ConeParticleEmitter.prototype.getClassName = function () {
  63882. return "ConeParticleEmitter";
  63883. };
  63884. /**
  63885. * Serializes the particle system to a JSON object.
  63886. * @returns the JSON object
  63887. */
  63888. ConeParticleEmitter.prototype.serialize = function () {
  63889. var serializationObject = {};
  63890. serializationObject.type = this.getClassName();
  63891. serializationObject.radius = this._radius;
  63892. serializationObject.angle = this._angle;
  63893. serializationObject.directionRandomizer = this.directionRandomizer;
  63894. return serializationObject;
  63895. };
  63896. /**
  63897. * Parse properties from a JSON object
  63898. * @param serializationObject defines the JSON object
  63899. */
  63900. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  63901. this.radius = serializationObject.radius;
  63902. this.angle = serializationObject.angle;
  63903. this.directionRandomizer = serializationObject.directionRandomizer;
  63904. };
  63905. return ConeParticleEmitter;
  63906. }());
  63907. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  63908. })(BABYLON || (BABYLON = {}));
  63909. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  63910. var BABYLON;
  63911. (function (BABYLON) {
  63912. /**
  63913. * Particle emitter emitting particles from the inside of a sphere.
  63914. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  63915. */
  63916. var SphereParticleEmitter = /** @class */ (function () {
  63917. /**
  63918. * Creates a new instance SphereParticleEmitter
  63919. * @param radius the radius of the emission sphere (1 by default)
  63920. * @param radiusRange the range of the emission sphere [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  63921. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  63922. */
  63923. function SphereParticleEmitter(
  63924. /**
  63925. * The radius of the emission sphere.
  63926. */
  63927. radius,
  63928. /**
  63929. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  63930. */
  63931. radiusRange,
  63932. /**
  63933. * How much to randomize the particle direction [0-1].
  63934. */
  63935. directionRandomizer) {
  63936. if (radius === void 0) { radius = 1; }
  63937. if (radiusRange === void 0) { radiusRange = 1; }
  63938. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  63939. this.radius = radius;
  63940. this.radiusRange = radiusRange;
  63941. this.directionRandomizer = directionRandomizer;
  63942. }
  63943. /**
  63944. * Called by the particle System when the direction is computed for the created particle.
  63945. * @param worldMatrix is the world matrix of the particle system
  63946. * @param directionToUpdate is the direction vector to update with the result
  63947. * @param particle is the particle we are computed the direction for
  63948. */
  63949. SphereParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  63950. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  63951. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  63952. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  63953. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  63954. direction.x += randX;
  63955. direction.y += randY;
  63956. direction.z += randZ;
  63957. direction.normalize();
  63958. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  63959. };
  63960. /**
  63961. * Called by the particle System when the position is computed for the created particle.
  63962. * @param worldMatrix is the world matrix of the particle system
  63963. * @param positionToUpdate is the position vector to update with the result
  63964. * @param particle is the particle we are computed the position for
  63965. */
  63966. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  63967. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  63968. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  63969. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  63970. var theta = Math.acos(2 * v - 1);
  63971. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  63972. var randY = randRadius * Math.cos(theta);
  63973. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  63974. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  63975. };
  63976. /**
  63977. * Clones the current emitter and returns a copy of it
  63978. * @returns the new emitter
  63979. */
  63980. SphereParticleEmitter.prototype.clone = function () {
  63981. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  63982. BABYLON.Tools.DeepCopy(this, newOne);
  63983. return newOne;
  63984. };
  63985. /**
  63986. * Called by the GPUParticleSystem to setup the update shader
  63987. * @param effect defines the update shader
  63988. */
  63989. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  63990. effect.setFloat("radius", this.radius);
  63991. effect.setFloat("radiusRange", this.radiusRange);
  63992. effect.setFloat("directionRandomizer", this.directionRandomizer);
  63993. };
  63994. /**
  63995. * Returns a string to use to update the GPU particles update shader
  63996. * @returns a string containng the defines string
  63997. */
  63998. SphereParticleEmitter.prototype.getEffectDefines = function () {
  63999. return "#define SPHEREEMITTER";
  64000. };
  64001. /**
  64002. * Returns the string "SphereParticleEmitter"
  64003. * @returns a string containing the class name
  64004. */
  64005. SphereParticleEmitter.prototype.getClassName = function () {
  64006. return "SphereParticleEmitter";
  64007. };
  64008. /**
  64009. * Serializes the particle system to a JSON object.
  64010. * @returns the JSON object
  64011. */
  64012. SphereParticleEmitter.prototype.serialize = function () {
  64013. var serializationObject = {};
  64014. serializationObject.type = this.getClassName();
  64015. serializationObject.radius = this.radius;
  64016. serializationObject.radiusRange = this.radiusRange;
  64017. serializationObject.directionRandomizer = this.directionRandomizer;
  64018. return serializationObject;
  64019. };
  64020. /**
  64021. * Parse properties from a JSON object
  64022. * @param serializationObject defines the JSON object
  64023. */
  64024. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  64025. this.radius = serializationObject.radius;
  64026. this.radiusRange = serializationObject.radiusRange;
  64027. this.directionRandomizer = serializationObject.directionRandomizer;
  64028. };
  64029. return SphereParticleEmitter;
  64030. }());
  64031. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  64032. /**
  64033. * Particle emitter emitting particles from the inside of a sphere.
  64034. * It emits the particles randomly between two vectors.
  64035. */
  64036. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  64037. __extends(SphereDirectedParticleEmitter, _super);
  64038. /**
  64039. * Creates a new instance SphereDirectedParticleEmitter
  64040. * @param radius the radius of the emission sphere (1 by default)
  64041. * @param direction1 the min limit of the emission direction (up vector by default)
  64042. * @param direction2 the max limit of the emission direction (up vector by default)
  64043. */
  64044. function SphereDirectedParticleEmitter(radius,
  64045. /**
  64046. * The min limit of the emission direction.
  64047. */
  64048. direction1,
  64049. /**
  64050. * The max limit of the emission direction.
  64051. */
  64052. direction2) {
  64053. if (radius === void 0) { radius = 1; }
  64054. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  64055. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  64056. var _this = _super.call(this, radius) || this;
  64057. _this.direction1 = direction1;
  64058. _this.direction2 = direction2;
  64059. return _this;
  64060. }
  64061. /**
  64062. * Called by the particle System when the direction is computed for the created particle.
  64063. * @param worldMatrix is the world matrix of the particle system
  64064. * @param directionToUpdate is the direction vector to update with the result
  64065. * @param particle is the particle we are computed the direction for
  64066. */
  64067. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  64068. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  64069. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  64070. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  64071. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  64072. };
  64073. /**
  64074. * Clones the current emitter and returns a copy of it
  64075. * @returns the new emitter
  64076. */
  64077. SphereDirectedParticleEmitter.prototype.clone = function () {
  64078. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  64079. BABYLON.Tools.DeepCopy(this, newOne);
  64080. return newOne;
  64081. };
  64082. /**
  64083. * Called by the GPUParticleSystem to setup the update shader
  64084. * @param effect defines the update shader
  64085. */
  64086. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  64087. effect.setFloat("radius", this.radius);
  64088. effect.setFloat("radiusRange", this.radiusRange);
  64089. effect.setVector3("direction1", this.direction1);
  64090. effect.setVector3("direction2", this.direction2);
  64091. };
  64092. /**
  64093. * Returns a string to use to update the GPU particles update shader
  64094. * @returns a string containng the defines string
  64095. */
  64096. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  64097. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  64098. };
  64099. /**
  64100. * Returns the string "SphereDirectedParticleEmitter"
  64101. * @returns a string containing the class name
  64102. */
  64103. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  64104. return "SphereDirectedParticleEmitter";
  64105. };
  64106. /**
  64107. * Serializes the particle system to a JSON object.
  64108. * @returns the JSON object
  64109. */
  64110. SphereDirectedParticleEmitter.prototype.serialize = function () {
  64111. var serializationObject = _super.prototype.serialize.call(this);
  64112. serializationObject.direction1 = this.direction1.asArray();
  64113. serializationObject.direction2 = this.direction2.asArray();
  64114. return serializationObject;
  64115. };
  64116. /**
  64117. * Parse properties from a JSON object
  64118. * @param serializationObject defines the JSON object
  64119. */
  64120. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  64121. _super.prototype.parse.call(this, serializationObject);
  64122. this.direction1.copyFrom(serializationObject.direction1);
  64123. this.direction2.copyFrom(serializationObject.direction2);
  64124. };
  64125. return SphereDirectedParticleEmitter;
  64126. }(SphereParticleEmitter));
  64127. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  64128. })(BABYLON || (BABYLON = {}));
  64129. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  64130. var BABYLON;
  64131. (function (BABYLON) {
  64132. /**
  64133. * Particle emitter emitting particles from the inside of a hemisphere.
  64134. * It emits the particles alongside the hemisphere radius. The emission direction might be randomized.
  64135. */
  64136. var HemisphericParticleEmitter = /** @class */ (function () {
  64137. /**
  64138. * Creates a new instance HemisphericParticleEmitter
  64139. * @param radius the radius of the emission hemisphere (1 by default)
  64140. * @param radiusRange the range of the emission hemisphere [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  64141. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  64142. */
  64143. function HemisphericParticleEmitter(
  64144. /**
  64145. * The radius of the emission hemisphere.
  64146. */
  64147. radius,
  64148. /**
  64149. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  64150. */
  64151. radiusRange,
  64152. /**
  64153. * How much to randomize the particle direction [0-1].
  64154. */
  64155. directionRandomizer) {
  64156. if (radius === void 0) { radius = 1; }
  64157. if (radiusRange === void 0) { radiusRange = 1; }
  64158. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  64159. this.radius = radius;
  64160. this.radiusRange = radiusRange;
  64161. this.directionRandomizer = directionRandomizer;
  64162. }
  64163. /**
  64164. * Called by the particle System when the direction is computed for the created particle.
  64165. * @param worldMatrix is the world matrix of the particle system
  64166. * @param directionToUpdate is the direction vector to update with the result
  64167. * @param particle is the particle we are computed the direction for
  64168. */
  64169. HemisphericParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  64170. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  64171. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  64172. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  64173. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  64174. direction.x += randX;
  64175. direction.y += randY;
  64176. direction.z += randZ;
  64177. direction.normalize();
  64178. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  64179. };
  64180. /**
  64181. * Called by the particle System when the position is computed for the created particle.
  64182. * @param worldMatrix is the world matrix of the particle system
  64183. * @param positionToUpdate is the position vector to update with the result
  64184. * @param particle is the particle we are computed the position for
  64185. */
  64186. HemisphericParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  64187. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  64188. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  64189. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  64190. var theta = Math.acos(2 * v - 1);
  64191. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  64192. var randY = randRadius * Math.cos(theta);
  64193. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  64194. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, Math.abs(randY), randZ, worldMatrix, positionToUpdate);
  64195. };
  64196. /**
  64197. * Clones the current emitter and returns a copy of it
  64198. * @returns the new emitter
  64199. */
  64200. HemisphericParticleEmitter.prototype.clone = function () {
  64201. var newOne = new HemisphericParticleEmitter(this.radius, this.directionRandomizer);
  64202. BABYLON.Tools.DeepCopy(this, newOne);
  64203. return newOne;
  64204. };
  64205. /**
  64206. * Called by the GPUParticleSystem to setup the update shader
  64207. * @param effect defines the update shader
  64208. */
  64209. HemisphericParticleEmitter.prototype.applyToShader = function (effect) {
  64210. effect.setFloat("radius", this.radius);
  64211. effect.setFloat("radiusRange", this.radiusRange);
  64212. effect.setFloat("directionRandomizer", this.directionRandomizer);
  64213. };
  64214. /**
  64215. * Returns a string to use to update the GPU particles update shader
  64216. * @returns a string containng the defines string
  64217. */
  64218. HemisphericParticleEmitter.prototype.getEffectDefines = function () {
  64219. return "#define HEMISPHERICEMITTER";
  64220. };
  64221. /**
  64222. * Returns the string "HemisphericParticleEmitter"
  64223. * @returns a string containing the class name
  64224. */
  64225. HemisphericParticleEmitter.prototype.getClassName = function () {
  64226. return "HemisphericParticleEmitter";
  64227. };
  64228. /**
  64229. * Serializes the particle system to a JSON object.
  64230. * @returns the JSON object
  64231. */
  64232. HemisphericParticleEmitter.prototype.serialize = function () {
  64233. var serializationObject = {};
  64234. serializationObject.type = this.getClassName();
  64235. serializationObject.radius = this.radius;
  64236. serializationObject.radiusRange = this.radiusRange;
  64237. serializationObject.directionRandomizer = this.directionRandomizer;
  64238. return serializationObject;
  64239. };
  64240. /**
  64241. * Parse properties from a JSON object
  64242. * @param serializationObject defines the JSON object
  64243. */
  64244. HemisphericParticleEmitter.prototype.parse = function (serializationObject) {
  64245. this.radius = serializationObject.radius;
  64246. this.radiusRange = serializationObject.radiusRange;
  64247. this.directionRandomizer = serializationObject.directionRandomizer;
  64248. };
  64249. return HemisphericParticleEmitter;
  64250. }());
  64251. BABYLON.HemisphericParticleEmitter = HemisphericParticleEmitter;
  64252. })(BABYLON || (BABYLON = {}));
  64253. //# sourceMappingURL=babylon.hemisphericParticleEmitter.js.map
  64254. var BABYLON;
  64255. (function (BABYLON) {
  64256. /**
  64257. * Particle emitter emitting particles from a point.
  64258. * It emits the particles randomly between 2 given directions.
  64259. */
  64260. var PointParticleEmitter = /** @class */ (function () {
  64261. /**
  64262. * Creates a new instance PointParticleEmitter
  64263. */
  64264. function PointParticleEmitter() {
  64265. /**
  64266. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  64267. */
  64268. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  64269. /**
  64270. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  64271. */
  64272. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  64273. }
  64274. /**
  64275. * Called by the particle System when the direction is computed for the created particle.
  64276. * @param worldMatrix is the world matrix of the particle system
  64277. * @param directionToUpdate is the direction vector to update with the result
  64278. * @param particle is the particle we are computed the direction for
  64279. */
  64280. PointParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  64281. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  64282. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  64283. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  64284. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  64285. };
  64286. /**
  64287. * Called by the particle System when the position is computed for the created particle.
  64288. * @param worldMatrix is the world matrix of the particle system
  64289. * @param positionToUpdate is the position vector to update with the result
  64290. * @param particle is the particle we are computed the position for
  64291. */
  64292. PointParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  64293. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0, 0, 0, worldMatrix, positionToUpdate);
  64294. };
  64295. /**
  64296. * Clones the current emitter and returns a copy of it
  64297. * @returns the new emitter
  64298. */
  64299. PointParticleEmitter.prototype.clone = function () {
  64300. var newOne = new PointParticleEmitter();
  64301. BABYLON.Tools.DeepCopy(this, newOne);
  64302. return newOne;
  64303. };
  64304. /**
  64305. * Called by the GPUParticleSystem to setup the update shader
  64306. * @param effect defines the update shader
  64307. */
  64308. PointParticleEmitter.prototype.applyToShader = function (effect) {
  64309. effect.setVector3("direction1", this.direction1);
  64310. effect.setVector3("direction2", this.direction2);
  64311. };
  64312. /**
  64313. * Returns a string to use to update the GPU particles update shader
  64314. * @returns a string containng the defines string
  64315. */
  64316. PointParticleEmitter.prototype.getEffectDefines = function () {
  64317. return "#define POINTEMITTER";
  64318. };
  64319. /**
  64320. * Returns the string "PointParticleEmitter"
  64321. * @returns a string containing the class name
  64322. */
  64323. PointParticleEmitter.prototype.getClassName = function () {
  64324. return "PointParticleEmitter";
  64325. };
  64326. /**
  64327. * Serializes the particle system to a JSON object.
  64328. * @returns the JSON object
  64329. */
  64330. PointParticleEmitter.prototype.serialize = function () {
  64331. var serializationObject = {};
  64332. serializationObject.type = this.getClassName();
  64333. serializationObject.direction1 = this.direction1.asArray();
  64334. serializationObject.direction2 = this.direction2.asArray();
  64335. return serializationObject;
  64336. };
  64337. /**
  64338. * Parse properties from a JSON object
  64339. * @param serializationObject defines the JSON object
  64340. */
  64341. PointParticleEmitter.prototype.parse = function (serializationObject) {
  64342. BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
  64343. BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  64344. };
  64345. return PointParticleEmitter;
  64346. }());
  64347. BABYLON.PointParticleEmitter = PointParticleEmitter;
  64348. })(BABYLON || (BABYLON = {}));
  64349. //# sourceMappingURL=babylon.pointParticleEmitter.js.map
  64350. var BABYLON;
  64351. (function (BABYLON) {
  64352. // Adds the parsers to the scene parsers.
  64353. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedData, scene, container, rootUrl) {
  64354. var individualParser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);
  64355. if (!individualParser) {
  64356. return;
  64357. }
  64358. // Particles Systems
  64359. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  64360. for (var index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  64361. var parsedParticleSystem = parsedData.particleSystems[index];
  64362. container.particleSystems.push(individualParser(parsedParticleSystem, scene, rootUrl));
  64363. }
  64364. }
  64365. });
  64366. BABYLON.AbstractScene.AddIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedParticleSystem, scene, rootUrl) {
  64367. if (parsedParticleSystem.activeParticleCount) {
  64368. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  64369. return ps;
  64370. }
  64371. else {
  64372. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  64373. return ps;
  64374. }
  64375. });
  64376. BABYLON.Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  64377. if (uniformsNames === void 0) { uniformsNames = []; }
  64378. if (samplers === void 0) { samplers = []; }
  64379. if (defines === void 0) { defines = ""; }
  64380. var attributesNamesOrOptions = BABYLON.ParticleSystem._GetAttributeNamesOrOptions();
  64381. var effectCreationOption = BABYLON.ParticleSystem._GetEffectCreationOptions();
  64382. if (defines.indexOf(" BILLBOARD") === -1) {
  64383. defines += "\n#define BILLBOARD\n";
  64384. }
  64385. if (samplers.indexOf("diffuseSampler") === -1) {
  64386. samplers.push("diffuseSampler");
  64387. }
  64388. return this.createEffect({
  64389. vertex: "particles",
  64390. fragmentElement: fragmentName
  64391. }, attributesNamesOrOptions, effectCreationOption.concat(uniformsNames), samplers, defines, fallbacks, onCompiled, onError);
  64392. };
  64393. BABYLON.Mesh.prototype.getEmittedParticleSystems = function () {
  64394. var results = new Array();
  64395. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  64396. var particleSystem = this.getScene().particleSystems[index];
  64397. if (particleSystem.emitter === this) {
  64398. results.push(particleSystem);
  64399. }
  64400. }
  64401. return results;
  64402. };
  64403. BABYLON.Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  64404. var results = new Array();
  64405. var descendants = this.getDescendants();
  64406. descendants.push(this);
  64407. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  64408. var particleSystem = this.getScene().particleSystems[index];
  64409. var emitter = particleSystem.emitter;
  64410. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  64411. results.push(particleSystem);
  64412. }
  64413. }
  64414. return results;
  64415. };
  64416. })(BABYLON || (BABYLON = {}));
  64417. //# sourceMappingURL=babylon.particleSystemComponent.js.map
  64418. var BABYLON;
  64419. (function (BABYLON) {
  64420. /**
  64421. * Type of sub emitter
  64422. */
  64423. var SubEmitterType;
  64424. (function (SubEmitterType) {
  64425. /**
  64426. * Attached to the particle over it's lifetime
  64427. */
  64428. SubEmitterType[SubEmitterType["ATTACHED"] = 0] = "ATTACHED";
  64429. /**
  64430. * Created when the particle dies
  64431. */
  64432. SubEmitterType[SubEmitterType["END"] = 1] = "END";
  64433. })(SubEmitterType = BABYLON.SubEmitterType || (BABYLON.SubEmitterType = {}));
  64434. /**
  64435. * Sub emitter class used to emit particles from an existing particle
  64436. */
  64437. var SubEmitter = /** @class */ (function () {
  64438. /**
  64439. * Creates a sub emitter
  64440. * @param particleSystem the particle system to be used by the sub emitter
  64441. */
  64442. function SubEmitter(
  64443. /**
  64444. * the particle system to be used by the sub emitter
  64445. */
  64446. particleSystem) {
  64447. this.particleSystem = particleSystem;
  64448. /**
  64449. * Type of the submitter (Default: END)
  64450. */
  64451. this.type = SubEmitterType.END;
  64452. /**
  64453. * 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)
  64454. * Note: This only is supported when using an emitter of type Mesh
  64455. */
  64456. this.inheritDirection = false;
  64457. /**
  64458. * How much of the attached particles speed should be added to the sub emitted particle (default: 0)
  64459. */
  64460. this.inheritedVelocityAmount = 0;
  64461. // Create mesh as emitter to support rotation
  64462. if (!particleSystem.emitter || !particleSystem.emitter.dispose) {
  64463. particleSystem.emitter = new BABYLON.AbstractMesh("SubemitterSystemEmitter", particleSystem.getScene());
  64464. }
  64465. // Automatically dispose of subemitter when system is disposed
  64466. particleSystem.onDisposeObservable.add(function () {
  64467. if (particleSystem.emitter && particleSystem.emitter.dispose) {
  64468. particleSystem.emitter.dispose();
  64469. }
  64470. });
  64471. }
  64472. /**
  64473. * Clones the sub emitter
  64474. * @returns the cloned sub emitter
  64475. */
  64476. SubEmitter.prototype.clone = function () {
  64477. // Clone particle system
  64478. var emitter = this.particleSystem.emitter;
  64479. if (!emitter) {
  64480. emitter = new BABYLON.Vector3();
  64481. }
  64482. else if (emitter instanceof BABYLON.Vector3) {
  64483. emitter = emitter.clone();
  64484. }
  64485. else if (emitter instanceof BABYLON.AbstractMesh) {
  64486. emitter = new BABYLON.Mesh("", emitter.getScene());
  64487. emitter.isVisible = false;
  64488. }
  64489. var clone = new SubEmitter(this.particleSystem.clone("", emitter));
  64490. // Clone properties
  64491. clone.type = this.type;
  64492. clone.inheritDirection = this.inheritDirection;
  64493. clone.inheritedVelocityAmount = this.inheritedVelocityAmount;
  64494. clone.particleSystem._disposeEmitterOnDispose = true;
  64495. clone.particleSystem.disposeOnStop = true;
  64496. return clone;
  64497. };
  64498. /**
  64499. * Serialize current object to a JSON object
  64500. * @returns the serialized object
  64501. */
  64502. SubEmitter.prototype.serialize = function () {
  64503. var serializationObject = {};
  64504. serializationObject.type = this.type;
  64505. serializationObject.inheritDirection = this.inheritDirection;
  64506. serializationObject.inheritedVelocityAmount = this.inheritedVelocityAmount;
  64507. serializationObject.particleSystem = this.particleSystem.serialize();
  64508. return serializationObject;
  64509. };
  64510. /**
  64511. * Creates a new SubEmitter from a serialized JSON version
  64512. * @param serializationObject defines the JSON object to read from
  64513. * @param scene defines the hosting scene
  64514. * @param rootUrl defines the rootUrl for data loading
  64515. * @returns a new SubEmitter
  64516. */
  64517. SubEmitter.Parse = function (serializationObject, scene, rootUrl) {
  64518. var system = serializationObject.particleSystem;
  64519. var subEmitter = new SubEmitter(BABYLON.ParticleSystem.Parse(system, scene, rootUrl));
  64520. subEmitter.type = serializationObject.type;
  64521. subEmitter.inheritDirection = serializationObject.inheritDirection;
  64522. subEmitter.inheritedVelocityAmount = serializationObject.inheritedVelocityAmount;
  64523. subEmitter.particleSystem._isSubEmitter = true;
  64524. return subEmitter;
  64525. };
  64526. /** Release associated resources */
  64527. SubEmitter.prototype.dispose = function () {
  64528. this.particleSystem.dispose();
  64529. };
  64530. return SubEmitter;
  64531. }());
  64532. BABYLON.SubEmitter = SubEmitter;
  64533. })(BABYLON || (BABYLON = {}));
  64534. //# sourceMappingURL=babylon.subEmitter.js.map
  64535. var BABYLON;
  64536. (function (BABYLON) {
  64537. /**
  64538. * 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.
  64539. *
  64540. * This returned material effects how the mesh will look based on the code in the shaders.
  64541. *
  64542. * @see http://doc.babylonjs.com/how_to/shader_material
  64543. */
  64544. var ShaderMaterial = /** @class */ (function (_super) {
  64545. __extends(ShaderMaterial, _super);
  64546. /**
  64547. * Instantiate a new shader material.
  64548. * 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.
  64549. * This returned material effects how the mesh will look based on the code in the shaders.
  64550. * @see http://doc.babylonjs.com/how_to/shader_material
  64551. * @param name Define the name of the material in the scene
  64552. * @param scene Define the scene the material belongs to
  64553. * @param shaderPath Defines the route to the shader code in one of three ways:
  64554. * - object - { vertex: "custom", fragment: "custom" }, used with BABYLON.Effect.ShadersStore["customVertexShader"] and BABYLON.Effect.ShadersStore["customFragmentShader"]
  64555. * - object - { vertexElement: "vertexShaderCode", fragmentElement: "fragmentShaderCode" }, used with shader code in <script> tags
  64556. * - string - "./COMMON_NAME", used with external files COMMON_NAME.vertex.fx and COMMON_NAME.fragment.fx in index.html folder.
  64557. * @param options Define the options used to create the shader
  64558. */
  64559. function ShaderMaterial(name, scene, shaderPath, options) {
  64560. if (options === void 0) { options = {}; }
  64561. var _this = _super.call(this, name, scene) || this;
  64562. _this._textures = {};
  64563. _this._textureArrays = {};
  64564. _this._floats = {};
  64565. _this._ints = {};
  64566. _this._floatsArrays = {};
  64567. _this._colors3 = {};
  64568. _this._colors3Arrays = {};
  64569. _this._colors4 = {};
  64570. _this._vectors2 = {};
  64571. _this._vectors3 = {};
  64572. _this._vectors4 = {};
  64573. _this._matrices = {};
  64574. _this._matrices3x3 = {};
  64575. _this._matrices2x2 = {};
  64576. _this._vectors2Arrays = {};
  64577. _this._vectors3Arrays = {};
  64578. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  64579. _this._shaderPath = shaderPath;
  64580. _this._options = __assign({ needAlphaBlending: false, needAlphaTesting: false, attributes: ["position", "normal", "uv"], uniforms: ["worldViewProjection"], uniformBuffers: [], samplers: [], defines: [] }, options);
  64581. return _this;
  64582. }
  64583. /**
  64584. * Gets the current class name of the material e.g. "ShaderMaterial"
  64585. * Mainly use in serialization.
  64586. * @returns the class name
  64587. */
  64588. ShaderMaterial.prototype.getClassName = function () {
  64589. return "ShaderMaterial";
  64590. };
  64591. /**
  64592. * Specifies if the material will require alpha blending
  64593. * @returns a boolean specifying if alpha blending is needed
  64594. */
  64595. ShaderMaterial.prototype.needAlphaBlending = function () {
  64596. return (this.alpha < 1.0) || this._options.needAlphaBlending;
  64597. };
  64598. /**
  64599. * Specifies if this material should be rendered in alpha test mode
  64600. * @returns a boolean specifying if an alpha test is needed.
  64601. */
  64602. ShaderMaterial.prototype.needAlphaTesting = function () {
  64603. return this._options.needAlphaTesting;
  64604. };
  64605. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  64606. if (this._options.uniforms.indexOf(uniformName) === -1) {
  64607. this._options.uniforms.push(uniformName);
  64608. }
  64609. };
  64610. /**
  64611. * Set a texture in the shader.
  64612. * @param name Define the name of the uniform samplers as defined in the shader
  64613. * @param texture Define the texture to bind to this sampler
  64614. * @return the material itself allowing "fluent" like uniform updates
  64615. */
  64616. ShaderMaterial.prototype.setTexture = function (name, texture) {
  64617. if (this._options.samplers.indexOf(name) === -1) {
  64618. this._options.samplers.push(name);
  64619. }
  64620. this._textures[name] = texture;
  64621. return this;
  64622. };
  64623. /**
  64624. * Set a texture array in the shader.
  64625. * @param name Define the name of the uniform sampler array as defined in the shader
  64626. * @param textures Define the list of textures to bind to this sampler
  64627. * @return the material itself allowing "fluent" like uniform updates
  64628. */
  64629. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  64630. if (this._options.samplers.indexOf(name) === -1) {
  64631. this._options.samplers.push(name);
  64632. }
  64633. this._checkUniform(name);
  64634. this._textureArrays[name] = textures;
  64635. return this;
  64636. };
  64637. /**
  64638. * Set a float in the shader.
  64639. * @param name Define the name of the uniform as defined in the shader
  64640. * @param value Define the value to give to the uniform
  64641. * @return the material itself allowing "fluent" like uniform updates
  64642. */
  64643. ShaderMaterial.prototype.setFloat = function (name, value) {
  64644. this._checkUniform(name);
  64645. this._floats[name] = value;
  64646. return this;
  64647. };
  64648. /**
  64649. * Set a int in the shader.
  64650. * @param name Define the name of the uniform as defined in the shader
  64651. * @param value Define the value to give to the uniform
  64652. * @return the material itself allowing "fluent" like uniform updates
  64653. */
  64654. ShaderMaterial.prototype.setInt = function (name, value) {
  64655. this._checkUniform(name);
  64656. this._ints[name] = value;
  64657. return this;
  64658. };
  64659. /**
  64660. * Set an array of floats in the shader.
  64661. * @param name Define the name of the uniform as defined in the shader
  64662. * @param value Define the value to give to the uniform
  64663. * @return the material itself allowing "fluent" like uniform updates
  64664. */
  64665. ShaderMaterial.prototype.setFloats = function (name, value) {
  64666. this._checkUniform(name);
  64667. this._floatsArrays[name] = value;
  64668. return this;
  64669. };
  64670. /**
  64671. * Set a vec3 in the shader from a Color3.
  64672. * @param name Define the name of the uniform as defined in the shader
  64673. * @param value Define the value to give to the uniform
  64674. * @return the material itself allowing "fluent" like uniform updates
  64675. */
  64676. ShaderMaterial.prototype.setColor3 = function (name, value) {
  64677. this._checkUniform(name);
  64678. this._colors3[name] = value;
  64679. return this;
  64680. };
  64681. /**
  64682. * Set a vec3 array in the shader from a Color3 array.
  64683. * @param name Define the name of the uniform as defined in the shader
  64684. * @param value Define the value to give to the uniform
  64685. * @return the material itself allowing "fluent" like uniform updates
  64686. */
  64687. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  64688. this._checkUniform(name);
  64689. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  64690. color.toArray(arr, arr.length);
  64691. return arr;
  64692. }, []);
  64693. return this;
  64694. };
  64695. /**
  64696. * Set a vec4 in the shader from a Color4.
  64697. * @param name Define the name of the uniform as defined in the shader
  64698. * @param value Define the value to give to the uniform
  64699. * @return the material itself allowing "fluent" like uniform updates
  64700. */
  64701. ShaderMaterial.prototype.setColor4 = function (name, value) {
  64702. this._checkUniform(name);
  64703. this._colors4[name] = value;
  64704. return this;
  64705. };
  64706. /**
  64707. * Set a vec2 in the shader from a Vector2.
  64708. * @param name Define the name of the uniform as defined in the shader
  64709. * @param value Define the value to give to the uniform
  64710. * @return the material itself allowing "fluent" like uniform updates
  64711. */
  64712. ShaderMaterial.prototype.setVector2 = function (name, value) {
  64713. this._checkUniform(name);
  64714. this._vectors2[name] = value;
  64715. return this;
  64716. };
  64717. /**
  64718. * Set a vec3 in the shader from a Vector3.
  64719. * @param name Define the name of the uniform as defined in the shader
  64720. * @param value Define the value to give to the uniform
  64721. * @return the material itself allowing "fluent" like uniform updates
  64722. */
  64723. ShaderMaterial.prototype.setVector3 = function (name, value) {
  64724. this._checkUniform(name);
  64725. this._vectors3[name] = value;
  64726. return this;
  64727. };
  64728. /**
  64729. * Set a vec4 in the shader from a Vector4.
  64730. * @param name Define the name of the uniform as defined in the shader
  64731. * @param value Define the value to give to the uniform
  64732. * @return the material itself allowing "fluent" like uniform updates
  64733. */
  64734. ShaderMaterial.prototype.setVector4 = function (name, value) {
  64735. this._checkUniform(name);
  64736. this._vectors4[name] = value;
  64737. return this;
  64738. };
  64739. /**
  64740. * Set a mat4 in the shader from a Matrix.
  64741. * @param name Define the name of the uniform as defined in the shader
  64742. * @param value Define the value to give to the uniform
  64743. * @return the material itself allowing "fluent" like uniform updates
  64744. */
  64745. ShaderMaterial.prototype.setMatrix = function (name, value) {
  64746. this._checkUniform(name);
  64747. this._matrices[name] = value;
  64748. return this;
  64749. };
  64750. /**
  64751. * Set a mat3 in the shader from a Float32Array.
  64752. * @param name Define the name of the uniform as defined in the shader
  64753. * @param value Define the value to give to the uniform
  64754. * @return the material itself allowing "fluent" like uniform updates
  64755. */
  64756. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  64757. this._checkUniform(name);
  64758. this._matrices3x3[name] = value;
  64759. return this;
  64760. };
  64761. /**
  64762. * Set a mat2 in the shader from a Float32Array.
  64763. * @param name Define the name of the uniform as defined in the shader
  64764. * @param value Define the value to give to the uniform
  64765. * @return the material itself allowing "fluent" like uniform updates
  64766. */
  64767. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  64768. this._checkUniform(name);
  64769. this._matrices2x2[name] = value;
  64770. return this;
  64771. };
  64772. /**
  64773. * Set a vec2 array in the shader from a number array.
  64774. * @param name Define the name of the uniform as defined in the shader
  64775. * @param value Define the value to give to the uniform
  64776. * @return the material itself allowing "fluent" like uniform updates
  64777. */
  64778. ShaderMaterial.prototype.setArray2 = function (name, value) {
  64779. this._checkUniform(name);
  64780. this._vectors2Arrays[name] = value;
  64781. return this;
  64782. };
  64783. /**
  64784. * Set a vec3 array in the shader from a number array.
  64785. * @param name Define the name of the uniform as defined in the shader
  64786. * @param value Define the value to give to the uniform
  64787. * @return the material itself allowing "fluent" like uniform updates
  64788. */
  64789. ShaderMaterial.prototype.setArray3 = function (name, value) {
  64790. this._checkUniform(name);
  64791. this._vectors3Arrays[name] = value;
  64792. return this;
  64793. };
  64794. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  64795. if (!mesh) {
  64796. return true;
  64797. }
  64798. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  64799. return false;
  64800. }
  64801. return false;
  64802. };
  64803. /**
  64804. * Checks if the material is ready to render the requested mesh
  64805. * @param mesh Define the mesh to render
  64806. * @param useInstances Define whether or not the material is used with instances
  64807. * @returns true if ready, otherwise false
  64808. */
  64809. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  64810. var scene = this.getScene();
  64811. var engine = scene.getEngine();
  64812. if (!this.checkReadyOnEveryCall) {
  64813. if (this._renderId === scene.getRenderId()) {
  64814. if (this._checkCache(scene, mesh, useInstances)) {
  64815. return true;
  64816. }
  64817. }
  64818. }
  64819. // Instances
  64820. var defines = [];
  64821. var attribs = [];
  64822. var fallbacks = new BABYLON.EffectFallbacks();
  64823. for (var index = 0; index < this._options.defines.length; index++) {
  64824. defines.push(this._options.defines[index]);
  64825. }
  64826. for (var index = 0; index < this._options.attributes.length; index++) {
  64827. attribs.push(this._options.attributes[index]);
  64828. }
  64829. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  64830. attribs.push(BABYLON.VertexBuffer.ColorKind);
  64831. defines.push("#define VERTEXCOLOR");
  64832. }
  64833. if (useInstances) {
  64834. defines.push("#define INSTANCES");
  64835. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  64836. }
  64837. // Bones
  64838. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  64839. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  64840. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  64841. if (mesh.numBoneInfluencers > 4) {
  64842. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  64843. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  64844. }
  64845. var skeleton = mesh.skeleton;
  64846. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  64847. fallbacks.addCPUSkinningFallback(0, mesh);
  64848. if (skeleton.isUsingTextureForMatrices) {
  64849. defines.push("#define BONETEXTURE");
  64850. if (this._options.uniforms.indexOf("boneTextureWidth") === -1) {
  64851. this._options.uniforms.push("boneTextureWidth");
  64852. }
  64853. if (this._options.samplers.indexOf("boneSampler") === -1) {
  64854. this._options.samplers.push("boneSampler");
  64855. }
  64856. }
  64857. else {
  64858. defines.push("#define BonesPerMesh " + (skeleton.bones.length + 1));
  64859. if (this._options.uniforms.indexOf("mBones") === -1) {
  64860. this._options.uniforms.push("mBones");
  64861. }
  64862. }
  64863. }
  64864. else {
  64865. defines.push("#define NUM_BONE_INFLUENCERS 0");
  64866. }
  64867. // Textures
  64868. for (var name in this._textures) {
  64869. if (!this._textures[name].isReady()) {
  64870. return false;
  64871. }
  64872. }
  64873. // Alpha test
  64874. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  64875. defines.push("#define ALPHATEST");
  64876. }
  64877. var previousEffect = this._effect;
  64878. var join = defines.join("\n");
  64879. this._effect = engine.createEffect(this._shaderPath, {
  64880. attributes: attribs,
  64881. uniformsNames: this._options.uniforms,
  64882. uniformBuffersNames: this._options.uniformBuffers,
  64883. samplers: this._options.samplers,
  64884. defines: join,
  64885. fallbacks: fallbacks,
  64886. onCompiled: this.onCompiled,
  64887. onError: this.onError
  64888. }, engine);
  64889. if (!this._effect.isReady()) {
  64890. return false;
  64891. }
  64892. if (previousEffect !== this._effect) {
  64893. scene.resetCachedMaterial();
  64894. }
  64895. this._renderId = scene.getRenderId();
  64896. return true;
  64897. };
  64898. /**
  64899. * Binds the world matrix to the material
  64900. * @param world defines the world transformation matrix
  64901. */
  64902. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  64903. var scene = this.getScene();
  64904. if (!this._effect) {
  64905. return;
  64906. }
  64907. if (this._options.uniforms.indexOf("world") !== -1) {
  64908. this._effect.setMatrix("world", world);
  64909. }
  64910. if (this._options.uniforms.indexOf("worldView") !== -1) {
  64911. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  64912. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  64913. }
  64914. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  64915. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  64916. }
  64917. };
  64918. /**
  64919. * Binds the material to the mesh
  64920. * @param world defines the world transformation matrix
  64921. * @param mesh defines the mesh to bind the material to
  64922. */
  64923. ShaderMaterial.prototype.bind = function (world, mesh) {
  64924. // Std values
  64925. this.bindOnlyWorldMatrix(world);
  64926. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  64927. if (this._options.uniforms.indexOf("view") !== -1) {
  64928. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  64929. }
  64930. if (this._options.uniforms.indexOf("projection") !== -1) {
  64931. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  64932. }
  64933. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  64934. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  64935. }
  64936. // Bones
  64937. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  64938. var name;
  64939. // Texture
  64940. for (name in this._textures) {
  64941. this._effect.setTexture(name, this._textures[name]);
  64942. }
  64943. // Texture arrays
  64944. for (name in this._textureArrays) {
  64945. this._effect.setTextureArray(name, this._textureArrays[name]);
  64946. }
  64947. // Int
  64948. for (name in this._ints) {
  64949. this._effect.setInt(name, this._ints[name]);
  64950. }
  64951. // Float
  64952. for (name in this._floats) {
  64953. this._effect.setFloat(name, this._floats[name]);
  64954. }
  64955. // Floats
  64956. for (name in this._floatsArrays) {
  64957. this._effect.setArray(name, this._floatsArrays[name]);
  64958. }
  64959. // Color3
  64960. for (name in this._colors3) {
  64961. this._effect.setColor3(name, this._colors3[name]);
  64962. }
  64963. for (name in this._colors3Arrays) {
  64964. this._effect.setArray3(name, this._colors3Arrays[name]);
  64965. }
  64966. // Color4
  64967. for (name in this._colors4) {
  64968. var color = this._colors4[name];
  64969. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  64970. }
  64971. // Vector2
  64972. for (name in this._vectors2) {
  64973. this._effect.setVector2(name, this._vectors2[name]);
  64974. }
  64975. // Vector3
  64976. for (name in this._vectors3) {
  64977. this._effect.setVector3(name, this._vectors3[name]);
  64978. }
  64979. // Vector4
  64980. for (name in this._vectors4) {
  64981. this._effect.setVector4(name, this._vectors4[name]);
  64982. }
  64983. // Matrix
  64984. for (name in this._matrices) {
  64985. this._effect.setMatrix(name, this._matrices[name]);
  64986. }
  64987. // Matrix 3x3
  64988. for (name in this._matrices3x3) {
  64989. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  64990. }
  64991. // Matrix 2x2
  64992. for (name in this._matrices2x2) {
  64993. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  64994. }
  64995. // Vector2Array
  64996. for (name in this._vectors2Arrays) {
  64997. this._effect.setArray2(name, this._vectors2Arrays[name]);
  64998. }
  64999. // Vector3Array
  65000. for (name in this._vectors3Arrays) {
  65001. this._effect.setArray3(name, this._vectors3Arrays[name]);
  65002. }
  65003. }
  65004. this._afterBind(mesh);
  65005. };
  65006. /**
  65007. * Gets the active textures from the material
  65008. * @returns an array of textures
  65009. */
  65010. ShaderMaterial.prototype.getActiveTextures = function () {
  65011. var activeTextures = _super.prototype.getActiveTextures.call(this);
  65012. for (var name in this._textures) {
  65013. activeTextures.push(this._textures[name]);
  65014. }
  65015. for (var name in this._textureArrays) {
  65016. var array = this._textureArrays[name];
  65017. for (var index = 0; index < array.length; index++) {
  65018. activeTextures.push(array[index]);
  65019. }
  65020. }
  65021. return activeTextures;
  65022. };
  65023. /**
  65024. * Specifies if the material uses a texture
  65025. * @param texture defines the texture to check against the material
  65026. * @returns a boolean specifying if the material uses the texture
  65027. */
  65028. ShaderMaterial.prototype.hasTexture = function (texture) {
  65029. if (_super.prototype.hasTexture.call(this, texture)) {
  65030. return true;
  65031. }
  65032. for (var name in this._textures) {
  65033. if (this._textures[name] === texture) {
  65034. return true;
  65035. }
  65036. }
  65037. for (var name in this._textureArrays) {
  65038. var array = this._textureArrays[name];
  65039. for (var index = 0; index < array.length; index++) {
  65040. if (array[index] === texture) {
  65041. return true;
  65042. }
  65043. }
  65044. }
  65045. return false;
  65046. };
  65047. /**
  65048. * Makes a duplicate of the material, and gives it a new name
  65049. * @param name defines the new name for the duplicated material
  65050. * @returns the cloned material
  65051. */
  65052. ShaderMaterial.prototype.clone = function (name) {
  65053. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  65054. return newShaderMaterial;
  65055. };
  65056. /**
  65057. * Disposes the material
  65058. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  65059. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  65060. * @param notBoundToMesh specifies if the material that is being disposed is known to be not bound to any mesh
  65061. */
  65062. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures, notBoundToMesh) {
  65063. if (forceDisposeTextures) {
  65064. var name;
  65065. for (name in this._textures) {
  65066. this._textures[name].dispose();
  65067. }
  65068. for (name in this._textureArrays) {
  65069. var array = this._textureArrays[name];
  65070. for (var index = 0; index < array.length; index++) {
  65071. array[index].dispose();
  65072. }
  65073. }
  65074. }
  65075. this._textures = {};
  65076. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures, notBoundToMesh);
  65077. };
  65078. /**
  65079. * Serializes this material in a JSON representation
  65080. * @returns the serialized material object
  65081. */
  65082. ShaderMaterial.prototype.serialize = function () {
  65083. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  65084. serializationObject.customType = "BABYLON.ShaderMaterial";
  65085. serializationObject.options = this._options;
  65086. serializationObject.shaderPath = this._shaderPath;
  65087. var name;
  65088. // Texture
  65089. serializationObject.textures = {};
  65090. for (name in this._textures) {
  65091. serializationObject.textures[name] = this._textures[name].serialize();
  65092. }
  65093. // Texture arrays
  65094. serializationObject.textureArrays = {};
  65095. for (name in this._textureArrays) {
  65096. serializationObject.textureArrays[name] = [];
  65097. var array = this._textureArrays[name];
  65098. for (var index = 0; index < array.length; index++) {
  65099. serializationObject.textureArrays[name].push(array[index].serialize());
  65100. }
  65101. }
  65102. // Float
  65103. serializationObject.floats = {};
  65104. for (name in this._floats) {
  65105. serializationObject.floats[name] = this._floats[name];
  65106. }
  65107. // Float s
  65108. serializationObject.FloatArrays = {};
  65109. for (name in this._floatsArrays) {
  65110. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  65111. }
  65112. // Color3
  65113. serializationObject.colors3 = {};
  65114. for (name in this._colors3) {
  65115. serializationObject.colors3[name] = this._colors3[name].asArray();
  65116. }
  65117. // Color3 array
  65118. serializationObject.colors3Arrays = {};
  65119. for (name in this._colors3Arrays) {
  65120. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  65121. }
  65122. // Color4
  65123. serializationObject.colors4 = {};
  65124. for (name in this._colors4) {
  65125. serializationObject.colors4[name] = this._colors4[name].asArray();
  65126. }
  65127. // Vector2
  65128. serializationObject.vectors2 = {};
  65129. for (name in this._vectors2) {
  65130. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  65131. }
  65132. // Vector3
  65133. serializationObject.vectors3 = {};
  65134. for (name in this._vectors3) {
  65135. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  65136. }
  65137. // Vector4
  65138. serializationObject.vectors4 = {};
  65139. for (name in this._vectors4) {
  65140. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  65141. }
  65142. // Matrix
  65143. serializationObject.matrices = {};
  65144. for (name in this._matrices) {
  65145. serializationObject.matrices[name] = this._matrices[name].asArray();
  65146. }
  65147. // Matrix 3x3
  65148. serializationObject.matrices3x3 = {};
  65149. for (name in this._matrices3x3) {
  65150. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  65151. }
  65152. // Matrix 2x2
  65153. serializationObject.matrices2x2 = {};
  65154. for (name in this._matrices2x2) {
  65155. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  65156. }
  65157. // Vector2Array
  65158. serializationObject.vectors2Arrays = {};
  65159. for (name in this._vectors2Arrays) {
  65160. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  65161. }
  65162. // Vector3Array
  65163. serializationObject.vectors3Arrays = {};
  65164. for (name in this._vectors3Arrays) {
  65165. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  65166. }
  65167. return serializationObject;
  65168. };
  65169. /**
  65170. * Creates a shader material from parsed shader material data
  65171. * @param source defines the JSON represnetation of the material
  65172. * @param scene defines the hosting scene
  65173. * @param rootUrl defines the root URL to use to load textures and relative dependencies
  65174. * @returns a new material
  65175. */
  65176. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  65177. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  65178. var name;
  65179. // Texture
  65180. for (name in source.textures) {
  65181. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  65182. }
  65183. // Texture arrays
  65184. for (name in source.textureArrays) {
  65185. var array = source.textureArrays[name];
  65186. var textureArray = new Array();
  65187. for (var index = 0; index < array.length; index++) {
  65188. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  65189. }
  65190. material.setTextureArray(name, textureArray);
  65191. }
  65192. // Float
  65193. for (name in source.floats) {
  65194. material.setFloat(name, source.floats[name]);
  65195. }
  65196. // Float s
  65197. for (name in source.floatsArrays) {
  65198. material.setFloats(name, source.floatsArrays[name]);
  65199. }
  65200. // Color3
  65201. for (name in source.colors3) {
  65202. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  65203. }
  65204. // Color3 arrays
  65205. for (name in source.colors3Arrays) {
  65206. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  65207. if (i % 3 === 0) {
  65208. arr.push([num]);
  65209. }
  65210. else {
  65211. arr[arr.length - 1].push(num);
  65212. }
  65213. return arr;
  65214. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  65215. material.setColor3Array(name, colors);
  65216. }
  65217. // Color4
  65218. for (name in source.colors4) {
  65219. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  65220. }
  65221. // Vector2
  65222. for (name in source.vectors2) {
  65223. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  65224. }
  65225. // Vector3
  65226. for (name in source.vectors3) {
  65227. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  65228. }
  65229. // Vector4
  65230. for (name in source.vectors4) {
  65231. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  65232. }
  65233. // Matrix
  65234. for (name in source.matrices) {
  65235. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  65236. }
  65237. // Matrix 3x3
  65238. for (name in source.matrices3x3) {
  65239. material.setMatrix3x3(name, source.matrices3x3[name]);
  65240. }
  65241. // Matrix 2x2
  65242. for (name in source.matrices2x2) {
  65243. material.setMatrix2x2(name, source.matrices2x2[name]);
  65244. }
  65245. // Vector2Array
  65246. for (name in source.vectors2Arrays) {
  65247. material.setArray2(name, source.vectors2Arrays[name]);
  65248. }
  65249. // Vector3Array
  65250. for (name in source.vectors3Arrays) {
  65251. material.setArray3(name, source.vectors3Arrays[name]);
  65252. }
  65253. return material;
  65254. };
  65255. return ShaderMaterial;
  65256. }(BABYLON.Material));
  65257. BABYLON.ShaderMaterial = ShaderMaterial;
  65258. })(BABYLON || (BABYLON = {}));
  65259. //# sourceMappingURL=babylon.shaderMaterial.js.map
  65260. var BABYLON;
  65261. (function (BABYLON) {
  65262. /**
  65263. * Mesh representing the gorund
  65264. */
  65265. var GroundMesh = /** @class */ (function (_super) {
  65266. __extends(GroundMesh, _super);
  65267. function GroundMesh(name, scene) {
  65268. var _this = _super.call(this, name, scene) || this;
  65269. /** If octree should be generated */
  65270. _this.generateOctree = false;
  65271. return _this;
  65272. }
  65273. /**
  65274. * "GroundMesh"
  65275. * @returns "GroundMesh"
  65276. */
  65277. GroundMesh.prototype.getClassName = function () {
  65278. return "GroundMesh";
  65279. };
  65280. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  65281. /**
  65282. * The minimum of x and y subdivisions
  65283. */
  65284. get: function () {
  65285. return Math.min(this._subdivisionsX, this._subdivisionsY);
  65286. },
  65287. enumerable: true,
  65288. configurable: true
  65289. });
  65290. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  65291. /**
  65292. * X subdivisions
  65293. */
  65294. get: function () {
  65295. return this._subdivisionsX;
  65296. },
  65297. enumerable: true,
  65298. configurable: true
  65299. });
  65300. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  65301. /**
  65302. * Y subdivisions
  65303. */
  65304. get: function () {
  65305. return this._subdivisionsY;
  65306. },
  65307. enumerable: true,
  65308. configurable: true
  65309. });
  65310. /**
  65311. * This function will update an octree to help to select the right submeshes for rendering, picking and collision computations.
  65312. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  65313. * @param chunksCount the number of subdivisions for x and y
  65314. * @param octreeBlocksSize (Default: 32)
  65315. */
  65316. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  65317. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  65318. this._subdivisionsX = chunksCount;
  65319. this._subdivisionsY = chunksCount;
  65320. this.subdivide(chunksCount);
  65321. // Call the octree system optimization if it is defined.
  65322. var thisAsAny = this;
  65323. if (thisAsAny.createOrUpdateSubmeshesOctree) {
  65324. thisAsAny.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  65325. }
  65326. };
  65327. /**
  65328. * Returns a height (y) value in the Worl system :
  65329. * the ground altitude at the coordinates (x, z) expressed in the World system.
  65330. * @param x x coordinate
  65331. * @param z z coordinate
  65332. * @returns the ground y position if (x, z) are outside the ground surface.
  65333. */
  65334. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  65335. var world = this.getWorldMatrix();
  65336. var invMat = BABYLON.Tmp.Matrix[5];
  65337. world.invertToRef(invMat);
  65338. var tmpVect = BABYLON.Tmp.Vector3[8];
  65339. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  65340. x = tmpVect.x;
  65341. z = tmpVect.z;
  65342. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  65343. return this.position.y;
  65344. }
  65345. if (!this._heightQuads || this._heightQuads.length == 0) {
  65346. this._initHeightQuads();
  65347. this._computeHeightQuads();
  65348. }
  65349. var facet = this._getFacetAt(x, z);
  65350. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  65351. // return y in the World system
  65352. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  65353. return tmpVect.y;
  65354. };
  65355. /**
  65356. * Returns a normalized vector (Vector3) orthogonal to the ground
  65357. * at the ground coordinates (x, z) expressed in the World system.
  65358. * @param x x coordinate
  65359. * @param z z coordinate
  65360. * @returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  65361. */
  65362. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  65363. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  65364. this.getNormalAtCoordinatesToRef(x, z, normal);
  65365. return normal;
  65366. };
  65367. /**
  65368. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  65369. * at the ground coordinates (x, z) expressed in the World system.
  65370. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  65371. * @param x x coordinate
  65372. * @param z z coordinate
  65373. * @param ref vector to store the result
  65374. * @returns the GroundMesh.
  65375. */
  65376. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  65377. var world = this.getWorldMatrix();
  65378. var tmpMat = BABYLON.Tmp.Matrix[5];
  65379. world.invertToRef(tmpMat);
  65380. var tmpVect = BABYLON.Tmp.Vector3[8];
  65381. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  65382. x = tmpVect.x;
  65383. z = tmpVect.z;
  65384. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  65385. return this;
  65386. }
  65387. if (!this._heightQuads || this._heightQuads.length == 0) {
  65388. this._initHeightQuads();
  65389. this._computeHeightQuads();
  65390. }
  65391. var facet = this._getFacetAt(x, z);
  65392. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  65393. return this;
  65394. };
  65395. /**
  65396. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  65397. * if the ground has been updated.
  65398. * This can be used in the render loop.
  65399. * @returns the GroundMesh.
  65400. */
  65401. GroundMesh.prototype.updateCoordinateHeights = function () {
  65402. if (!this._heightQuads || this._heightQuads.length == 0) {
  65403. this._initHeightQuads();
  65404. }
  65405. this._computeHeightQuads();
  65406. return this;
  65407. };
  65408. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  65409. GroundMesh.prototype._getFacetAt = function (x, z) {
  65410. // retrieve col and row from x, z coordinates in the ground local system
  65411. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  65412. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  65413. var quad = this._heightQuads[row * this._subdivisionsX + col];
  65414. var facet;
  65415. if (z < quad.slope.x * x + quad.slope.y) {
  65416. facet = quad.facet1;
  65417. }
  65418. else {
  65419. facet = quad.facet2;
  65420. }
  65421. return facet;
  65422. };
  65423. // Creates and populates the heightMap array with "facet" elements :
  65424. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  65425. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  65426. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  65427. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  65428. // Returns the GroundMesh.
  65429. GroundMesh.prototype._initHeightQuads = function () {
  65430. var subdivisionsX = this._subdivisionsX;
  65431. var subdivisionsY = this._subdivisionsY;
  65432. this._heightQuads = new Array();
  65433. for (var row = 0; row < subdivisionsY; row++) {
  65434. for (var col = 0; col < subdivisionsX; col++) {
  65435. 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) };
  65436. this._heightQuads[row * subdivisionsX + col] = quad;
  65437. }
  65438. }
  65439. return this;
  65440. };
  65441. // Compute each quad element values and update the the heightMap array :
  65442. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  65443. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  65444. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  65445. // Returns the GroundMesh.
  65446. GroundMesh.prototype._computeHeightQuads = function () {
  65447. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  65448. if (!positions) {
  65449. return this;
  65450. }
  65451. var v1 = BABYLON.Tmp.Vector3[3];
  65452. var v2 = BABYLON.Tmp.Vector3[2];
  65453. var v3 = BABYLON.Tmp.Vector3[1];
  65454. var v4 = BABYLON.Tmp.Vector3[0];
  65455. var v1v2 = BABYLON.Tmp.Vector3[4];
  65456. var v1v3 = BABYLON.Tmp.Vector3[5];
  65457. var v1v4 = BABYLON.Tmp.Vector3[6];
  65458. var norm1 = BABYLON.Tmp.Vector3[7];
  65459. var norm2 = BABYLON.Tmp.Vector3[8];
  65460. var i = 0;
  65461. var j = 0;
  65462. var k = 0;
  65463. var cd = 0; // 2D slope coefficient : z = cd * x + h
  65464. var h = 0;
  65465. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  65466. var d2 = 0;
  65467. var subdivisionsX = this._subdivisionsX;
  65468. var subdivisionsY = this._subdivisionsY;
  65469. for (var row = 0; row < subdivisionsY; row++) {
  65470. for (var col = 0; col < subdivisionsX; col++) {
  65471. i = col * 3;
  65472. j = row * (subdivisionsX + 1) * 3;
  65473. k = (row + 1) * (subdivisionsX + 1) * 3;
  65474. v1.x = positions[j + i];
  65475. v1.y = positions[j + i + 1];
  65476. v1.z = positions[j + i + 2];
  65477. v2.x = positions[j + i + 3];
  65478. v2.y = positions[j + i + 4];
  65479. v2.z = positions[j + i + 5];
  65480. v3.x = positions[k + i];
  65481. v3.y = positions[k + i + 1];
  65482. v3.z = positions[k + i + 2];
  65483. v4.x = positions[k + i + 3];
  65484. v4.y = positions[k + i + 4];
  65485. v4.z = positions[k + i + 5];
  65486. // 2D slope V1V4
  65487. cd = (v4.z - v1.z) / (v4.x - v1.x);
  65488. h = v1.z - cd * v1.x; // v1 belongs to the slope
  65489. // facet equations :
  65490. // we compute each facet normal vector
  65491. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  65492. // we compute the value d by applying the equation to v1 which belongs to the plane
  65493. // then we store the facet equation in a Vector4
  65494. v2.subtractToRef(v1, v1v2);
  65495. v3.subtractToRef(v1, v1v3);
  65496. v4.subtractToRef(v1, v1v4);
  65497. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  65498. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  65499. norm1.normalize();
  65500. norm2.normalize();
  65501. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  65502. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  65503. var quad = this._heightQuads[row * subdivisionsX + col];
  65504. quad.slope.copyFromFloats(cd, h);
  65505. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  65506. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  65507. }
  65508. }
  65509. return this;
  65510. };
  65511. /**
  65512. * Serializes this ground mesh
  65513. * @param serializationObject object to write serialization to
  65514. */
  65515. GroundMesh.prototype.serialize = function (serializationObject) {
  65516. _super.prototype.serialize.call(this, serializationObject);
  65517. serializationObject.subdivisionsX = this._subdivisionsX;
  65518. serializationObject.subdivisionsY = this._subdivisionsY;
  65519. serializationObject.minX = this._minX;
  65520. serializationObject.maxX = this._maxX;
  65521. serializationObject.minZ = this._minZ;
  65522. serializationObject.maxZ = this._maxZ;
  65523. serializationObject.width = this._width;
  65524. serializationObject.height = this._height;
  65525. };
  65526. /**
  65527. * Parses a serialized ground mesh
  65528. * @param parsedMesh the serialized mesh
  65529. * @param scene the scene to create the ground mesh in
  65530. * @returns the created ground mesh
  65531. */
  65532. GroundMesh.Parse = function (parsedMesh, scene) {
  65533. var result = new GroundMesh(parsedMesh.name, scene);
  65534. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  65535. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  65536. result._minX = parsedMesh.minX;
  65537. result._maxX = parsedMesh.maxX;
  65538. result._minZ = parsedMesh.minZ;
  65539. result._maxZ = parsedMesh.maxZ;
  65540. result._width = parsedMesh.width;
  65541. result._height = parsedMesh.height;
  65542. return result;
  65543. };
  65544. return GroundMesh;
  65545. }(BABYLON.Mesh));
  65546. BABYLON.GroundMesh = GroundMesh;
  65547. })(BABYLON || (BABYLON = {}));
  65548. //# sourceMappingURL=babylon.groundMesh.js.map
  65549. var BABYLON;
  65550. (function (BABYLON) {
  65551. /**
  65552. * Creates an instance based on a source mesh.
  65553. */
  65554. var InstancedMesh = /** @class */ (function (_super) {
  65555. __extends(InstancedMesh, _super);
  65556. function InstancedMesh(name, source) {
  65557. var _this = _super.call(this, name, source.getScene()) || this;
  65558. /** @hidden */
  65559. _this._indexInSourceMeshInstanceArray = -1;
  65560. source.addInstance(_this);
  65561. _this._sourceMesh = source;
  65562. _this.position.copyFrom(source.position);
  65563. _this.rotation.copyFrom(source.rotation);
  65564. _this.scaling.copyFrom(source.scaling);
  65565. if (source.rotationQuaternion) {
  65566. _this.rotationQuaternion = source.rotationQuaternion.clone();
  65567. }
  65568. _this.infiniteDistance = source.infiniteDistance;
  65569. _this.setPivotMatrix(source.getPivotMatrix());
  65570. _this.refreshBoundingInfo();
  65571. _this._syncSubMeshes();
  65572. return _this;
  65573. }
  65574. /**
  65575. * Returns the string "InstancedMesh".
  65576. */
  65577. InstancedMesh.prototype.getClassName = function () {
  65578. return "InstancedMesh";
  65579. };
  65580. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  65581. // Methods
  65582. /**
  65583. * If the source mesh receives shadows
  65584. */
  65585. get: function () {
  65586. return this._sourceMesh.receiveShadows;
  65587. },
  65588. enumerable: true,
  65589. configurable: true
  65590. });
  65591. Object.defineProperty(InstancedMesh.prototype, "material", {
  65592. /**
  65593. * The material of the source mesh
  65594. */
  65595. get: function () {
  65596. return this._sourceMesh.material;
  65597. },
  65598. enumerable: true,
  65599. configurable: true
  65600. });
  65601. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  65602. /**
  65603. * Visibility of the source mesh
  65604. */
  65605. get: function () {
  65606. return this._sourceMesh.visibility;
  65607. },
  65608. enumerable: true,
  65609. configurable: true
  65610. });
  65611. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  65612. /**
  65613. * Skeleton of the source mesh
  65614. */
  65615. get: function () {
  65616. return this._sourceMesh.skeleton;
  65617. },
  65618. enumerable: true,
  65619. configurable: true
  65620. });
  65621. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  65622. /**
  65623. * Rendering ground id of the source mesh
  65624. */
  65625. get: function () {
  65626. return this._sourceMesh.renderingGroupId;
  65627. },
  65628. set: function (value) {
  65629. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  65630. return;
  65631. }
  65632. //no-op with warning
  65633. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  65634. },
  65635. enumerable: true,
  65636. configurable: true
  65637. });
  65638. /**
  65639. * Returns the total number of vertices (integer).
  65640. */
  65641. InstancedMesh.prototype.getTotalVertices = function () {
  65642. return this._sourceMesh.getTotalVertices();
  65643. };
  65644. /**
  65645. * Returns a positive integer : the total number of indices in this mesh geometry.
  65646. * @returns the numner of indices or zero if the mesh has no geometry.
  65647. */
  65648. InstancedMesh.prototype.getTotalIndices = function () {
  65649. return this._sourceMesh.getTotalIndices();
  65650. };
  65651. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  65652. /**
  65653. * The source mesh of the instance
  65654. */
  65655. get: function () {
  65656. return this._sourceMesh;
  65657. },
  65658. enumerable: true,
  65659. configurable: true
  65660. });
  65661. /**
  65662. * Is this node ready to be used/rendered
  65663. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  65664. * @return {boolean} is it ready
  65665. */
  65666. InstancedMesh.prototype.isReady = function (completeCheck) {
  65667. if (completeCheck === void 0) { completeCheck = false; }
  65668. return this._sourceMesh.isReady(completeCheck, true);
  65669. };
  65670. /**
  65671. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  65672. * @param kind kind of verticies to retreive (eg. positons, normals, uvs, etc.)
  65673. * @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.
  65674. * @returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  65675. */
  65676. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  65677. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  65678. };
  65679. /**
  65680. * Sets the vertex data of the mesh geometry for the requested `kind`.
  65681. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  65682. * The `data` are either a numeric array either a Float32Array.
  65683. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  65684. * 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).
  65685. * Note that a new underlying VertexBuffer object is created each call.
  65686. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  65687. *
  65688. * Possible `kind` values :
  65689. * - BABYLON.VertexBuffer.PositionKind
  65690. * - BABYLON.VertexBuffer.UVKind
  65691. * - BABYLON.VertexBuffer.UV2Kind
  65692. * - BABYLON.VertexBuffer.UV3Kind
  65693. * - BABYLON.VertexBuffer.UV4Kind
  65694. * - BABYLON.VertexBuffer.UV5Kind
  65695. * - BABYLON.VertexBuffer.UV6Kind
  65696. * - BABYLON.VertexBuffer.ColorKind
  65697. * - BABYLON.VertexBuffer.MatricesIndicesKind
  65698. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  65699. * - BABYLON.VertexBuffer.MatricesWeightsKind
  65700. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  65701. *
  65702. * Returns the Mesh.
  65703. */
  65704. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  65705. if (this.sourceMesh) {
  65706. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  65707. }
  65708. return this.sourceMesh;
  65709. };
  65710. /**
  65711. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  65712. * If the mesh has no geometry, it is simply returned as it is.
  65713. * The `data` are either a numeric array either a Float32Array.
  65714. * No new underlying VertexBuffer object is created.
  65715. * 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.
  65716. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  65717. *
  65718. * Possible `kind` values :
  65719. * - BABYLON.VertexBuffer.PositionKind
  65720. * - BABYLON.VertexBuffer.UVKind
  65721. * - BABYLON.VertexBuffer.UV2Kind
  65722. * - BABYLON.VertexBuffer.UV3Kind
  65723. * - BABYLON.VertexBuffer.UV4Kind
  65724. * - BABYLON.VertexBuffer.UV5Kind
  65725. * - BABYLON.VertexBuffer.UV6Kind
  65726. * - BABYLON.VertexBuffer.ColorKind
  65727. * - BABYLON.VertexBuffer.MatricesIndicesKind
  65728. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  65729. * - BABYLON.VertexBuffer.MatricesWeightsKind
  65730. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  65731. *
  65732. * Returns the Mesh.
  65733. */
  65734. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  65735. if (this.sourceMesh) {
  65736. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  65737. }
  65738. return this.sourceMesh;
  65739. };
  65740. /**
  65741. * Sets the mesh indices.
  65742. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  65743. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  65744. * This method creates a new index buffer each call.
  65745. * Returns the Mesh.
  65746. */
  65747. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  65748. if (totalVertices === void 0) { totalVertices = null; }
  65749. if (this.sourceMesh) {
  65750. this.sourceMesh.setIndices(indices, totalVertices);
  65751. }
  65752. return this.sourceMesh;
  65753. };
  65754. /**
  65755. * Boolean : True if the mesh owns the requested kind of data.
  65756. */
  65757. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  65758. return this._sourceMesh.isVerticesDataPresent(kind);
  65759. };
  65760. /**
  65761. * Returns an array of indices (IndicesArray).
  65762. */
  65763. InstancedMesh.prototype.getIndices = function () {
  65764. return this._sourceMesh.getIndices();
  65765. };
  65766. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  65767. get: function () {
  65768. return this._sourceMesh._positions;
  65769. },
  65770. enumerable: true,
  65771. configurable: true
  65772. });
  65773. /**
  65774. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  65775. * This means the mesh underlying bounding box and sphere are recomputed.
  65776. * @param applySkeleton defines whether to apply the skeleton before computing the bounding info
  65777. * @returns the current mesh
  65778. */
  65779. InstancedMesh.prototype.refreshBoundingInfo = function (applySkeleton) {
  65780. if (applySkeleton === void 0) { applySkeleton = false; }
  65781. if (this._boundingInfo && this._boundingInfo.isLocked) {
  65782. return this;
  65783. }
  65784. var bias = this._sourceMesh.geometry ? this._sourceMesh.geometry.boundingBias : null;
  65785. this._refreshBoundingInfo(this._sourceMesh._getPositionData(applySkeleton), bias);
  65786. return this;
  65787. };
  65788. /** @hidden */
  65789. InstancedMesh.prototype._preActivate = function () {
  65790. if (this._currentLOD) {
  65791. this._currentLOD._preActivate();
  65792. }
  65793. return this;
  65794. };
  65795. /** @hidden */
  65796. InstancedMesh.prototype._activate = function (renderId) {
  65797. if (this._currentLOD) {
  65798. this._currentLOD._registerInstanceForRenderId(this, renderId);
  65799. }
  65800. return this;
  65801. };
  65802. /**
  65803. * Returns the current associated LOD AbstractMesh.
  65804. */
  65805. InstancedMesh.prototype.getLOD = function (camera) {
  65806. if (!camera) {
  65807. return this;
  65808. }
  65809. var boundingInfo = this.getBoundingInfo();
  65810. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  65811. if (this._currentLOD === this.sourceMesh) {
  65812. return this;
  65813. }
  65814. return this._currentLOD;
  65815. };
  65816. /** @hidden */
  65817. InstancedMesh.prototype._syncSubMeshes = function () {
  65818. this.releaseSubMeshes();
  65819. if (this._sourceMesh.subMeshes) {
  65820. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  65821. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  65822. }
  65823. }
  65824. return this;
  65825. };
  65826. /** @hidden */
  65827. InstancedMesh.prototype._generatePointsArray = function () {
  65828. return this._sourceMesh._generatePointsArray();
  65829. };
  65830. /**
  65831. * Creates a new InstancedMesh from the current mesh.
  65832. * - name (string) : the cloned mesh name
  65833. * - newParent (optional Node) : the optional Node to parent the clone to.
  65834. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  65835. *
  65836. * Returns the clone.
  65837. */
  65838. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  65839. var result = this._sourceMesh.createInstance(name);
  65840. // Deep copy
  65841. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  65842. // Bounding info
  65843. this.refreshBoundingInfo();
  65844. // Parent
  65845. if (newParent) {
  65846. result.parent = newParent;
  65847. }
  65848. if (!doNotCloneChildren) {
  65849. // Children
  65850. for (var index = 0; index < this.getScene().meshes.length; index++) {
  65851. var mesh = this.getScene().meshes[index];
  65852. if (mesh.parent === this) {
  65853. mesh.clone(mesh.name, result);
  65854. }
  65855. }
  65856. }
  65857. result.computeWorldMatrix(true);
  65858. return result;
  65859. };
  65860. /**
  65861. * Disposes the InstancedMesh.
  65862. * Returns nothing.
  65863. */
  65864. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  65865. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  65866. // Remove from mesh
  65867. this._sourceMesh.removeInstance(this);
  65868. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  65869. };
  65870. return InstancedMesh;
  65871. }(BABYLON.AbstractMesh));
  65872. BABYLON.InstancedMesh = InstancedMesh;
  65873. })(BABYLON || (BABYLON = {}));
  65874. //# sourceMappingURL=babylon.instancedMesh.js.map
  65875. var BABYLON;
  65876. (function (BABYLON) {
  65877. /**
  65878. * Line mesh
  65879. * @see https://doc.babylonjs.com/babylon101/parametric_shapes
  65880. */
  65881. var LinesMesh = /** @class */ (function (_super) {
  65882. __extends(LinesMesh, _super);
  65883. /**
  65884. * Creates a new LinesMesh
  65885. * @param name defines the name
  65886. * @param scene defines the hosting scene
  65887. * @param parent defines the parent mesh if any
  65888. * @param source defines the optional source LinesMesh used to clone data from
  65889. * @param doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  65890. * When false, achieved by calling a clone(), also passing False.
  65891. * This will make creation of children, recursive.
  65892. * @param useVertexColor defines if this LinesMesh supports vertex color
  65893. * @param useVertexAlpha defines if this LinesMesh supports vertex alpha
  65894. */
  65895. function LinesMesh(name, scene, parent, source, doNotCloneChildren,
  65896. /**
  65897. * If vertex color should be applied to the mesh
  65898. */
  65899. useVertexColor,
  65900. /**
  65901. * If vertex alpha should be applied to the mesh
  65902. */
  65903. useVertexAlpha) {
  65904. if (scene === void 0) { scene = null; }
  65905. if (parent === void 0) { parent = null; }
  65906. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  65907. _this.useVertexColor = useVertexColor;
  65908. _this.useVertexAlpha = useVertexAlpha;
  65909. /**
  65910. * Color of the line (Default: White)
  65911. */
  65912. _this.color = new BABYLON.Color3(1, 1, 1);
  65913. /**
  65914. * Alpha of the line (Default: 1)
  65915. */
  65916. _this.alpha = 1;
  65917. if (source) {
  65918. _this.color = source.color.clone();
  65919. _this.alpha = source.alpha;
  65920. _this.useVertexColor = source.useVertexColor;
  65921. _this.useVertexAlpha = source.useVertexAlpha;
  65922. }
  65923. _this.intersectionThreshold = 0.1;
  65924. var defines = [];
  65925. var options = {
  65926. attributes: [BABYLON.VertexBuffer.PositionKind, "world0", "world1", "world2", "world3"],
  65927. uniforms: ["world", "viewProjection"],
  65928. needAlphaBlending: true,
  65929. defines: defines
  65930. };
  65931. if (useVertexAlpha === false) {
  65932. options.needAlphaBlending = false;
  65933. }
  65934. if (!useVertexColor) {
  65935. options.uniforms.push("color");
  65936. }
  65937. else {
  65938. options.defines.push("#define VERTEXCOLOR");
  65939. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  65940. }
  65941. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  65942. return _this;
  65943. }
  65944. /**
  65945. * Returns the string "LineMesh"
  65946. */
  65947. LinesMesh.prototype.getClassName = function () {
  65948. return "LinesMesh";
  65949. };
  65950. Object.defineProperty(LinesMesh.prototype, "material", {
  65951. /**
  65952. * @hidden
  65953. */
  65954. get: function () {
  65955. return this._colorShader;
  65956. },
  65957. /**
  65958. * @hidden
  65959. */
  65960. set: function (value) {
  65961. // Do nothing
  65962. },
  65963. enumerable: true,
  65964. configurable: true
  65965. });
  65966. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  65967. /**
  65968. * @hidden
  65969. */
  65970. get: function () {
  65971. return false;
  65972. },
  65973. enumerable: true,
  65974. configurable: true
  65975. });
  65976. /** @hidden */
  65977. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  65978. if (!this._geometry) {
  65979. return this;
  65980. }
  65981. // VBOs
  65982. this._geometry._bind(this._colorShader.getEffect());
  65983. // Color
  65984. if (!this.useVertexColor) {
  65985. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  65986. }
  65987. return this;
  65988. };
  65989. /** @hidden */
  65990. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  65991. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  65992. return this;
  65993. }
  65994. var engine = this.getScene().getEngine();
  65995. // Draw order
  65996. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  65997. return this;
  65998. };
  65999. /**
  66000. * Disposes of the line mesh
  66001. * @param doNotRecurse If children should be disposed
  66002. */
  66003. LinesMesh.prototype.dispose = function (doNotRecurse) {
  66004. this._colorShader.dispose(false, false, true);
  66005. _super.prototype.dispose.call(this, doNotRecurse);
  66006. };
  66007. /**
  66008. * Returns a new LineMesh object cloned from the current one.
  66009. */
  66010. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  66011. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  66012. };
  66013. /**
  66014. * Creates a new InstancedLinesMesh object from the mesh model.
  66015. * @see http://doc.babylonjs.com/how_to/how_to_use_instances
  66016. * @param name defines the name of the new instance
  66017. * @returns a new InstancedLinesMesh
  66018. */
  66019. LinesMesh.prototype.createInstance = function (name) {
  66020. return new InstancedLinesMesh(name, this);
  66021. };
  66022. return LinesMesh;
  66023. }(BABYLON.Mesh));
  66024. BABYLON.LinesMesh = LinesMesh;
  66025. /**
  66026. * Creates an instance based on a source LinesMesh
  66027. */
  66028. var InstancedLinesMesh = /** @class */ (function (_super) {
  66029. __extends(InstancedLinesMesh, _super);
  66030. function InstancedLinesMesh(name, source) {
  66031. var _this = _super.call(this, name, source) || this;
  66032. _this.intersectionThreshold = source.intersectionThreshold;
  66033. return _this;
  66034. }
  66035. /**
  66036. * Returns the string "InstancedLinesMesh".
  66037. */
  66038. InstancedLinesMesh.prototype.getClassName = function () {
  66039. return "InstancedLinesMesh";
  66040. };
  66041. return InstancedLinesMesh;
  66042. }(BABYLON.InstancedMesh));
  66043. BABYLON.InstancedLinesMesh = InstancedLinesMesh;
  66044. })(BABYLON || (BABYLON = {}));
  66045. //# sourceMappingURL=babylon.linesMesh.js.map
  66046. var BABYLON;
  66047. (function (BABYLON) {
  66048. /**
  66049. * This class implement a typical dictionary using a string as key and the generic type T as value.
  66050. * The underlying implementation relies on an associative array to ensure the best performances.
  66051. * The value can be anything including 'null' but except 'undefined'
  66052. */
  66053. var StringDictionary = /** @class */ (function () {
  66054. function StringDictionary() {
  66055. this._count = 0;
  66056. this._data = {};
  66057. }
  66058. /**
  66059. * This will clear this dictionary and copy the content from the 'source' one.
  66060. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  66061. * @param source the dictionary to take the content from and copy to this dictionary
  66062. */
  66063. StringDictionary.prototype.copyFrom = function (source) {
  66064. var _this = this;
  66065. this.clear();
  66066. source.forEach(function (t, v) { return _this.add(t, v); });
  66067. };
  66068. /**
  66069. * Get a value based from its key
  66070. * @param key the given key to get the matching value from
  66071. * @return the value if found, otherwise undefined is returned
  66072. */
  66073. StringDictionary.prototype.get = function (key) {
  66074. var val = this._data[key];
  66075. if (val !== undefined) {
  66076. return val;
  66077. }
  66078. return undefined;
  66079. };
  66080. /**
  66081. * Get a value from its key or add it if it doesn't exist.
  66082. * This method will ensure you that a given key/data will be present in the dictionary.
  66083. * @param key the given key to get the matching value from
  66084. * @param factory the factory that will create the value if the key is not present in the dictionary.
  66085. * The factory will only be invoked if there's no data for the given key.
  66086. * @return the value corresponding to the key.
  66087. */
  66088. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  66089. var val = this.get(key);
  66090. if (val !== undefined) {
  66091. return val;
  66092. }
  66093. val = factory(key);
  66094. if (val) {
  66095. this.add(key, val);
  66096. }
  66097. return val;
  66098. };
  66099. /**
  66100. * Get a value from its key if present in the dictionary otherwise add it
  66101. * @param key the key to get the value from
  66102. * @param val if there's no such key/value pair in the dictionary add it with this value
  66103. * @return the value corresponding to the key
  66104. */
  66105. StringDictionary.prototype.getOrAdd = function (key, val) {
  66106. var curVal = this.get(key);
  66107. if (curVal !== undefined) {
  66108. return curVal;
  66109. }
  66110. this.add(key, val);
  66111. return val;
  66112. };
  66113. /**
  66114. * Check if there's a given key in the dictionary
  66115. * @param key the key to check for
  66116. * @return true if the key is present, false otherwise
  66117. */
  66118. StringDictionary.prototype.contains = function (key) {
  66119. return this._data[key] !== undefined;
  66120. };
  66121. /**
  66122. * Add a new key and its corresponding value
  66123. * @param key the key to add
  66124. * @param value the value corresponding to the key
  66125. * @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
  66126. */
  66127. StringDictionary.prototype.add = function (key, value) {
  66128. if (this._data[key] !== undefined) {
  66129. return false;
  66130. }
  66131. this._data[key] = value;
  66132. ++this._count;
  66133. return true;
  66134. };
  66135. /**
  66136. * Update a specific value associated to a key
  66137. * @param key defines the key to use
  66138. * @param value defines the value to store
  66139. * @returns true if the value was updated (or false if the key was not found)
  66140. */
  66141. StringDictionary.prototype.set = function (key, value) {
  66142. if (this._data[key] === undefined) {
  66143. return false;
  66144. }
  66145. this._data[key] = value;
  66146. return true;
  66147. };
  66148. /**
  66149. * Get the element of the given key and remove it from the dictionary
  66150. * @param key defines the key to search
  66151. * @returns the value associated with the key or null if not found
  66152. */
  66153. StringDictionary.prototype.getAndRemove = function (key) {
  66154. var val = this.get(key);
  66155. if (val !== undefined) {
  66156. delete this._data[key];
  66157. --this._count;
  66158. return val;
  66159. }
  66160. return null;
  66161. };
  66162. /**
  66163. * Remove a key/value from the dictionary.
  66164. * @param key the key to remove
  66165. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  66166. */
  66167. StringDictionary.prototype.remove = function (key) {
  66168. if (this.contains(key)) {
  66169. delete this._data[key];
  66170. --this._count;
  66171. return true;
  66172. }
  66173. return false;
  66174. };
  66175. /**
  66176. * Clear the whole content of the dictionary
  66177. */
  66178. StringDictionary.prototype.clear = function () {
  66179. this._data = {};
  66180. this._count = 0;
  66181. };
  66182. Object.defineProperty(StringDictionary.prototype, "count", {
  66183. /**
  66184. * Gets the current count
  66185. */
  66186. get: function () {
  66187. return this._count;
  66188. },
  66189. enumerable: true,
  66190. configurable: true
  66191. });
  66192. /**
  66193. * Execute a callback on each key/val of the dictionary.
  66194. * Note that you can remove any element in this dictionary in the callback implementation
  66195. * @param callback the callback to execute on a given key/value pair
  66196. */
  66197. StringDictionary.prototype.forEach = function (callback) {
  66198. for (var cur in this._data) {
  66199. var val = this._data[cur];
  66200. callback(cur, val);
  66201. }
  66202. };
  66203. /**
  66204. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  66205. * If the callback returns null or undefined the method will iterate to the next key/value pair
  66206. * Note that you can remove any element in this dictionary in the callback implementation
  66207. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  66208. * @returns the first item
  66209. */
  66210. StringDictionary.prototype.first = function (callback) {
  66211. for (var cur in this._data) {
  66212. var val = this._data[cur];
  66213. var res = callback(cur, val);
  66214. if (res) {
  66215. return res;
  66216. }
  66217. }
  66218. return null;
  66219. };
  66220. return StringDictionary;
  66221. }());
  66222. BABYLON.StringDictionary = StringDictionary;
  66223. })(BABYLON || (BABYLON = {}));
  66224. //# sourceMappingURL=babylon.stringDictionary.js.map
  66225. var BABYLON;
  66226. (function (BABYLON) {
  66227. var Debug;
  66228. (function (Debug) {
  66229. /**
  66230. * Class used to render a debug view of a given skeleton
  66231. * @see http://www.babylonjs-playground.com/#1BZJVJ#8
  66232. */
  66233. var SkeletonViewer = /** @class */ (function () {
  66234. /**
  66235. * Creates a new SkeletonViewer
  66236. * @param skeleton defines the skeleton to render
  66237. * @param mesh defines the mesh attached to the skeleton
  66238. * @param scene defines the hosting scene
  66239. * @param autoUpdateBonesMatrices defines a boolean indicating if bones matrices must be forced to update before rendering (true by default)
  66240. * @param renderingGroupId defines the rendering group id to use with the viewer
  66241. */
  66242. function SkeletonViewer(
  66243. /** defines the skeleton to render */
  66244. skeleton,
  66245. /** defines the mesh attached to the skeleton */
  66246. mesh, scene,
  66247. /** defines a boolean indicating if bones matrices must be forced to update before rendering (true by default) */
  66248. autoUpdateBonesMatrices,
  66249. /** defines the rendering group id to use with the viewer */
  66250. renderingGroupId) {
  66251. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  66252. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  66253. this.skeleton = skeleton;
  66254. this.mesh = mesh;
  66255. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  66256. this.renderingGroupId = renderingGroupId;
  66257. /** Gets or sets the color used to render the skeleton */
  66258. this.color = BABYLON.Color3.White();
  66259. this._debugLines = new Array();
  66260. this._isEnabled = false;
  66261. this._scene = scene;
  66262. this._utilityLayer = new BABYLON.UtilityLayerRenderer(this._scene, false);
  66263. this._utilityLayer.pickUtilitySceneFirst = false;
  66264. this._utilityLayer.utilityLayerScene.autoClearDepthAndStencil = true;
  66265. this.update();
  66266. this._renderFunction = this.update.bind(this);
  66267. }
  66268. Object.defineProperty(SkeletonViewer.prototype, "debugMesh", {
  66269. /**
  66270. * Returns the mesh used to render the bones
  66271. */
  66272. get: function () {
  66273. return this._debugMesh;
  66274. },
  66275. enumerable: true,
  66276. configurable: true
  66277. });
  66278. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  66279. get: function () {
  66280. return this._isEnabled;
  66281. },
  66282. /** Gets or sets a boolean indicating if the viewer is enabled */
  66283. set: function (value) {
  66284. if (this._isEnabled === value) {
  66285. return;
  66286. }
  66287. this._isEnabled = value;
  66288. if (value) {
  66289. this._scene.registerBeforeRender(this._renderFunction);
  66290. }
  66291. else {
  66292. this._scene.unregisterBeforeRender(this._renderFunction);
  66293. }
  66294. },
  66295. enumerable: true,
  66296. configurable: true
  66297. });
  66298. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  66299. if (x === void 0) { x = 0; }
  66300. if (y === void 0) { y = 0; }
  66301. if (z === void 0) { z = 0; }
  66302. var tmat = BABYLON.Tmp.Matrix[0];
  66303. var parentBone = bone.getParent();
  66304. tmat.copyFrom(bone.getLocalMatrix());
  66305. if (x !== 0 || y !== 0 || z !== 0) {
  66306. var tmat2 = BABYLON.Tmp.Matrix[1];
  66307. BABYLON.Matrix.IdentityToRef(tmat2);
  66308. tmat2.setTranslationFromFloats(x, y, z);
  66309. tmat2.multiplyToRef(tmat, tmat);
  66310. }
  66311. if (parentBone) {
  66312. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  66313. }
  66314. tmat.multiplyToRef(meshMat, tmat);
  66315. position.x = tmat.m[12];
  66316. position.y = tmat.m[13];
  66317. position.z = tmat.m[14];
  66318. };
  66319. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  66320. var len = bones.length;
  66321. var meshPos = this.mesh.position;
  66322. for (var i = 0; i < len; i++) {
  66323. var bone = bones[i];
  66324. var points = this._debugLines[i];
  66325. if (!points) {
  66326. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  66327. this._debugLines[i] = points;
  66328. }
  66329. this._getBonePosition(points[0], bone, meshMat);
  66330. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  66331. points[0].subtractInPlace(meshPos);
  66332. points[1].subtractInPlace(meshPos);
  66333. }
  66334. };
  66335. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  66336. var len = bones.length;
  66337. var boneNum = 0;
  66338. var meshPos = this.mesh.position;
  66339. for (var i = len - 1; i >= 0; i--) {
  66340. var childBone = bones[i];
  66341. var parentBone = childBone.getParent();
  66342. if (!parentBone) {
  66343. continue;
  66344. }
  66345. var points = this._debugLines[boneNum];
  66346. if (!points) {
  66347. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  66348. this._debugLines[boneNum] = points;
  66349. }
  66350. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  66351. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  66352. points[0].subtractInPlace(meshPos);
  66353. points[1].subtractInPlace(meshPos);
  66354. boneNum++;
  66355. }
  66356. };
  66357. /** Update the viewer to sync with current skeleton state */
  66358. SkeletonViewer.prototype.update = function () {
  66359. if (!this._utilityLayer) {
  66360. return;
  66361. }
  66362. if (this.autoUpdateBonesMatrices) {
  66363. this.skeleton.computeAbsoluteTransforms();
  66364. }
  66365. if (this.skeleton.bones[0].length === undefined) {
  66366. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  66367. }
  66368. else {
  66369. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  66370. }
  66371. var targetScene = this._utilityLayer.utilityLayerScene;
  66372. if (!this._debugMesh) {
  66373. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, targetScene);
  66374. this._debugMesh.renderingGroupId = this.renderingGroupId;
  66375. }
  66376. else {
  66377. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, targetScene);
  66378. }
  66379. this._debugMesh.position.copyFrom(this.mesh.position);
  66380. this._debugMesh.color = this.color;
  66381. };
  66382. /** Release associated resources */
  66383. SkeletonViewer.prototype.dispose = function () {
  66384. this.isEnabled = false;
  66385. if (this._debugMesh) {
  66386. this.isEnabled = false;
  66387. this._debugMesh.dispose();
  66388. this._debugMesh = null;
  66389. }
  66390. if (this._utilityLayer) {
  66391. this._utilityLayer.dispose();
  66392. this._utilityLayer = null;
  66393. }
  66394. };
  66395. return SkeletonViewer;
  66396. }());
  66397. Debug.SkeletonViewer = SkeletonViewer;
  66398. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  66399. })(BABYLON || (BABYLON = {}));
  66400. //# sourceMappingURL=babylon.skeletonViewer.js.map
  66401. /**
  66402. * Module Debug contains the (visual) components to debug a scene correctly
  66403. */
  66404. var BABYLON;
  66405. (function (BABYLON) {
  66406. var Debug;
  66407. (function (Debug) {
  66408. /**
  66409. * The Axes viewer will show 3 axes in a specific point in space
  66410. */
  66411. var AxesViewer = /** @class */ (function () {
  66412. /**
  66413. * Creates a new AxesViewer
  66414. * @param scene defines the hosting scene
  66415. * @param scaleLines defines a number used to scale line length (1 by default)
  66416. * @param renderingGroupId defines a number used to set the renderingGroupId of the meshes (2 by default)
  66417. * @param xAxis defines the node hierarchy used to render the x-axis
  66418. * @param yAxis defines the node hierarchy used to render the y-axis
  66419. * @param zAxis defines the node hierarchy used to render the z-axis
  66420. */
  66421. function AxesViewer(scene, scaleLines, renderingGroupId, xAxis, yAxis, zAxis) {
  66422. if (scaleLines === void 0) { scaleLines = 1; }
  66423. if (renderingGroupId === void 0) { renderingGroupId = 2; }
  66424. this._scaleLinesFactor = 4;
  66425. this._instanced = false;
  66426. /**
  66427. * Gets or sets a number used to scale line length
  66428. */
  66429. this.scaleLines = 1;
  66430. this.scaleLines = scaleLines;
  66431. if (!xAxis) {
  66432. var redColoredMaterial = new BABYLON.StandardMaterial("", scene);
  66433. redColoredMaterial.disableLighting = true;
  66434. redColoredMaterial.emissiveColor = BABYLON.Color3.Red().scale(0.5);
  66435. xAxis = BABYLON.AxisDragGizmo._CreateArrow(scene, redColoredMaterial);
  66436. }
  66437. if (!yAxis) {
  66438. var greenColoredMaterial = new BABYLON.StandardMaterial("", scene);
  66439. greenColoredMaterial.disableLighting = true;
  66440. greenColoredMaterial.emissiveColor = BABYLON.Color3.Green().scale(0.5);
  66441. yAxis = BABYLON.AxisDragGizmo._CreateArrow(scene, greenColoredMaterial);
  66442. }
  66443. if (!zAxis) {
  66444. var blueColoredMaterial = new BABYLON.StandardMaterial("", scene);
  66445. blueColoredMaterial.disableLighting = true;
  66446. blueColoredMaterial.emissiveColor = BABYLON.Color3.Blue().scale(0.5);
  66447. zAxis = BABYLON.AxisDragGizmo._CreateArrow(scene, blueColoredMaterial);
  66448. }
  66449. this._xAxis = xAxis;
  66450. this._xAxis.scaling.setAll(this.scaleLines * this._scaleLinesFactor);
  66451. this._yAxis = yAxis;
  66452. this._yAxis.scaling.setAll(this.scaleLines * this._scaleLinesFactor);
  66453. this._zAxis = zAxis;
  66454. this._zAxis.scaling.setAll(this.scaleLines * this._scaleLinesFactor);
  66455. if (renderingGroupId != null) {
  66456. AxesViewer._SetRenderingGroupId(this._xAxis, renderingGroupId);
  66457. AxesViewer._SetRenderingGroupId(this._yAxis, renderingGroupId);
  66458. AxesViewer._SetRenderingGroupId(this._zAxis, renderingGroupId);
  66459. }
  66460. this.scene = scene;
  66461. this.update(new BABYLON.Vector3(), BABYLON.Vector3.Right(), BABYLON.Vector3.Up(), BABYLON.Vector3.Forward());
  66462. }
  66463. Object.defineProperty(AxesViewer.prototype, "xAxis", {
  66464. /** Gets the node hierarchy used to render x-axis */
  66465. get: function () {
  66466. return this._xAxis;
  66467. },
  66468. enumerable: true,
  66469. configurable: true
  66470. });
  66471. Object.defineProperty(AxesViewer.prototype, "yAxis", {
  66472. /** Gets the node hierarchy used to render y-axis */
  66473. get: function () {
  66474. return this._yAxis;
  66475. },
  66476. enumerable: true,
  66477. configurable: true
  66478. });
  66479. Object.defineProperty(AxesViewer.prototype, "zAxis", {
  66480. /** Gets the node hierarchy used to render z-axis */
  66481. get: function () {
  66482. return this._zAxis;
  66483. },
  66484. enumerable: true,
  66485. configurable: true
  66486. });
  66487. /**
  66488. * Force the viewer to update
  66489. * @param position defines the position of the viewer
  66490. * @param xaxis defines the x axis of the viewer
  66491. * @param yaxis defines the y axis of the viewer
  66492. * @param zaxis defines the z axis of the viewer
  66493. */
  66494. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  66495. this._xAxis.position.copyFrom(position);
  66496. this._xAxis.setDirection(xaxis);
  66497. this._xAxis.scaling.setAll(this.scaleLines * this._scaleLinesFactor);
  66498. this._yAxis.position.copyFrom(position);
  66499. this._yAxis.setDirection(yaxis);
  66500. this._yAxis.scaling.setAll(this.scaleLines * this._scaleLinesFactor);
  66501. this._zAxis.position.copyFrom(position);
  66502. this._zAxis.setDirection(zaxis);
  66503. this._zAxis.scaling.setAll(this.scaleLines * this._scaleLinesFactor);
  66504. };
  66505. /**
  66506. * Creates an instance of this axes viewer.
  66507. * @returns a new axes viewer with instanced meshes
  66508. */
  66509. AxesViewer.prototype.createInstance = function () {
  66510. var xAxis = BABYLON.AxisDragGizmo._CreateArrowInstance(this.scene, this._xAxis);
  66511. var yAxis = BABYLON.AxisDragGizmo._CreateArrowInstance(this.scene, this._yAxis);
  66512. var zAxis = BABYLON.AxisDragGizmo._CreateArrowInstance(this.scene, this._zAxis);
  66513. var axesViewer = new AxesViewer(this.scene, this.scaleLines, null, xAxis, yAxis, zAxis);
  66514. axesViewer._instanced = true;
  66515. return axesViewer;
  66516. };
  66517. /** Releases resources */
  66518. AxesViewer.prototype.dispose = function () {
  66519. if (this._xAxis) {
  66520. this._xAxis.dispose(false, !this._instanced);
  66521. delete this._xAxis;
  66522. }
  66523. if (this._yAxis) {
  66524. this._yAxis.dispose(false, !this._instanced);
  66525. delete this._yAxis;
  66526. }
  66527. if (this._zAxis) {
  66528. this._zAxis.dispose(false, !this._instanced);
  66529. delete this._zAxis;
  66530. }
  66531. delete this.scene;
  66532. };
  66533. AxesViewer._SetRenderingGroupId = function (node, id) {
  66534. node.getChildMeshes().forEach(function (mesh) {
  66535. mesh.renderingGroupId = id;
  66536. });
  66537. };
  66538. return AxesViewer;
  66539. }());
  66540. Debug.AxesViewer = AxesViewer;
  66541. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  66542. })(BABYLON || (BABYLON = {}));
  66543. //# sourceMappingURL=babylon.axesViewer.js.map
  66544. var BABYLON;
  66545. (function (BABYLON) {
  66546. var Debug;
  66547. (function (Debug) {
  66548. /**
  66549. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  66550. * @see demo here: https://www.babylonjs-playground.com/#0DE8F4#8
  66551. */
  66552. var BoneAxesViewer = /** @class */ (function (_super) {
  66553. __extends(BoneAxesViewer, _super);
  66554. /**
  66555. * Creates a new BoneAxesViewer
  66556. * @param scene defines the hosting scene
  66557. * @param bone defines the target bone
  66558. * @param mesh defines the target mesh
  66559. * @param scaleLines defines a scaling factor for line length (1 by default)
  66560. */
  66561. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  66562. if (scaleLines === void 0) { scaleLines = 1; }
  66563. var _this = _super.call(this, scene, scaleLines) || this;
  66564. /** Gets current position */
  66565. _this.pos = BABYLON.Vector3.Zero();
  66566. /** Gets direction of X axis */
  66567. _this.xaxis = BABYLON.Vector3.Zero();
  66568. /** Gets direction of Y axis */
  66569. _this.yaxis = BABYLON.Vector3.Zero();
  66570. /** Gets direction of Z axis */
  66571. _this.zaxis = BABYLON.Vector3.Zero();
  66572. _this.mesh = mesh;
  66573. _this.bone = bone;
  66574. return _this;
  66575. }
  66576. /**
  66577. * Force the viewer to update
  66578. */
  66579. BoneAxesViewer.prototype.update = function () {
  66580. if (!this.mesh || !this.bone) {
  66581. return;
  66582. }
  66583. var bone = this.bone;
  66584. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  66585. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  66586. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  66587. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  66588. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  66589. };
  66590. /** Releases resources */
  66591. BoneAxesViewer.prototype.dispose = function () {
  66592. if (this.mesh) {
  66593. this.mesh = null;
  66594. this.bone = null;
  66595. _super.prototype.dispose.call(this);
  66596. }
  66597. };
  66598. return BoneAxesViewer;
  66599. }(Debug.AxesViewer));
  66600. Debug.BoneAxesViewer = BoneAxesViewer;
  66601. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  66602. })(BABYLON || (BABYLON = {}));
  66603. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  66604. var BABYLON;
  66605. (function (BABYLON) {
  66606. /**
  66607. * As raycast might be hard to debug, the RayHelper can help rendering the different rays
  66608. * in order to better appreciate the issue one might have.
  66609. * @see http://doc.babylonjs.com/babylon101/raycasts#debugging
  66610. */
  66611. var RayHelper = /** @class */ (function () {
  66612. /**
  66613. * Instantiate a new ray helper.
  66614. * As raycast might be hard to debug, the RayHelper can help rendering the different rays
  66615. * in order to better appreciate the issue one might have.
  66616. * @see http://doc.babylonjs.com/babylon101/raycasts#debugging
  66617. * @param ray Defines the ray we are currently tryin to visualize
  66618. */
  66619. function RayHelper(ray) {
  66620. this.ray = ray;
  66621. }
  66622. /**
  66623. * Helper function to create a colored helper in a scene in one line.
  66624. * @param ray Defines the ray we are currently tryin to visualize
  66625. * @param scene Defines the scene the ray is used in
  66626. * @param color Defines the color we want to see the ray in
  66627. * @returns The newly created ray helper.
  66628. */
  66629. RayHelper.CreateAndShow = function (ray, scene, color) {
  66630. var helper = new RayHelper(ray);
  66631. helper.show(scene, color);
  66632. return helper;
  66633. };
  66634. /**
  66635. * Shows the ray we are willing to debug.
  66636. * @param scene Defines the scene the ray needs to be rendered in
  66637. * @param color Defines the color the ray needs to be rendered in
  66638. */
  66639. RayHelper.prototype.show = function (scene, color) {
  66640. if (!this._renderFunction && this.ray) {
  66641. var ray = this.ray;
  66642. this._renderFunction = this._render.bind(this);
  66643. this._scene = scene;
  66644. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  66645. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  66646. if (this._renderFunction) {
  66647. this._scene.registerBeforeRender(this._renderFunction);
  66648. }
  66649. }
  66650. if (color && this._renderLine) {
  66651. this._renderLine.color.copyFrom(color);
  66652. }
  66653. };
  66654. /**
  66655. * Hides the ray we are debugging.
  66656. */
  66657. RayHelper.prototype.hide = function () {
  66658. if (this._renderFunction && this._scene) {
  66659. this._scene.unregisterBeforeRender(this._renderFunction);
  66660. this._scene = null;
  66661. this._renderFunction = null;
  66662. if (this._renderLine) {
  66663. this._renderLine.dispose();
  66664. this._renderLine = null;
  66665. }
  66666. this._renderPoints = [];
  66667. }
  66668. };
  66669. RayHelper.prototype._render = function () {
  66670. var ray = this.ray;
  66671. if (!ray) {
  66672. return;
  66673. }
  66674. var point = this._renderPoints[1];
  66675. var len = Math.min(ray.length, 1000000);
  66676. point.copyFrom(ray.direction);
  66677. point.scaleInPlace(len);
  66678. point.addInPlace(ray.origin);
  66679. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  66680. };
  66681. /**
  66682. * Attach a ray helper to a mesh so that we can easily see its orientation for instance or information like its normals.
  66683. * @param mesh Defines the mesh we want the helper attached to
  66684. * @param meshSpaceDirection Defines the direction of the Ray in mesh space (local space of the mesh node)
  66685. * @param meshSpaceOrigin Defines the origin of the Ray in mesh space (local space of the mesh node)
  66686. * @param length Defines the length of the ray
  66687. */
  66688. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  66689. this._attachedToMesh = mesh;
  66690. var ray = this.ray;
  66691. if (!ray) {
  66692. return;
  66693. }
  66694. if (!ray.direction) {
  66695. ray.direction = BABYLON.Vector3.Zero();
  66696. }
  66697. if (!ray.origin) {
  66698. ray.origin = BABYLON.Vector3.Zero();
  66699. }
  66700. if (length) {
  66701. ray.length = length;
  66702. }
  66703. if (!meshSpaceOrigin) {
  66704. meshSpaceOrigin = BABYLON.Vector3.Zero();
  66705. }
  66706. if (!meshSpaceDirection) {
  66707. // -1 so that this will work with Mesh.lookAt
  66708. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  66709. }
  66710. if (!this._meshSpaceDirection) {
  66711. this._meshSpaceDirection = meshSpaceDirection.clone();
  66712. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  66713. }
  66714. else {
  66715. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  66716. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  66717. }
  66718. if (!this._updateToMeshFunction) {
  66719. this._updateToMeshFunction = this._updateToMesh.bind(this);
  66720. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  66721. }
  66722. this._updateToMesh();
  66723. };
  66724. /**
  66725. * Detach the ray helper from the mesh it has previously been attached to.
  66726. */
  66727. RayHelper.prototype.detachFromMesh = function () {
  66728. if (this._attachedToMesh) {
  66729. if (this._updateToMeshFunction) {
  66730. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  66731. }
  66732. this._attachedToMesh = null;
  66733. this._updateToMeshFunction = null;
  66734. }
  66735. };
  66736. RayHelper.prototype._updateToMesh = function () {
  66737. var ray = this.ray;
  66738. if (!this._attachedToMesh || !ray) {
  66739. return;
  66740. }
  66741. if (this._attachedToMesh._isDisposed) {
  66742. this.detachFromMesh();
  66743. return;
  66744. }
  66745. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  66746. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  66747. };
  66748. /**
  66749. * Dispose the helper and release its associated resources.
  66750. */
  66751. RayHelper.prototype.dispose = function () {
  66752. this.hide();
  66753. this.detachFromMesh();
  66754. this.ray = null;
  66755. };
  66756. return RayHelper;
  66757. }());
  66758. BABYLON.RayHelper = RayHelper;
  66759. })(BABYLON || (BABYLON = {}));
  66760. //# sourceMappingURL=babylon.rayHelper.js.map
  66761. var __assign = (this && this.__assign) || function () {
  66762. __assign = Object.assign || function(t) {
  66763. for (var s, i = 1, n = arguments.length; i < n; i++) {
  66764. s = arguments[i];
  66765. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  66766. t[p] = s[p];
  66767. }
  66768. return t;
  66769. };
  66770. return __assign.apply(this, arguments);
  66771. };
  66772. var BABYLON;
  66773. (function (BABYLON) {
  66774. Object.defineProperty(BABYLON.Scene.prototype, "debugLayer", {
  66775. get: function () {
  66776. if (!this._debugLayer) {
  66777. this._debugLayer = new DebugLayer(this);
  66778. }
  66779. return this._debugLayer;
  66780. },
  66781. enumerable: true,
  66782. configurable: true
  66783. });
  66784. /**
  66785. * The debug layer (aka Inspector) is the go to tool in order to better understand
  66786. * what is happening in your scene
  66787. * @see http://doc.babylonjs.com/features/playground_debuglayer
  66788. */
  66789. var DebugLayer = /** @class */ (function () {
  66790. /**
  66791. * Instantiates a new debug layer.
  66792. * The debug layer (aka Inspector) is the go to tool in order to better understand
  66793. * what is happening in your scene
  66794. * @see http://doc.babylonjs.com/features/playground_debuglayer
  66795. * @param scene Defines the scene to inspect
  66796. */
  66797. function DebugLayer(scene) {
  66798. var _this = this;
  66799. this.BJSINSPECTOR = this._getGlobalInspector();
  66800. /**
  66801. * Observable triggered when a property is changed through the inspector.
  66802. */
  66803. this.onPropertyChangedObservable = new BABYLON.Observable();
  66804. this._scene = scene;
  66805. this._scene.onDisposeObservable.add(function () {
  66806. // Debug layer
  66807. if (_this._scene._debugLayer) {
  66808. _this._scene._debugLayer.hide();
  66809. }
  66810. });
  66811. }
  66812. /** Creates the inspector window. */
  66813. DebugLayer.prototype._createInspector = function (config) {
  66814. if (this.isVisible()) {
  66815. return;
  66816. }
  66817. var userOptions = __assign({ overlay: false, showExplorer: true, showInspector: true, embedMode: false, handleResize: true, enablePopup: true }, config);
  66818. this.BJSINSPECTOR = this.BJSINSPECTOR || this._getGlobalInspector();
  66819. this.BJSINSPECTOR.Inspector.Show(this._scene, userOptions);
  66820. };
  66821. /** Get the inspector from bundle or global */
  66822. DebugLayer.prototype._getGlobalInspector = function () {
  66823. // UMD Global name detection from Webpack Bundle UMD Name.
  66824. if (typeof INSPECTOR !== 'undefined') {
  66825. return INSPECTOR;
  66826. }
  66827. // In case of module let s check the global emitted from the Inspector entry point.
  66828. if (BABYLON && BABYLON.Inspector) {
  66829. return BABYLON;
  66830. }
  66831. return undefined;
  66832. };
  66833. /**
  66834. * Get if the inspector is visible or not.
  66835. * @returns true if visible otherwise, false
  66836. */
  66837. DebugLayer.prototype.isVisible = function () {
  66838. return this.BJSINSPECTOR && this.BJSINSPECTOR.Inspector.IsVisible;
  66839. };
  66840. /**
  66841. * Hide the inspector and close its window.
  66842. */
  66843. DebugLayer.prototype.hide = function () {
  66844. this.BJSINSPECTOR.Inspector.Hide();
  66845. };
  66846. /**
  66847. * Launch the debugLayer.
  66848. * @param config Define the configuration of the inspector
  66849. */
  66850. DebugLayer.prototype.show = function (config) {
  66851. if (typeof this.BJSINSPECTOR == 'undefined') {
  66852. // Load inspector and add it to the DOM
  66853. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  66854. }
  66855. else {
  66856. // Otherwise creates the inspector
  66857. this._createInspector(config);
  66858. }
  66859. };
  66860. /**
  66861. * Define the url to get the inspector script from.
  66862. * By default it uses the babylonjs CDN.
  66863. * @ignoreNaming
  66864. */
  66865. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  66866. return DebugLayer;
  66867. }());
  66868. BABYLON.DebugLayer = DebugLayer;
  66869. })(BABYLON || (BABYLON = {}));
  66870. //# sourceMappingURL=babylon.debugLayer.js.map
  66871. var BABYLON;
  66872. (function (BABYLON) {
  66873. var Debug;
  66874. (function (Debug) {
  66875. /**
  66876. * Used to show the physics impostor around the specific mesh
  66877. */
  66878. var PhysicsViewer = /** @class */ (function () {
  66879. /**
  66880. * Creates a new PhysicsViewer
  66881. * @param scene defines the hosting scene
  66882. */
  66883. function PhysicsViewer(scene) {
  66884. /** @hidden */
  66885. this._impostors = [];
  66886. /** @hidden */
  66887. this._meshes = [];
  66888. /** @hidden */
  66889. this._numMeshes = 0;
  66890. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  66891. var physicEngine = this._scene.getPhysicsEngine();
  66892. if (physicEngine) {
  66893. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  66894. }
  66895. this._utilityLayer = new BABYLON.UtilityLayerRenderer(this._scene, false);
  66896. this._utilityLayer.pickUtilitySceneFirst = false;
  66897. this._utilityLayer.utilityLayerScene.autoClearDepthAndStencil = true;
  66898. }
  66899. /** @hidden */
  66900. PhysicsViewer.prototype._updateDebugMeshes = function () {
  66901. var plugin = this._physicsEnginePlugin;
  66902. for (var i = 0; i < this._numMeshes; i++) {
  66903. var impostor = this._impostors[i];
  66904. if (!impostor) {
  66905. continue;
  66906. }
  66907. if (impostor.isDisposed) {
  66908. this.hideImpostor(this._impostors[i--]);
  66909. }
  66910. else {
  66911. var mesh = this._meshes[i];
  66912. if (mesh && plugin) {
  66913. plugin.syncMeshWithImpostor(mesh, impostor);
  66914. }
  66915. }
  66916. }
  66917. };
  66918. /**
  66919. * Renders a specified physic impostor
  66920. * @param impostor defines the impostor to render
  66921. * @returns the new debug mesh used to render the impostor
  66922. */
  66923. PhysicsViewer.prototype.showImpostor = function (impostor) {
  66924. if (!this._scene) {
  66925. return null;
  66926. }
  66927. for (var i = 0; i < this._numMeshes; i++) {
  66928. if (this._impostors[i] == impostor) {
  66929. return null;
  66930. }
  66931. }
  66932. var debugMesh = this._getDebugMesh(impostor);
  66933. if (debugMesh) {
  66934. this._impostors[this._numMeshes] = impostor;
  66935. this._meshes[this._numMeshes] = debugMesh;
  66936. if (this._numMeshes === 0) {
  66937. this._renderFunction = this._updateDebugMeshes.bind(this);
  66938. this._scene.registerBeforeRender(this._renderFunction);
  66939. }
  66940. this._numMeshes++;
  66941. }
  66942. return debugMesh;
  66943. };
  66944. /**
  66945. * Hides a specified physic impostor
  66946. * @param impostor defines the impostor to hide
  66947. */
  66948. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  66949. if (!impostor || !this._scene || !this._utilityLayer) {
  66950. return;
  66951. }
  66952. var removed = false;
  66953. var utilityLayerScene = this._utilityLayer.utilityLayerScene;
  66954. for (var i = 0; i < this._numMeshes; i++) {
  66955. if (this._impostors[i] == impostor) {
  66956. var mesh = this._meshes[i];
  66957. if (!mesh) {
  66958. continue;
  66959. }
  66960. utilityLayerScene.removeMesh(mesh);
  66961. mesh.dispose();
  66962. this._numMeshes--;
  66963. if (this._numMeshes > 0) {
  66964. this._meshes[i] = this._meshes[this._numMeshes];
  66965. this._impostors[i] = this._impostors[this._numMeshes];
  66966. this._meshes[this._numMeshes] = null;
  66967. this._impostors[this._numMeshes] = null;
  66968. }
  66969. else {
  66970. this._meshes[0] = null;
  66971. this._impostors[0] = null;
  66972. }
  66973. removed = true;
  66974. break;
  66975. }
  66976. }
  66977. if (removed && this._numMeshes === 0) {
  66978. this._scene.unregisterBeforeRender(this._renderFunction);
  66979. }
  66980. };
  66981. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  66982. if (!this._debugMaterial) {
  66983. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  66984. this._debugMaterial.wireframe = true;
  66985. this._debugMaterial.emissiveColor = BABYLON.Color3.White();
  66986. this._debugMaterial.disableLighting = true;
  66987. }
  66988. return this._debugMaterial;
  66989. };
  66990. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  66991. if (!this._debugBoxMesh) {
  66992. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  66993. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  66994. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  66995. }
  66996. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  66997. };
  66998. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  66999. if (!this._debugSphereMesh) {
  67000. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  67001. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  67002. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  67003. }
  67004. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  67005. };
  67006. PhysicsViewer.prototype._getDebugMesh = function (impostor) {
  67007. if (!this._utilityLayer) {
  67008. return null;
  67009. }
  67010. var mesh = null;
  67011. var utilityLayerScene = this._utilityLayer.utilityLayerScene;
  67012. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  67013. mesh = this._getDebugBoxMesh(utilityLayerScene);
  67014. impostor.getBoxSizeToRef(mesh.scaling);
  67015. }
  67016. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  67017. mesh = this._getDebugSphereMesh(utilityLayerScene);
  67018. var radius = impostor.getRadius();
  67019. mesh.scaling.x = radius * 2;
  67020. mesh.scaling.y = radius * 2;
  67021. mesh.scaling.z = radius * 2;
  67022. }
  67023. return mesh;
  67024. };
  67025. /** Releases all resources */
  67026. PhysicsViewer.prototype.dispose = function () {
  67027. for (var i = 0; i < this._numMeshes; i++) {
  67028. this.hideImpostor(this._impostors[i]);
  67029. }
  67030. if (this._debugBoxMesh) {
  67031. this._debugBoxMesh.dispose();
  67032. }
  67033. if (this._debugSphereMesh) {
  67034. this._debugSphereMesh.dispose();
  67035. }
  67036. if (this._debugMaterial) {
  67037. this._debugMaterial.dispose();
  67038. }
  67039. this._impostors.length = 0;
  67040. this._scene = null;
  67041. this._physicsEnginePlugin = null;
  67042. if (this._utilityLayer) {
  67043. this._utilityLayer.dispose();
  67044. this._utilityLayer = null;
  67045. }
  67046. };
  67047. return PhysicsViewer;
  67048. }());
  67049. Debug.PhysicsViewer = PhysicsViewer;
  67050. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  67051. })(BABYLON || (BABYLON = {}));
  67052. //# sourceMappingURL=babylon.physicsViewer.js.map
  67053. var BABYLON;
  67054. (function (BABYLON) {
  67055. Object.defineProperty(BABYLON.Scene.prototype, "forceShowBoundingBoxes", {
  67056. get: function () {
  67057. return this._forceShowBoundingBoxes || false;
  67058. },
  67059. set: function (value) {
  67060. this._forceShowBoundingBoxes = value;
  67061. // Lazyly creates a BB renderer if needed.
  67062. if (value) {
  67063. this.getBoundingBoxRenderer();
  67064. }
  67065. },
  67066. enumerable: true,
  67067. configurable: true
  67068. });
  67069. BABYLON.Scene.prototype.getBoundingBoxRenderer = function () {
  67070. if (!this._boundingBoxRenderer) {
  67071. this._boundingBoxRenderer = new BoundingBoxRenderer(this);
  67072. }
  67073. return this._boundingBoxRenderer;
  67074. };
  67075. Object.defineProperty(BABYLON.AbstractMesh.prototype, "showBoundingBox", {
  67076. get: function () {
  67077. return this._showBoundingBox || false;
  67078. },
  67079. set: function (value) {
  67080. this._showBoundingBox = value;
  67081. // Lazyly creates a BB renderer if needed.
  67082. if (value) {
  67083. this.getScene().getBoundingBoxRenderer();
  67084. }
  67085. },
  67086. enumerable: true,
  67087. configurable: true
  67088. });
  67089. /**
  67090. * Component responsible of rendering the bounding box of the meshes in a scene.
  67091. * This is usually used through the mesh.showBoundingBox or the scene.forceShowBoundingBoxes properties
  67092. */
  67093. var BoundingBoxRenderer = /** @class */ (function () {
  67094. /**
  67095. * Instantiates a new bounding box renderer in a scene.
  67096. * @param scene the scene the renderer renders in
  67097. */
  67098. function BoundingBoxRenderer(scene) {
  67099. /**
  67100. * The component name helpfull to identify the component in the list of scene components.
  67101. */
  67102. this.name = BABYLON.SceneComponentConstants.NAME_BOUNDINGBOXRENDERER;
  67103. /**
  67104. * Color of the bounding box lines placed in front of an object
  67105. */
  67106. this.frontColor = new BABYLON.Color3(1, 1, 1);
  67107. /**
  67108. * Color of the bounding box lines placed behind an object
  67109. */
  67110. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  67111. /**
  67112. * Defines if the renderer should show the back lines or not
  67113. */
  67114. this.showBackLines = true;
  67115. /**
  67116. * @hidden
  67117. */
  67118. this.renderList = new BABYLON.SmartArray(32);
  67119. this._vertexBuffers = {};
  67120. this.scene = scene;
  67121. scene._addComponent(this);
  67122. }
  67123. /**
  67124. * Registers the component in a given scene
  67125. */
  67126. BoundingBoxRenderer.prototype.register = function () {
  67127. this.scene._beforeEvaluateActiveMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER, this, this.reset);
  67128. this.scene._activeMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER, this, this._activeMesh);
  67129. this.scene._evaluateSubMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER, this, this._evaluateSubMesh);
  67130. this.scene._afterRenderingGroupDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER, this, this.render);
  67131. };
  67132. BoundingBoxRenderer.prototype._evaluateSubMesh = function (mesh, subMesh) {
  67133. if (mesh.showSubMeshesBoundingBox) {
  67134. var boundingInfo = subMesh.getBoundingInfo();
  67135. if (boundingInfo !== null && boundingInfo !== undefined) {
  67136. boundingInfo.boundingBox._tag = mesh.renderingGroupId;
  67137. this.renderList.push(boundingInfo.boundingBox);
  67138. }
  67139. }
  67140. };
  67141. BoundingBoxRenderer.prototype._activeMesh = function (sourceMesh, mesh) {
  67142. if (sourceMesh.showBoundingBox || this.scene.forceShowBoundingBoxes) {
  67143. var boundingInfo = sourceMesh.getBoundingInfo();
  67144. boundingInfo.boundingBox._tag = mesh.renderingGroupId;
  67145. this.renderList.push(boundingInfo.boundingBox);
  67146. }
  67147. };
  67148. BoundingBoxRenderer.prototype._prepareRessources = function () {
  67149. if (this._colorShader) {
  67150. return;
  67151. }
  67152. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this.scene, "color", {
  67153. attributes: [BABYLON.VertexBuffer.PositionKind],
  67154. uniforms: ["world", "viewProjection", "color"]
  67155. });
  67156. var engine = this.scene.getEngine();
  67157. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  67158. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  67159. this._createIndexBuffer();
  67160. };
  67161. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  67162. var engine = this.scene.getEngine();
  67163. 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]);
  67164. };
  67165. /**
  67166. * Rebuilds the elements related to this component in case of
  67167. * context lost for instance.
  67168. */
  67169. BoundingBoxRenderer.prototype.rebuild = function () {
  67170. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  67171. if (vb) {
  67172. vb._rebuild();
  67173. }
  67174. this._createIndexBuffer();
  67175. };
  67176. /**
  67177. * @hidden
  67178. */
  67179. BoundingBoxRenderer.prototype.reset = function () {
  67180. this.renderList.reset();
  67181. };
  67182. /**
  67183. * Render the bounding boxes of a specific rendering group
  67184. * @param renderingGroupId defines the rendering group to render
  67185. */
  67186. BoundingBoxRenderer.prototype.render = function (renderingGroupId) {
  67187. if (this.renderList.length === 0) {
  67188. return;
  67189. }
  67190. this._prepareRessources();
  67191. if (!this._colorShader.isReady()) {
  67192. return;
  67193. }
  67194. var engine = this.scene.getEngine();
  67195. engine.setDepthWrite(false);
  67196. this._colorShader._preBind();
  67197. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  67198. var boundingBox = this.renderList.data[boundingBoxIndex];
  67199. if (boundingBox._tag !== renderingGroupId) {
  67200. continue;
  67201. }
  67202. var min = boundingBox.minimum;
  67203. var max = boundingBox.maximum;
  67204. var diff = max.subtract(min);
  67205. var median = min.add(diff.scale(0.5));
  67206. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  67207. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  67208. .multiply(boundingBox.getWorldMatrix());
  67209. // VBOs
  67210. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  67211. if (this.showBackLines) {
  67212. // Back
  67213. engine.setDepthFunctionToGreaterOrEqual();
  67214. this.scene.resetCachedMaterial();
  67215. this._colorShader.setColor4("color", this.backColor.toColor4());
  67216. this._colorShader.bind(worldMatrix);
  67217. // Draw order
  67218. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  67219. }
  67220. // Front
  67221. engine.setDepthFunctionToLess();
  67222. this.scene.resetCachedMaterial();
  67223. this._colorShader.setColor4("color", this.frontColor.toColor4());
  67224. this._colorShader.bind(worldMatrix);
  67225. // Draw order
  67226. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  67227. }
  67228. this._colorShader.unbind();
  67229. engine.setDepthFunctionToLessOrEqual();
  67230. engine.setDepthWrite(true);
  67231. };
  67232. /**
  67233. * In case of occlusion queries, we can render the occlusion bounding box through this method
  67234. * @param mesh Define the mesh to render the occlusion bounding box for
  67235. */
  67236. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  67237. this._prepareRessources();
  67238. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  67239. return;
  67240. }
  67241. var engine = this.scene.getEngine();
  67242. engine.setDepthWrite(false);
  67243. engine.setColorWrite(false);
  67244. this._colorShader._preBind();
  67245. var boundingBox = mesh._boundingInfo.boundingBox;
  67246. var min = boundingBox.minimum;
  67247. var max = boundingBox.maximum;
  67248. var diff = max.subtract(min);
  67249. var median = min.add(diff.scale(0.5));
  67250. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  67251. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  67252. .multiply(boundingBox.getWorldMatrix());
  67253. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  67254. engine.setDepthFunctionToLess();
  67255. this.scene.resetCachedMaterial();
  67256. this._colorShader.bind(worldMatrix);
  67257. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  67258. this._colorShader.unbind();
  67259. engine.setDepthFunctionToLessOrEqual();
  67260. engine.setDepthWrite(true);
  67261. engine.setColorWrite(true);
  67262. };
  67263. /**
  67264. * Dispose and release the resources attached to this renderer.
  67265. */
  67266. BoundingBoxRenderer.prototype.dispose = function () {
  67267. if (!this._colorShader) {
  67268. return;
  67269. }
  67270. this.renderList.dispose();
  67271. this._colorShader.dispose();
  67272. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  67273. if (buffer) {
  67274. buffer.dispose();
  67275. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  67276. }
  67277. this.scene.getEngine()._releaseBuffer(this._indexBuffer);
  67278. };
  67279. return BoundingBoxRenderer;
  67280. }());
  67281. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  67282. })(BABYLON || (BABYLON = {}));
  67283. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  67284. var BABYLON;
  67285. (function (BABYLON) {
  67286. BABYLON.Engine.prototype.createTransformFeedback = function () {
  67287. return this._gl.createTransformFeedback();
  67288. };
  67289. BABYLON.Engine.prototype.deleteTransformFeedback = function (value) {
  67290. this._gl.deleteTransformFeedback(value);
  67291. };
  67292. BABYLON.Engine.prototype.bindTransformFeedback = function (value) {
  67293. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  67294. };
  67295. BABYLON.Engine.prototype.beginTransformFeedback = function (usePoints) {
  67296. if (usePoints === void 0) { usePoints = true; }
  67297. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  67298. };
  67299. BABYLON.Engine.prototype.endTransformFeedback = function () {
  67300. this._gl.endTransformFeedback();
  67301. };
  67302. BABYLON.Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  67303. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  67304. };
  67305. BABYLON.Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  67306. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  67307. };
  67308. })(BABYLON || (BABYLON = {}));
  67309. //# sourceMappingURL=babylon.engine.transformFeedback.js.map
  67310. var BABYLON;
  67311. (function (BABYLON) {
  67312. /**
  67313. * This represents a GPU particle system in Babylon
  67314. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  67315. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  67316. */
  67317. var GPUParticleSystem = /** @class */ (function (_super) {
  67318. __extends(GPUParticleSystem, _super);
  67319. /**
  67320. * Instantiates a GPU particle system.
  67321. * 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.
  67322. * @param name The name of the particle system
  67323. * @param options The options used to create the system
  67324. * @param scene The scene the particle system belongs to
  67325. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  67326. */
  67327. function GPUParticleSystem(name, options, scene, isAnimationSheetEnabled) {
  67328. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  67329. var _this = _super.call(this, name) || this;
  67330. /**
  67331. * The layer mask we are rendering the particles through.
  67332. */
  67333. _this.layerMask = 0x0FFFFFFF;
  67334. _this._accumulatedCount = 0;
  67335. _this._targetIndex = 0;
  67336. _this._currentRenderId = -1;
  67337. _this._started = false;
  67338. _this._stopped = false;
  67339. _this._timeDelta = 0;
  67340. _this._actualFrame = 0;
  67341. _this._rawTextureWidth = 256;
  67342. /**
  67343. * An event triggered when the system is disposed.
  67344. */
  67345. _this.onDisposeObservable = new BABYLON.Observable();
  67346. /**
  67347. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  67348. * to override the particles.
  67349. */
  67350. _this.forceDepthWrite = false;
  67351. _this._preWarmDone = false;
  67352. _this._scene = scene || BABYLON.Engine.LastCreatedScene;
  67353. // Setup the default processing configuration to the scene.
  67354. _this._attachImageProcessingConfiguration(null);
  67355. _this._engine = _this._scene.getEngine();
  67356. if (!options.randomTextureSize) {
  67357. delete options.randomTextureSize;
  67358. }
  67359. var fullOptions = __assign({ capacity: 50000, randomTextureSize: _this._engine.getCaps().maxTextureSize }, options);
  67360. var optionsAsNumber = options;
  67361. if (isFinite(optionsAsNumber)) {
  67362. fullOptions.capacity = optionsAsNumber;
  67363. }
  67364. _this._capacity = fullOptions.capacity;
  67365. _this._activeCount = fullOptions.capacity;
  67366. _this._currentActiveCount = 0;
  67367. _this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  67368. _this._scene.particleSystems.push(_this);
  67369. _this._updateEffectOptions = {
  67370. attributes: ["position", "age", "life", "seed", "size", "color", "direction", "initialDirection", "angle", "cellIndex", "cellStartOffset", "noiseCoordinates1", "noiseCoordinates2"],
  67371. uniformsNames: ["currentCount", "timeDelta", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "scaleRange", "gravity", "emitPower",
  67372. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "coneAngle", "stopFactor",
  67373. "angleRange", "radiusRange", "cellInfos", "noiseStrength", "limitVelocityDamping"],
  67374. uniformBuffersNames: [],
  67375. samplers: ["randomSampler", "randomSampler2", "sizeGradientSampler", "angularSpeedGradientSampler", "velocityGradientSampler", "limitVelocityGradientSampler", "noiseSampler", "dragGradientSampler"],
  67376. defines: "",
  67377. fallbacks: null,
  67378. onCompiled: null,
  67379. onError: null,
  67380. indexParameters: null,
  67381. maxSimultaneousLights: 0,
  67382. transformFeedbackVaryings: []
  67383. };
  67384. _this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  67385. // Random data
  67386. var maxTextureSize = Math.min(_this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  67387. var d = [];
  67388. for (var i = 0; i < maxTextureSize; ++i) {
  67389. d.push(Math.random());
  67390. d.push(Math.random());
  67391. d.push(Math.random());
  67392. d.push(Math.random());
  67393. }
  67394. _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);
  67395. _this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  67396. _this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  67397. d = [];
  67398. for (var i = 0; i < maxTextureSize; ++i) {
  67399. d.push(Math.random());
  67400. d.push(Math.random());
  67401. d.push(Math.random());
  67402. d.push(Math.random());
  67403. }
  67404. _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);
  67405. _this._randomTexture2.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  67406. _this._randomTexture2.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  67407. _this._randomTextureSize = maxTextureSize;
  67408. return _this;
  67409. }
  67410. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  67411. /**
  67412. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  67413. */
  67414. get: function () {
  67415. if (!BABYLON.Engine.LastCreatedEngine) {
  67416. return false;
  67417. }
  67418. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  67419. },
  67420. enumerable: true,
  67421. configurable: true
  67422. });
  67423. /**
  67424. * Gets the maximum number of particles active at the same time.
  67425. * @returns The max number of active particles.
  67426. */
  67427. GPUParticleSystem.prototype.getCapacity = function () {
  67428. return this._capacity;
  67429. };
  67430. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  67431. /**
  67432. * Gets or set the number of active particles
  67433. */
  67434. get: function () {
  67435. return this._activeCount;
  67436. },
  67437. set: function (value) {
  67438. this._activeCount = Math.min(value, this._capacity);
  67439. },
  67440. enumerable: true,
  67441. configurable: true
  67442. });
  67443. /**
  67444. * Is this system ready to be used/rendered
  67445. * @return true if the system is ready
  67446. */
  67447. GPUParticleSystem.prototype.isReady = function () {
  67448. if (!this._updateEffect) {
  67449. this._recreateUpdateEffect();
  67450. this._recreateRenderEffect();
  67451. return false;
  67452. }
  67453. if (!this.emitter || !this._updateEffect.isReady() || !this._imageProcessingConfiguration.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  67454. return false;
  67455. }
  67456. return true;
  67457. };
  67458. /**
  67459. * Gets if the system has been started. (Note: this will still be true after stop is called)
  67460. * @returns True if it has been started, otherwise false.
  67461. */
  67462. GPUParticleSystem.prototype.isStarted = function () {
  67463. return this._started;
  67464. };
  67465. /**
  67466. * Starts the particle system and begins to emit
  67467. * @param delay defines the delay in milliseconds before starting the system (this.startDelay by default)
  67468. */
  67469. GPUParticleSystem.prototype.start = function (delay) {
  67470. var _this = this;
  67471. if (delay === void 0) { delay = this.startDelay; }
  67472. if (!this.targetStopDuration && this._hasTargetStopDurationDependantGradient()) {
  67473. throw "Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set";
  67474. }
  67475. if (delay) {
  67476. setTimeout(function () {
  67477. _this.start(0);
  67478. }, delay);
  67479. return;
  67480. }
  67481. this._started = true;
  67482. this._stopped = false;
  67483. this._preWarmDone = false;
  67484. // Animations
  67485. if (this.beginAnimationOnStart && this.animations && this.animations.length > 0) {
  67486. this.getScene().beginAnimation(this, this.beginAnimationFrom, this.beginAnimationTo, this.beginAnimationLoop);
  67487. }
  67488. };
  67489. /**
  67490. * Stops the particle system.
  67491. */
  67492. GPUParticleSystem.prototype.stop = function () {
  67493. this._stopped = true;
  67494. };
  67495. /**
  67496. * Remove all active particles
  67497. */
  67498. GPUParticleSystem.prototype.reset = function () {
  67499. this._releaseBuffers();
  67500. this._releaseVAOs();
  67501. this._currentActiveCount = 0;
  67502. this._targetIndex = 0;
  67503. };
  67504. /**
  67505. * Returns the string "GPUParticleSystem"
  67506. * @returns a string containing the class name
  67507. */
  67508. GPUParticleSystem.prototype.getClassName = function () {
  67509. return "GPUParticleSystem";
  67510. };
  67511. GPUParticleSystem.prototype._removeGradientAndTexture = function (gradient, gradients, texture) {
  67512. _super.prototype._removeGradientAndTexture.call(this, gradient, gradients, texture);
  67513. this._releaseBuffers();
  67514. return this;
  67515. };
  67516. /**
  67517. * Adds a new color gradient
  67518. * @param gradient defines the gradient to use (between 0 and 1)
  67519. * @param color1 defines the color to affect to the specified gradient
  67520. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  67521. * @returns the current particle system
  67522. */
  67523. GPUParticleSystem.prototype.addColorGradient = function (gradient, color1, color2) {
  67524. if (!this._colorGradients) {
  67525. this._colorGradients = [];
  67526. }
  67527. var colorGradient = new BABYLON.ColorGradient();
  67528. colorGradient.gradient = gradient;
  67529. colorGradient.color1 = color1;
  67530. this._colorGradients.push(colorGradient);
  67531. this._colorGradients.sort(function (a, b) {
  67532. if (a.gradient < b.gradient) {
  67533. return -1;
  67534. }
  67535. else if (a.gradient > b.gradient) {
  67536. return 1;
  67537. }
  67538. return 0;
  67539. });
  67540. if (this._colorGradientsTexture) {
  67541. this._colorGradientsTexture.dispose();
  67542. this._colorGradientsTexture = null;
  67543. }
  67544. this._releaseBuffers();
  67545. return this;
  67546. };
  67547. /**
  67548. * Remove a specific color gradient
  67549. * @param gradient defines the gradient to remove
  67550. * @returns the current particle system
  67551. */
  67552. GPUParticleSystem.prototype.removeColorGradient = function (gradient) {
  67553. this._removeGradientAndTexture(gradient, this._colorGradients, this._colorGradientsTexture);
  67554. this._colorGradientsTexture = null;
  67555. return this;
  67556. };
  67557. GPUParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor) {
  67558. var valueGradient = new BABYLON.FactorGradient();
  67559. valueGradient.gradient = gradient;
  67560. valueGradient.factor1 = factor;
  67561. factorGradients.push(valueGradient);
  67562. factorGradients.sort(function (a, b) {
  67563. if (a.gradient < b.gradient) {
  67564. return -1;
  67565. }
  67566. else if (a.gradient > b.gradient) {
  67567. return 1;
  67568. }
  67569. return 0;
  67570. });
  67571. this._releaseBuffers();
  67572. };
  67573. /**
  67574. * Adds a new size gradient
  67575. * @param gradient defines the gradient to use (between 0 and 1)
  67576. * @param factor defines the size factor to affect to the specified gradient
  67577. * @returns the current particle system
  67578. */
  67579. GPUParticleSystem.prototype.addSizeGradient = function (gradient, factor) {
  67580. if (!this._sizeGradients) {
  67581. this._sizeGradients = [];
  67582. }
  67583. this._addFactorGradient(this._sizeGradients, gradient, factor);
  67584. if (this._sizeGradientsTexture) {
  67585. this._sizeGradientsTexture.dispose();
  67586. this._sizeGradientsTexture = null;
  67587. }
  67588. this._releaseBuffers();
  67589. return this;
  67590. };
  67591. /**
  67592. * Remove a specific size gradient
  67593. * @param gradient defines the gradient to remove
  67594. * @returns the current particle system
  67595. */
  67596. GPUParticleSystem.prototype.removeSizeGradient = function (gradient) {
  67597. this._removeGradientAndTexture(gradient, this._sizeGradients, this._sizeGradientsTexture);
  67598. this._sizeGradientsTexture = null;
  67599. return this;
  67600. };
  67601. /**
  67602. * Adds a new angular speed gradient
  67603. * @param gradient defines the gradient to use (between 0 and 1)
  67604. * @param factor defines the angular speed to affect to the specified gradient
  67605. * @returns the current particle system
  67606. */
  67607. GPUParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor) {
  67608. if (!this._angularSpeedGradients) {
  67609. this._angularSpeedGradients = [];
  67610. }
  67611. this._addFactorGradient(this._angularSpeedGradients, gradient, factor);
  67612. if (this._angularSpeedGradientsTexture) {
  67613. this._angularSpeedGradientsTexture.dispose();
  67614. this._angularSpeedGradientsTexture = null;
  67615. }
  67616. this._releaseBuffers();
  67617. return this;
  67618. };
  67619. /**
  67620. * Remove a specific angular speed gradient
  67621. * @param gradient defines the gradient to remove
  67622. * @returns the current particle system
  67623. */
  67624. GPUParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  67625. this._removeGradientAndTexture(gradient, this._angularSpeedGradients, this._angularSpeedGradientsTexture);
  67626. this._angularSpeedGradientsTexture = null;
  67627. return this;
  67628. };
  67629. /**
  67630. * Adds a new velocity gradient
  67631. * @param gradient defines the gradient to use (between 0 and 1)
  67632. * @param factor defines the velocity to affect to the specified gradient
  67633. * @returns the current particle system
  67634. */
  67635. GPUParticleSystem.prototype.addVelocityGradient = function (gradient, factor) {
  67636. if (!this._velocityGradients) {
  67637. this._velocityGradients = [];
  67638. }
  67639. this._addFactorGradient(this._velocityGradients, gradient, factor);
  67640. if (this._velocityGradientsTexture) {
  67641. this._velocityGradientsTexture.dispose();
  67642. this._velocityGradientsTexture = null;
  67643. }
  67644. this._releaseBuffers();
  67645. return this;
  67646. };
  67647. /**
  67648. * Remove a specific velocity gradient
  67649. * @param gradient defines the gradient to remove
  67650. * @returns the current particle system
  67651. */
  67652. GPUParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  67653. this._removeGradientAndTexture(gradient, this._velocityGradients, this._velocityGradientsTexture);
  67654. this._velocityGradientsTexture = null;
  67655. return this;
  67656. };
  67657. /**
  67658. * Adds a new limit velocity gradient
  67659. * @param gradient defines the gradient to use (between 0 and 1)
  67660. * @param factor defines the limit velocity value to affect to the specified gradient
  67661. * @returns the current particle system
  67662. */
  67663. GPUParticleSystem.prototype.addLimitVelocityGradient = function (gradient, factor) {
  67664. if (!this._limitVelocityGradients) {
  67665. this._limitVelocityGradients = [];
  67666. }
  67667. this._addFactorGradient(this._limitVelocityGradients, gradient, factor);
  67668. if (this._limitVelocityGradientsTexture) {
  67669. this._limitVelocityGradientsTexture.dispose();
  67670. this._limitVelocityGradientsTexture = null;
  67671. }
  67672. this._releaseBuffers();
  67673. return this;
  67674. };
  67675. /**
  67676. * Remove a specific limit velocity gradient
  67677. * @param gradient defines the gradient to remove
  67678. * @returns the current particle system
  67679. */
  67680. GPUParticleSystem.prototype.removeLimitVelocityGradient = function (gradient) {
  67681. this._removeGradientAndTexture(gradient, this._limitVelocityGradients, this._limitVelocityGradientsTexture);
  67682. this._limitVelocityGradientsTexture = null;
  67683. return this;
  67684. };
  67685. /**
  67686. * Adds a new drag gradient
  67687. * @param gradient defines the gradient to use (between 0 and 1)
  67688. * @param factor defines the drag value to affect to the specified gradient
  67689. * @returns the current particle system
  67690. */
  67691. GPUParticleSystem.prototype.addDragGradient = function (gradient, factor) {
  67692. if (!this._dragGradients) {
  67693. this._dragGradients = [];
  67694. }
  67695. this._addFactorGradient(this._dragGradients, gradient, factor);
  67696. if (this._dragGradientsTexture) {
  67697. this._dragGradientsTexture.dispose();
  67698. this._dragGradientsTexture = null;
  67699. }
  67700. this._releaseBuffers();
  67701. return this;
  67702. };
  67703. /**
  67704. * Remove a specific drag gradient
  67705. * @param gradient defines the gradient to remove
  67706. * @returns the current particle system
  67707. */
  67708. GPUParticleSystem.prototype.removeDragGradient = function (gradient) {
  67709. this._removeGradientAndTexture(gradient, this._dragGradients, this._dragGradientsTexture);
  67710. this._dragGradientsTexture = null;
  67711. return this;
  67712. };
  67713. /**
  67714. * Not supported by GPUParticleSystem
  67715. * @param gradient defines the gradient to use (between 0 and 1)
  67716. * @param factor defines the emit rate value to affect to the specified gradient
  67717. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  67718. * @returns the current particle system
  67719. */
  67720. GPUParticleSystem.prototype.addEmitRateGradient = function (gradient, factor, factor2) {
  67721. // Do nothing as emit rate is not supported by GPUParticleSystem
  67722. return this;
  67723. };
  67724. /**
  67725. * Not supported by GPUParticleSystem
  67726. * @param gradient defines the gradient to remove
  67727. * @returns the current particle system
  67728. */
  67729. GPUParticleSystem.prototype.removeEmitRateGradient = function (gradient) {
  67730. // Do nothing as emit rate is not supported by GPUParticleSystem
  67731. return this;
  67732. };
  67733. /**
  67734. * Not supported by GPUParticleSystem
  67735. * @param gradient defines the gradient to use (between 0 and 1)
  67736. * @param factor defines the start size value to affect to the specified gradient
  67737. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  67738. * @returns the current particle system
  67739. */
  67740. GPUParticleSystem.prototype.addStartSizeGradient = function (gradient, factor, factor2) {
  67741. // Do nothing as start size is not supported by GPUParticleSystem
  67742. return this;
  67743. };
  67744. /**
  67745. * Not supported by GPUParticleSystem
  67746. * @param gradient defines the gradient to remove
  67747. * @returns the current particle system
  67748. */
  67749. GPUParticleSystem.prototype.removeStartSizeGradient = function (gradient) {
  67750. // Do nothing as start size is not supported by GPUParticleSystem
  67751. return this;
  67752. };
  67753. /**
  67754. * Not supported by GPUParticleSystem
  67755. * @param gradient defines the gradient to use (between 0 and 1)
  67756. * @param min defines the color remap minimal range
  67757. * @param max defines the color remap maximal range
  67758. * @returns the current particle system
  67759. */
  67760. GPUParticleSystem.prototype.addColorRemapGradient = function (gradient, min, max) {
  67761. // Do nothing as start size is not supported by GPUParticleSystem
  67762. return this;
  67763. };
  67764. /**
  67765. * Not supported by GPUParticleSystem
  67766. * @param gradient defines the gradient to remove
  67767. * @returns the current particle system
  67768. */
  67769. GPUParticleSystem.prototype.removeColorRemapGradient = function (gradient) {
  67770. // Do nothing as start size is not supported by GPUParticleSystem
  67771. return this;
  67772. };
  67773. /**
  67774. * Not supported by GPUParticleSystem
  67775. * @param gradient defines the gradient to use (between 0 and 1)
  67776. * @param min defines the alpha remap minimal range
  67777. * @param max defines the alpha remap maximal range
  67778. * @returns the current particle system
  67779. */
  67780. GPUParticleSystem.prototype.addAlphaRemapGradient = function (gradient, min, max) {
  67781. // Do nothing as start size is not supported by GPUParticleSystem
  67782. return this;
  67783. };
  67784. /**
  67785. * Not supported by GPUParticleSystem
  67786. * @param gradient defines the gradient to remove
  67787. * @returns the current particle system
  67788. */
  67789. GPUParticleSystem.prototype.removeAlphaRemapGradient = function (gradient) {
  67790. // Do nothing as start size is not supported by GPUParticleSystem
  67791. return this;
  67792. };
  67793. /**
  67794. * Not supported by GPUParticleSystem
  67795. * @param gradient defines the gradient to use (between 0 and 1)
  67796. * @param color defines the color to affect to the specified gradient
  67797. * @returns the current particle system
  67798. */
  67799. GPUParticleSystem.prototype.addRampGradient = function (gradient, color) {
  67800. //Not supported by GPUParticleSystem
  67801. return this;
  67802. };
  67803. /**
  67804. * Not supported by GPUParticleSystem
  67805. * @param gradient defines the gradient to remove
  67806. * @returns the current particle system
  67807. */
  67808. GPUParticleSystem.prototype.removeRampGradient = function (gradient) {
  67809. //Not supported by GPUParticleSystem
  67810. return this;
  67811. };
  67812. /**
  67813. * Not supported by GPUParticleSystem
  67814. * @returns the list of ramp gradients
  67815. */
  67816. GPUParticleSystem.prototype.getRampGradients = function () {
  67817. return null;
  67818. };
  67819. Object.defineProperty(GPUParticleSystem.prototype, "useRampGradients", {
  67820. /**
  67821. * Not supported by GPUParticleSystem
  67822. * Gets or sets a boolean indicating that ramp gradients must be used
  67823. * @see http://doc.babylonjs.com/babylon101/particles#ramp-gradients
  67824. */
  67825. get: function () {
  67826. //Not supported by GPUParticleSystem
  67827. return false;
  67828. },
  67829. set: function (value) {
  67830. //Not supported by GPUParticleSystem
  67831. },
  67832. enumerable: true,
  67833. configurable: true
  67834. });
  67835. /**
  67836. * Not supported by GPUParticleSystem
  67837. * @param gradient defines the gradient to use (between 0 and 1)
  67838. * @param factor defines the life time factor to affect to the specified gradient
  67839. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  67840. * @returns the current particle system
  67841. */
  67842. GPUParticleSystem.prototype.addLifeTimeGradient = function (gradient, factor, factor2) {
  67843. //Not supported by GPUParticleSystem
  67844. return this;
  67845. };
  67846. /**
  67847. * Not supported by GPUParticleSystem
  67848. * @param gradient defines the gradient to remove
  67849. * @returns the current particle system
  67850. */
  67851. GPUParticleSystem.prototype.removeLifeTimeGradient = function (gradient) {
  67852. //Not supported by GPUParticleSystem
  67853. return this;
  67854. };
  67855. GPUParticleSystem.prototype._reset = function () {
  67856. this._releaseBuffers();
  67857. };
  67858. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  67859. var updateVertexBuffers = {};
  67860. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  67861. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  67862. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  67863. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 4);
  67864. updateVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3);
  67865. var offset = 12;
  67866. if (!this._colorGradientsTexture) {
  67867. updateVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4);
  67868. offset += 4;
  67869. }
  67870. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", offset, 3);
  67871. offset += 3;
  67872. if (!this._isBillboardBased) {
  67873. updateVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3);
  67874. offset += 3;
  67875. }
  67876. if (this._angularSpeedGradientsTexture) {
  67877. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1);
  67878. offset += 1;
  67879. }
  67880. else {
  67881. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 2);
  67882. offset += 2;
  67883. }
  67884. if (this._isAnimationSheetEnabled) {
  67885. updateVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1);
  67886. offset += 1;
  67887. if (this.spriteRandomStartCell) {
  67888. updateVertexBuffers["cellStartOffset"] = source.createVertexBuffer("cellStartOffset", offset, 1);
  67889. offset += 1;
  67890. }
  67891. }
  67892. if (this.noiseTexture) {
  67893. updateVertexBuffers["noiseCoordinates1"] = source.createVertexBuffer("noiseCoordinates1", offset, 3);
  67894. offset += 3;
  67895. updateVertexBuffers["noiseCoordinates2"] = source.createVertexBuffer("noiseCoordinates2", offset, 3);
  67896. offset += 3;
  67897. }
  67898. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  67899. this._engine.bindArrayBuffer(null);
  67900. return vao;
  67901. };
  67902. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  67903. var renderVertexBuffers = {};
  67904. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  67905. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  67906. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  67907. renderVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3, this._attributesStrideSize, true);
  67908. var offset = 12;
  67909. if (!this._colorGradientsTexture) {
  67910. renderVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4, this._attributesStrideSize, true);
  67911. offset += 4;
  67912. }
  67913. if (this.billboardMode === BABYLON.ParticleSystem.BILLBOARDMODE_STRETCHED) {
  67914. renderVertexBuffers["direction"] = source.createVertexBuffer("direction", offset, 3, this._attributesStrideSize, true);
  67915. }
  67916. offset += 3; // Direction
  67917. if (!this._isBillboardBased) {
  67918. renderVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3, this._attributesStrideSize, true);
  67919. offset += 3;
  67920. }
  67921. renderVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1, this._attributesStrideSize, true);
  67922. if (this._angularSpeedGradientsTexture) {
  67923. offset++;
  67924. }
  67925. else {
  67926. offset += 2;
  67927. }
  67928. if (this._isAnimationSheetEnabled) {
  67929. renderVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1, this._attributesStrideSize, true);
  67930. offset += 1;
  67931. if (this.spriteRandomStartCell) {
  67932. renderVertexBuffers["cellStartOffset"] = source.createVertexBuffer("cellStartOffset", offset, 1, this._attributesStrideSize, true);
  67933. offset += 1;
  67934. }
  67935. }
  67936. if (this.noiseTexture) {
  67937. renderVertexBuffers["noiseCoordinates1"] = source.createVertexBuffer("noiseCoordinates1", offset, 3, this._attributesStrideSize, true);
  67938. offset += 3;
  67939. renderVertexBuffers["noiseCoordinates2"] = source.createVertexBuffer("noiseCoordinates2", offset, 3, this._attributesStrideSize, true);
  67940. offset += 3;
  67941. }
  67942. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  67943. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  67944. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  67945. this._engine.bindArrayBuffer(null);
  67946. return vao;
  67947. };
  67948. GPUParticleSystem.prototype._initialize = function (force) {
  67949. if (force === void 0) { force = false; }
  67950. if (this._buffer0 && !force) {
  67951. return;
  67952. }
  67953. var engine = this._scene.getEngine();
  67954. var data = new Array();
  67955. this._attributesStrideSize = 21;
  67956. this._targetIndex = 0;
  67957. if (!this.isBillboardBased) {
  67958. this._attributesStrideSize += 3;
  67959. }
  67960. if (this._colorGradientsTexture) {
  67961. this._attributesStrideSize -= 4;
  67962. }
  67963. if (this._angularSpeedGradientsTexture) {
  67964. this._attributesStrideSize -= 1;
  67965. }
  67966. if (this._isAnimationSheetEnabled) {
  67967. this._attributesStrideSize += 1;
  67968. if (this.spriteRandomStartCell) {
  67969. this._attributesStrideSize += 1;
  67970. }
  67971. }
  67972. if (this.noiseTexture) {
  67973. this._attributesStrideSize += 6;
  67974. }
  67975. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  67976. // position
  67977. data.push(0.0);
  67978. data.push(0.0);
  67979. data.push(0.0);
  67980. // Age and life
  67981. data.push(0.0); // create the particle as a dead one to create a new one at start
  67982. data.push(0.0);
  67983. // Seed
  67984. data.push(Math.random());
  67985. data.push(Math.random());
  67986. data.push(Math.random());
  67987. data.push(Math.random());
  67988. // Size
  67989. data.push(0.0);
  67990. data.push(0.0);
  67991. data.push(0.0);
  67992. if (!this._colorGradientsTexture) {
  67993. // color
  67994. data.push(0.0);
  67995. data.push(0.0);
  67996. data.push(0.0);
  67997. data.push(0.0);
  67998. }
  67999. // direction
  68000. data.push(0.0);
  68001. data.push(0.0);
  68002. data.push(0.0);
  68003. if (!this.isBillboardBased) {
  68004. // initialDirection
  68005. data.push(0.0);
  68006. data.push(0.0);
  68007. data.push(0.0);
  68008. }
  68009. // angle
  68010. data.push(0.0);
  68011. if (!this._angularSpeedGradientsTexture) {
  68012. data.push(0.0);
  68013. }
  68014. if (this._isAnimationSheetEnabled) {
  68015. data.push(0.0);
  68016. if (this.spriteRandomStartCell) {
  68017. data.push(0.0);
  68018. }
  68019. }
  68020. if (this.noiseTexture) { // Random coordinates for reading into noise texture
  68021. data.push(Math.random());
  68022. data.push(Math.random());
  68023. data.push(Math.random());
  68024. data.push(Math.random());
  68025. data.push(Math.random());
  68026. data.push(Math.random());
  68027. }
  68028. }
  68029. // Sprite data
  68030. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  68031. -0.5, 0.5, 0, 1,
  68032. -0.5, -0.5, 0, 0,
  68033. 0.5, -0.5, 1, 0]);
  68034. // Buffers
  68035. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  68036. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  68037. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  68038. // Update VAO
  68039. this._updateVAO = [];
  68040. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  68041. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  68042. // Render VAO
  68043. this._renderVAO = [];
  68044. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  68045. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  68046. // Links
  68047. this._sourceBuffer = this._buffer0;
  68048. this._targetBuffer = this._buffer1;
  68049. };
  68050. /** @hidden */
  68051. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  68052. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  68053. if (this._isBillboardBased) {
  68054. defines += "\n#define BILLBOARD";
  68055. }
  68056. if (this._colorGradientsTexture) {
  68057. defines += "\n#define COLORGRADIENTS";
  68058. }
  68059. if (this._sizeGradientsTexture) {
  68060. defines += "\n#define SIZEGRADIENTS";
  68061. }
  68062. if (this._angularSpeedGradientsTexture) {
  68063. defines += "\n#define ANGULARSPEEDGRADIENTS";
  68064. }
  68065. if (this._velocityGradientsTexture) {
  68066. defines += "\n#define VELOCITYGRADIENTS";
  68067. }
  68068. if (this._limitVelocityGradientsTexture) {
  68069. defines += "\n#define LIMITVELOCITYGRADIENTS";
  68070. }
  68071. if (this._dragGradientsTexture) {
  68072. defines += "\n#define DRAGGRADIENTS";
  68073. }
  68074. if (this.isAnimationSheetEnabled) {
  68075. defines += "\n#define ANIMATESHEET";
  68076. if (this.spriteRandomStartCell) {
  68077. defines += "\n#define ANIMATESHEETRANDOMSTART";
  68078. }
  68079. }
  68080. if (this.noiseTexture) {
  68081. defines += "\n#define NOISE";
  68082. }
  68083. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  68084. return;
  68085. }
  68086. this._updateEffectOptions.transformFeedbackVaryings = ["outPosition", "outAge", "outLife", "outSeed", "outSize"];
  68087. if (!this._colorGradientsTexture) {
  68088. this._updateEffectOptions.transformFeedbackVaryings.push("outColor");
  68089. }
  68090. this._updateEffectOptions.transformFeedbackVaryings.push("outDirection");
  68091. if (!this._isBillboardBased) {
  68092. this._updateEffectOptions.transformFeedbackVaryings.push("outInitialDirection");
  68093. }
  68094. this._updateEffectOptions.transformFeedbackVaryings.push("outAngle");
  68095. if (this.isAnimationSheetEnabled) {
  68096. this._updateEffectOptions.transformFeedbackVaryings.push("outCellIndex");
  68097. if (this.spriteRandomStartCell) {
  68098. this._updateEffectOptions.transformFeedbackVaryings.push("outCellStartOffset");
  68099. }
  68100. }
  68101. if (this.noiseTexture) {
  68102. this._updateEffectOptions.transformFeedbackVaryings.push("outNoiseCoordinates1");
  68103. this._updateEffectOptions.transformFeedbackVaryings.push("outNoiseCoordinates2");
  68104. }
  68105. this._updateEffectOptions.defines = defines;
  68106. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  68107. };
  68108. /** @hidden */
  68109. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  68110. var defines = "";
  68111. if (this._scene.clipPlane) {
  68112. defines = "\n#define CLIPPLANE";
  68113. }
  68114. if (this._scene.clipPlane2) {
  68115. defines = "\n#define CLIPPLANE2";
  68116. }
  68117. if (this._scene.clipPlane3) {
  68118. defines = "\n#define CLIPPLANE3";
  68119. }
  68120. if (this._scene.clipPlane4) {
  68121. defines = "\n#define CLIPPLANE4";
  68122. }
  68123. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_MULTIPLY) {
  68124. defines = "\n#define BLENDMULTIPLYMODE";
  68125. }
  68126. if (this._isBillboardBased) {
  68127. defines += "\n#define BILLBOARD";
  68128. switch (this.billboardMode) {
  68129. case BABYLON.ParticleSystem.BILLBOARDMODE_Y:
  68130. defines += "\n#define BILLBOARDY";
  68131. break;
  68132. case BABYLON.ParticleSystem.BILLBOARDMODE_STRETCHED:
  68133. defines += "\n#define BILLBOARDSTRETCHED";
  68134. break;
  68135. case BABYLON.ParticleSystem.BILLBOARDMODE_ALL:
  68136. default:
  68137. break;
  68138. }
  68139. }
  68140. if (this._colorGradientsTexture) {
  68141. defines += "\n#define COLORGRADIENTS";
  68142. }
  68143. if (this.isAnimationSheetEnabled) {
  68144. defines += "\n#define ANIMATESHEET";
  68145. }
  68146. if (this._imageProcessingConfiguration) {
  68147. this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines);
  68148. defines += "\n" + this._imageProcessingConfigurationDefines.toString();
  68149. }
  68150. if (this._renderEffect && this._renderEffect.defines === defines) {
  68151. return;
  68152. }
  68153. var uniforms = ["view", "projection", "colorDead", "invView", "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "sheetInfos", "translationPivot", "eyePosition"];
  68154. var samplers = ["textureSampler", "colorGradientSampler"];
  68155. if (BABYLON.ImageProcessingConfiguration) {
  68156. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._imageProcessingConfigurationDefines);
  68157. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._imageProcessingConfigurationDefines);
  68158. }
  68159. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv", "direction", "initialDirection", "angle", "cellIndex"], uniforms, samplers, this._scene.getEngine(), defines);
  68160. };
  68161. /**
  68162. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  68163. * @param preWarm defines if we are in the pre-warmimg phase
  68164. */
  68165. GPUParticleSystem.prototype.animate = function (preWarm) {
  68166. if (preWarm === void 0) { preWarm = false; }
  68167. this._timeDelta = this.updateSpeed * (preWarm ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  68168. this._actualFrame += this._timeDelta;
  68169. if (!this._stopped) {
  68170. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  68171. this.stop();
  68172. }
  68173. }
  68174. };
  68175. GPUParticleSystem.prototype._createFactorGradientTexture = function (factorGradients, textureName) {
  68176. var texture = this[textureName];
  68177. if (!factorGradients || !factorGradients.length || texture) {
  68178. return;
  68179. }
  68180. var data = new Float32Array(this._rawTextureWidth);
  68181. for (var x = 0; x < this._rawTextureWidth; x++) {
  68182. var ratio = x / this._rawTextureWidth;
  68183. BABYLON.Tools.GetCurrentGradient(ratio, factorGradients, function (currentGradient, nextGradient, scale) {
  68184. data[x] = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  68185. });
  68186. }
  68187. this[textureName] = BABYLON.RawTexture.CreateRTexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  68188. };
  68189. GPUParticleSystem.prototype._createSizeGradientTexture = function () {
  68190. this._createFactorGradientTexture(this._sizeGradients, "_sizeGradientsTexture");
  68191. };
  68192. GPUParticleSystem.prototype._createAngularSpeedGradientTexture = function () {
  68193. this._createFactorGradientTexture(this._angularSpeedGradients, "_angularSpeedGradientsTexture");
  68194. };
  68195. GPUParticleSystem.prototype._createVelocityGradientTexture = function () {
  68196. this._createFactorGradientTexture(this._velocityGradients, "_velocityGradientsTexture");
  68197. };
  68198. GPUParticleSystem.prototype._createLimitVelocityGradientTexture = function () {
  68199. this._createFactorGradientTexture(this._limitVelocityGradients, "_limitVelocityGradientsTexture");
  68200. };
  68201. GPUParticleSystem.prototype._createDragGradientTexture = function () {
  68202. this._createFactorGradientTexture(this._dragGradients, "_dragGradientsTexture");
  68203. };
  68204. GPUParticleSystem.prototype._createColorGradientTexture = function () {
  68205. if (!this._colorGradients || !this._colorGradients.length || this._colorGradientsTexture) {
  68206. return;
  68207. }
  68208. var data = new Uint8Array(this._rawTextureWidth * 4);
  68209. var tmpColor = BABYLON.Tmp.Color4[0];
  68210. for (var x = 0; x < this._rawTextureWidth; x++) {
  68211. var ratio = x / this._rawTextureWidth;
  68212. BABYLON.Tools.GetCurrentGradient(ratio, this._colorGradients, function (currentGradient, nextGradient, scale) {
  68213. BABYLON.Color4.LerpToRef(currentGradient.color1, nextGradient.color1, scale, tmpColor);
  68214. data[x * 4] = tmpColor.r * 255;
  68215. data[x * 4 + 1] = tmpColor.g * 255;
  68216. data[x * 4 + 2] = tmpColor.b * 255;
  68217. data[x * 4 + 3] = tmpColor.a * 255;
  68218. });
  68219. }
  68220. this._colorGradientsTexture = BABYLON.RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  68221. };
  68222. /**
  68223. * Renders the particle system in its current state
  68224. * @param preWarm defines if the system should only update the particles but not render them
  68225. * @returns the current number of particles
  68226. */
  68227. GPUParticleSystem.prototype.render = function (preWarm) {
  68228. if (preWarm === void 0) { preWarm = false; }
  68229. if (!this._started) {
  68230. return 0;
  68231. }
  68232. this._createColorGradientTexture();
  68233. this._createSizeGradientTexture();
  68234. this._createAngularSpeedGradientTexture();
  68235. this._createVelocityGradientTexture();
  68236. this._createLimitVelocityGradientTexture();
  68237. this._createDragGradientTexture();
  68238. this._recreateUpdateEffect();
  68239. this._recreateRenderEffect();
  68240. if (!this.isReady()) {
  68241. return 0;
  68242. }
  68243. if (!preWarm) {
  68244. if (!this._preWarmDone && this.preWarmCycles) {
  68245. for (var index = 0; index < this.preWarmCycles; index++) {
  68246. this.animate(true);
  68247. this.render(true);
  68248. }
  68249. this._preWarmDone = true;
  68250. }
  68251. if (this._currentRenderId === this._scene.getFrameId()) {
  68252. return 0;
  68253. }
  68254. this._currentRenderId = this._scene.getFrameId();
  68255. }
  68256. // Get everything ready to render
  68257. this._initialize();
  68258. this._accumulatedCount += this.emitRate * this._timeDelta;
  68259. if (this._accumulatedCount > 1) {
  68260. var intPart = this._accumulatedCount | 0;
  68261. this._accumulatedCount -= intPart;
  68262. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + intPart);
  68263. }
  68264. if (!this._currentActiveCount) {
  68265. return 0;
  68266. }
  68267. // Enable update effect
  68268. this._engine.enableEffect(this._updateEffect);
  68269. this._engine.setState(false);
  68270. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  68271. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  68272. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  68273. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  68274. this._updateEffect.setTexture("randomSampler2", this._randomTexture2);
  68275. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  68276. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  68277. if (!this._colorGradientsTexture) {
  68278. this._updateEffect.setDirectColor4("color1", this.color1);
  68279. this._updateEffect.setDirectColor4("color2", this.color2);
  68280. }
  68281. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  68282. this._updateEffect.setFloat4("scaleRange", this.minScaleX, this.maxScaleX, this.minScaleY, this.maxScaleY);
  68283. this._updateEffect.setFloat4("angleRange", this.minAngularSpeed, this.maxAngularSpeed, this.minInitialRotation, this.maxInitialRotation);
  68284. this._updateEffect.setVector3("gravity", this.gravity);
  68285. if (this._sizeGradientsTexture) {
  68286. this._updateEffect.setTexture("sizeGradientSampler", this._sizeGradientsTexture);
  68287. }
  68288. if (this._angularSpeedGradientsTexture) {
  68289. this._updateEffect.setTexture("angularSpeedGradientSampler", this._angularSpeedGradientsTexture);
  68290. }
  68291. if (this._velocityGradientsTexture) {
  68292. this._updateEffect.setTexture("velocityGradientSampler", this._velocityGradientsTexture);
  68293. }
  68294. if (this._limitVelocityGradientsTexture) {
  68295. this._updateEffect.setTexture("limitVelocityGradientSampler", this._limitVelocityGradientsTexture);
  68296. this._updateEffect.setFloat("limitVelocityDamping", this.limitVelocityDamping);
  68297. }
  68298. if (this._dragGradientsTexture) {
  68299. this._updateEffect.setTexture("dragGradientSampler", this._dragGradientsTexture);
  68300. }
  68301. if (this.particleEmitterType) {
  68302. this.particleEmitterType.applyToShader(this._updateEffect);
  68303. }
  68304. if (this._isAnimationSheetEnabled) {
  68305. this._updateEffect.setFloat3("cellInfos", this.startSpriteCellID, this.endSpriteCellID, this.spriteCellChangeSpeed);
  68306. }
  68307. if (this.noiseTexture) {
  68308. this._updateEffect.setTexture("noiseSampler", this.noiseTexture);
  68309. this._updateEffect.setVector3("noiseStrength", this.noiseStrength);
  68310. }
  68311. var emitterWM;
  68312. if (this.emitter.position) {
  68313. var emitterMesh = this.emitter;
  68314. emitterWM = emitterMesh.getWorldMatrix();
  68315. }
  68316. else {
  68317. var emitterPosition = this.emitter;
  68318. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  68319. }
  68320. this._updateEffect.setMatrix("emitterWM", emitterWM);
  68321. // Bind source VAO
  68322. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  68323. // Update
  68324. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  68325. this._engine.setRasterizerState(false);
  68326. this._engine.beginTransformFeedback(true);
  68327. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  68328. this._engine.endTransformFeedback();
  68329. this._engine.setRasterizerState(true);
  68330. this._engine.bindTransformFeedbackBuffer(null);
  68331. if (!preWarm) {
  68332. // Enable render effect
  68333. this._engine.enableEffect(this._renderEffect);
  68334. var viewMatrix = this._scene.getViewMatrix();
  68335. this._renderEffect.setMatrix("view", viewMatrix);
  68336. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  68337. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  68338. this._renderEffect.setVector2("translationPivot", this.translationPivot);
  68339. if (this._colorGradientsTexture) {
  68340. this._renderEffect.setTexture("colorGradientSampler", this._colorGradientsTexture);
  68341. }
  68342. else {
  68343. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  68344. }
  68345. if (this._isAnimationSheetEnabled && this.particleTexture) {
  68346. var baseSize = this.particleTexture.getBaseSize();
  68347. this._renderEffect.setFloat3("sheetInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  68348. }
  68349. if (this._isBillboardBased) {
  68350. var camera = this._scene.activeCamera;
  68351. this._renderEffect.setVector3("eyePosition", camera.globalPosition);
  68352. }
  68353. if (this._scene.clipPlane || this._scene.clipPlane2 || this._scene.clipPlane3 || this._scene.clipPlane4) {
  68354. var invView = viewMatrix.clone();
  68355. invView.invert();
  68356. this._renderEffect.setMatrix("invView", invView);
  68357. BABYLON.MaterialHelper.BindClipPlane(this._renderEffect, this._scene);
  68358. }
  68359. // image processing
  68360. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  68361. this._imageProcessingConfiguration.bind(this._renderEffect);
  68362. }
  68363. // Draw order
  68364. switch (this.blendMode) {
  68365. case BABYLON.ParticleSystem.BLENDMODE_ADD:
  68366. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  68367. break;
  68368. case BABYLON.ParticleSystem.BLENDMODE_ONEONE:
  68369. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  68370. break;
  68371. case BABYLON.ParticleSystem.BLENDMODE_STANDARD:
  68372. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  68373. break;
  68374. case BABYLON.ParticleSystem.BLENDMODE_MULTIPLY:
  68375. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_MULTIPLY);
  68376. break;
  68377. }
  68378. if (this.forceDepthWrite) {
  68379. this._engine.setDepthWrite(true);
  68380. }
  68381. // Bind source VAO
  68382. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  68383. // Render
  68384. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  68385. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  68386. }
  68387. // Switch VAOs
  68388. this._targetIndex++;
  68389. if (this._targetIndex === 2) {
  68390. this._targetIndex = 0;
  68391. }
  68392. // Switch buffers
  68393. var tmpBuffer = this._sourceBuffer;
  68394. this._sourceBuffer = this._targetBuffer;
  68395. this._targetBuffer = tmpBuffer;
  68396. return this._currentActiveCount;
  68397. };
  68398. /**
  68399. * Rebuilds the particle system
  68400. */
  68401. GPUParticleSystem.prototype.rebuild = function () {
  68402. this._initialize(true);
  68403. };
  68404. GPUParticleSystem.prototype._releaseBuffers = function () {
  68405. if (this._buffer0) {
  68406. this._buffer0.dispose();
  68407. this._buffer0 = null;
  68408. }
  68409. if (this._buffer1) {
  68410. this._buffer1.dispose();
  68411. this._buffer1 = null;
  68412. }
  68413. if (this._spriteBuffer) {
  68414. this._spriteBuffer.dispose();
  68415. this._spriteBuffer = null;
  68416. }
  68417. };
  68418. GPUParticleSystem.prototype._releaseVAOs = function () {
  68419. if (!this._updateVAO) {
  68420. return;
  68421. }
  68422. for (var index = 0; index < this._updateVAO.length; index++) {
  68423. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  68424. }
  68425. this._updateVAO = [];
  68426. for (var index = 0; index < this._renderVAO.length; index++) {
  68427. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  68428. }
  68429. this._renderVAO = [];
  68430. };
  68431. /**
  68432. * Disposes the particle system and free the associated resources
  68433. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  68434. */
  68435. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  68436. if (disposeTexture === void 0) { disposeTexture = true; }
  68437. var index = this._scene.particleSystems.indexOf(this);
  68438. if (index > -1) {
  68439. this._scene.particleSystems.splice(index, 1);
  68440. }
  68441. this._releaseBuffers();
  68442. this._releaseVAOs();
  68443. if (this._colorGradientsTexture) {
  68444. this._colorGradientsTexture.dispose();
  68445. this._colorGradientsTexture = null;
  68446. }
  68447. if (this._sizeGradientsTexture) {
  68448. this._sizeGradientsTexture.dispose();
  68449. this._sizeGradientsTexture = null;
  68450. }
  68451. if (this._angularSpeedGradientsTexture) {
  68452. this._angularSpeedGradientsTexture.dispose();
  68453. this._angularSpeedGradientsTexture = null;
  68454. }
  68455. if (this._velocityGradientsTexture) {
  68456. this._velocityGradientsTexture.dispose();
  68457. this._velocityGradientsTexture = null;
  68458. }
  68459. if (this._limitVelocityGradientsTexture) {
  68460. this._limitVelocityGradientsTexture.dispose();
  68461. this._limitVelocityGradientsTexture = null;
  68462. }
  68463. if (this._dragGradientsTexture) {
  68464. this._dragGradientsTexture.dispose();
  68465. this._dragGradientsTexture = null;
  68466. }
  68467. if (this._randomTexture) {
  68468. this._randomTexture.dispose();
  68469. this._randomTexture = null;
  68470. }
  68471. if (this._randomTexture2) {
  68472. this._randomTexture2.dispose();
  68473. this._randomTexture2 = null;
  68474. }
  68475. if (disposeTexture && this.particleTexture) {
  68476. this.particleTexture.dispose();
  68477. this.particleTexture = null;
  68478. }
  68479. if (disposeTexture && this.noiseTexture) {
  68480. this.noiseTexture.dispose();
  68481. this.noiseTexture = null;
  68482. }
  68483. // Callback
  68484. this.onDisposeObservable.notifyObservers(this);
  68485. this.onDisposeObservable.clear();
  68486. };
  68487. /**
  68488. * Clones the particle system.
  68489. * @param name The name of the cloned object
  68490. * @param newEmitter The new emitter to use
  68491. * @returns the cloned particle system
  68492. */
  68493. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  68494. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  68495. BABYLON.Tools.DeepCopy(this, result);
  68496. if (newEmitter === undefined) {
  68497. newEmitter = this.emitter;
  68498. }
  68499. result.emitter = newEmitter;
  68500. if (this.particleTexture) {
  68501. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  68502. }
  68503. return result;
  68504. };
  68505. /**
  68506. * Serializes the particle system to a JSON object.
  68507. * @returns the JSON object
  68508. */
  68509. GPUParticleSystem.prototype.serialize = function () {
  68510. var serializationObject = {};
  68511. BABYLON.ParticleSystem._Serialize(serializationObject, this);
  68512. serializationObject.activeParticleCount = this.activeParticleCount;
  68513. return serializationObject;
  68514. };
  68515. /**
  68516. * Parses a JSON object to create a GPU particle system.
  68517. * @param parsedParticleSystem The JSON object to parse
  68518. * @param scene The scene to create the particle system in
  68519. * @param rootUrl The root url to use to load external dependencies like texture
  68520. * @param doNotStart Ignore the preventAutoStart attribute and does not start
  68521. * @returns the parsed GPU particle system
  68522. */
  68523. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl, doNotStart) {
  68524. if (doNotStart === void 0) { doNotStart = false; }
  68525. var name = parsedParticleSystem.name;
  68526. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  68527. if (parsedParticleSystem.activeParticleCount) {
  68528. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  68529. }
  68530. BABYLON.ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  68531. // Auto start
  68532. if (parsedParticleSystem.preventAutoStart) {
  68533. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  68534. }
  68535. if (!doNotStart && !particleSystem.preventAutoStart) {
  68536. particleSystem.start();
  68537. }
  68538. return particleSystem;
  68539. };
  68540. return GPUParticleSystem;
  68541. }(BABYLON.BaseParticleSystem));
  68542. BABYLON.GPUParticleSystem = GPUParticleSystem;
  68543. })(BABYLON || (BABYLON = {}));
  68544. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  68545. var BABYLON;
  68546. (function (BABYLON) {
  68547. /**
  68548. * Represents one particle of a solid particle system.
  68549. */
  68550. var SolidParticle = /** @class */ (function () {
  68551. /**
  68552. * Creates a Solid Particle object.
  68553. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  68554. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  68555. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  68556. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  68557. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  68558. * @param shapeId (integer) is the model shape identifier in the SPS.
  68559. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  68560. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  68561. */
  68562. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  68563. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  68564. /**
  68565. * particle global index
  68566. */
  68567. this.idx = 0;
  68568. /**
  68569. * The color of the particle
  68570. */
  68571. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  68572. /**
  68573. * The world space position of the particle.
  68574. */
  68575. this.position = BABYLON.Vector3.Zero();
  68576. /**
  68577. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  68578. */
  68579. this.rotation = BABYLON.Vector3.Zero();
  68580. /**
  68581. * The scaling of the particle.
  68582. */
  68583. this.scaling = BABYLON.Vector3.One();
  68584. /**
  68585. * The uvs of the particle.
  68586. */
  68587. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  68588. /**
  68589. * The current speed of the particle.
  68590. */
  68591. this.velocity = BABYLON.Vector3.Zero();
  68592. /**
  68593. * The pivot point in the particle local space.
  68594. */
  68595. this.pivot = BABYLON.Vector3.Zero();
  68596. /**
  68597. * Must the particle be translated from its pivot point in its local space ?
  68598. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  68599. * Default : false
  68600. */
  68601. this.translateFromPivot = false;
  68602. /**
  68603. * Is the particle active or not ?
  68604. */
  68605. this.alive = true;
  68606. /**
  68607. * Is the particle visible or not ?
  68608. */
  68609. this.isVisible = true;
  68610. /**
  68611. * Index of this particle in the global "positions" array (Internal use)
  68612. * @hidden
  68613. */
  68614. this._pos = 0;
  68615. /**
  68616. * @hidden Index of this particle in the global "indices" array (Internal use)
  68617. */
  68618. this._ind = 0;
  68619. /**
  68620. * ModelShape id of this particle
  68621. */
  68622. this.shapeId = 0;
  68623. /**
  68624. * Index of the particle in its shape id (Internal use)
  68625. */
  68626. this.idxInShape = 0;
  68627. /**
  68628. * @hidden Still set as invisible in order to skip useless computations (Internal use)
  68629. */
  68630. this._stillInvisible = false;
  68631. /**
  68632. * @hidden Last computed particle rotation matrix
  68633. */
  68634. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  68635. /**
  68636. * Parent particle Id, if any.
  68637. * Default null.
  68638. */
  68639. this.parentId = null;
  68640. /**
  68641. * @hidden Internal global position in the SPS.
  68642. */
  68643. this._globalPosition = BABYLON.Vector3.Zero();
  68644. this.idx = particleIndex;
  68645. this._pos = positionIndex;
  68646. this._ind = indiceIndex;
  68647. this._model = model;
  68648. this.shapeId = shapeId;
  68649. this.idxInShape = idxInShape;
  68650. this._sps = sps;
  68651. if (modelBoundingInfo) {
  68652. this._modelBoundingInfo = modelBoundingInfo;
  68653. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  68654. }
  68655. }
  68656. Object.defineProperty(SolidParticle.prototype, "scale", {
  68657. /**
  68658. * Legacy support, changed scale to scaling
  68659. */
  68660. get: function () {
  68661. return this.scaling;
  68662. },
  68663. /**
  68664. * Legacy support, changed scale to scaling
  68665. */
  68666. set: function (scale) {
  68667. this.scaling = scale;
  68668. },
  68669. enumerable: true,
  68670. configurable: true
  68671. });
  68672. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  68673. /**
  68674. * Legacy support, changed quaternion to rotationQuaternion
  68675. */
  68676. get: function () {
  68677. return this.rotationQuaternion;
  68678. },
  68679. /**
  68680. * Legacy support, changed quaternion to rotationQuaternion
  68681. */
  68682. set: function (q) {
  68683. this.rotationQuaternion = q;
  68684. },
  68685. enumerable: true,
  68686. configurable: true
  68687. });
  68688. /**
  68689. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  68690. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  68691. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  68692. * @returns true if it intersects
  68693. */
  68694. SolidParticle.prototype.intersectsMesh = function (target) {
  68695. if (!this._boundingInfo || !target._boundingInfo) {
  68696. return false;
  68697. }
  68698. if (this._sps._bSphereOnly) {
  68699. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  68700. }
  68701. return this._boundingInfo.intersects(target._boundingInfo, false);
  68702. };
  68703. /**
  68704. * get the rotation matrix of the particle
  68705. * @hidden
  68706. */
  68707. SolidParticle.prototype.getRotationMatrix = function (m) {
  68708. var quaternion;
  68709. if (this.rotationQuaternion) {
  68710. quaternion = this.rotationQuaternion;
  68711. }
  68712. else {
  68713. quaternion = BABYLON.Tmp.Quaternion[0];
  68714. var rotation = this.rotation;
  68715. BABYLON.Quaternion.RotationYawPitchRollToRef(rotation.y, rotation.x, rotation.z, quaternion);
  68716. }
  68717. quaternion.toRotationMatrix(m);
  68718. };
  68719. return SolidParticle;
  68720. }());
  68721. BABYLON.SolidParticle = SolidParticle;
  68722. /**
  68723. * Represents the shape of the model used by one particle of a solid particle system.
  68724. * SPS internal tool, don't use it manually.
  68725. */
  68726. var ModelShape = /** @class */ (function () {
  68727. /**
  68728. * 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.
  68729. * SPS internal tool, don't use it manually.
  68730. * @hidden
  68731. */
  68732. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  68733. /**
  68734. * length of the shape in the model indices array (internal use)
  68735. * @hidden
  68736. */
  68737. this._indicesLength = 0;
  68738. this.shapeID = id;
  68739. this._shape = shape;
  68740. this._indicesLength = indicesLength;
  68741. this._shapeUV = shapeUV;
  68742. this._positionFunction = posFunction;
  68743. this._vertexFunction = vtxFunction;
  68744. }
  68745. return ModelShape;
  68746. }());
  68747. BABYLON.ModelShape = ModelShape;
  68748. /**
  68749. * Represents a Depth Sorted Particle in the solid particle system.
  68750. */
  68751. var DepthSortedParticle = /** @class */ (function () {
  68752. function DepthSortedParticle() {
  68753. /**
  68754. * Index of the particle in the "indices" array
  68755. */
  68756. this.ind = 0;
  68757. /**
  68758. * Length of the particle shape in the "indices" array
  68759. */
  68760. this.indicesLength = 0;
  68761. /**
  68762. * Squared distance from the particle to the camera
  68763. */
  68764. this.sqDistance = 0.0;
  68765. }
  68766. return DepthSortedParticle;
  68767. }());
  68768. BABYLON.DepthSortedParticle = DepthSortedParticle;
  68769. })(BABYLON || (BABYLON = {}));
  68770. //# sourceMappingURL=babylon.solidParticle.js.map
  68771. var BABYLON;
  68772. (function (BABYLON) {
  68773. var depthSortFunction = function (p1, p2) { return p2.sqDistance - p1.sqDistance; };
  68774. /**
  68775. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  68776. *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.
  68777. * The SPS is also a particle system. It provides some methods to manage the particles.
  68778. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  68779. *
  68780. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  68781. */
  68782. var SolidParticleSystem = /** @class */ (function () {
  68783. /**
  68784. * Creates a SPS (Solid Particle System) object.
  68785. * @param name (String) is the SPS name, this will be the underlying mesh name.
  68786. * @param scene (Scene) is the scene in which the SPS is added.
  68787. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  68788. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  68789. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  68790. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  68791. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  68792. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  68793. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  68794. */
  68795. function SolidParticleSystem(name, scene, options) {
  68796. /**
  68797. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  68798. * Example : var p = SPS.particles[i];
  68799. */
  68800. this.particles = new Array();
  68801. /**
  68802. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  68803. */
  68804. this.nbParticles = 0;
  68805. /**
  68806. * If the particles must ever face the camera (default false). Useful for planar particles.
  68807. */
  68808. this.billboard = false;
  68809. /**
  68810. * Recompute normals when adding a shape
  68811. */
  68812. this.recomputeNormals = true;
  68813. /**
  68814. * This a counter ofr your own usage. It's not set by any SPS functions.
  68815. */
  68816. this.counter = 0;
  68817. /**
  68818. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  68819. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  68820. */
  68821. this.vars = {};
  68822. /**
  68823. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  68824. * @hidden
  68825. */
  68826. this._bSphereOnly = false;
  68827. /**
  68828. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  68829. * @hidden
  68830. */
  68831. this._bSphereRadiusFactor = 1.0;
  68832. this._positions = new Array();
  68833. this._indices = new Array();
  68834. this._normals = new Array();
  68835. this._colors = new Array();
  68836. this._uvs = new Array();
  68837. this._index = 0; // indices index
  68838. this._updatable = true;
  68839. this._pickable = false;
  68840. this._isVisibilityBoxLocked = false;
  68841. this._alwaysVisible = false;
  68842. this._depthSort = false;
  68843. this._shapeCounter = 0;
  68844. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  68845. this._color = new BABYLON.Color4(0, 0, 0, 0);
  68846. this._computeParticleColor = true;
  68847. this._computeParticleTexture = true;
  68848. this._computeParticleRotation = true;
  68849. this._computeParticleVertex = false;
  68850. this._computeBoundingBox = false;
  68851. this._depthSortParticles = true;
  68852. this._mustUnrotateFixedNormals = false;
  68853. this._particlesIntersect = false;
  68854. this._needs32Bits = false;
  68855. this.name = name;
  68856. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  68857. this._camera = scene.activeCamera;
  68858. this._pickable = options ? options.isPickable : false;
  68859. this._depthSort = options ? options.enableDepthSort : false;
  68860. this._particlesIntersect = options ? options.particleIntersection : false;
  68861. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  68862. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  68863. if (options && options.updatable !== undefined) {
  68864. this._updatable = options.updatable;
  68865. }
  68866. else {
  68867. this._updatable = true;
  68868. }
  68869. if (this._pickable) {
  68870. this.pickedParticles = [];
  68871. }
  68872. if (this._depthSort) {
  68873. this.depthSortedParticles = [];
  68874. }
  68875. }
  68876. /**
  68877. * Builds the SPS underlying mesh. Returns a standard Mesh.
  68878. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  68879. * @returns the created mesh
  68880. */
  68881. SolidParticleSystem.prototype.buildMesh = function () {
  68882. if (this.nbParticles === 0) {
  68883. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  68884. this.addShape(triangle, 1);
  68885. triangle.dispose();
  68886. }
  68887. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  68888. this._positions32 = new Float32Array(this._positions);
  68889. this._uvs32 = new Float32Array(this._uvs);
  68890. this._colors32 = new Float32Array(this._colors);
  68891. if (this.recomputeNormals) {
  68892. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  68893. }
  68894. this._normals32 = new Float32Array(this._normals);
  68895. this._fixedNormal32 = new Float32Array(this._normals);
  68896. if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction
  68897. this._unrotateFixedNormals();
  68898. }
  68899. var vertexData = new BABYLON.VertexData();
  68900. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  68901. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  68902. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  68903. if (this._uvs32.length > 0) {
  68904. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  68905. }
  68906. if (this._colors32.length > 0) {
  68907. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  68908. }
  68909. var mesh = new BABYLON.Mesh(this.name, this._scene);
  68910. vertexData.applyToMesh(mesh, this._updatable);
  68911. this.mesh = mesh;
  68912. this.mesh.isPickable = this._pickable;
  68913. // free memory
  68914. if (!this._depthSort) {
  68915. this._indices = null;
  68916. }
  68917. this._positions = null;
  68918. this._normals = null;
  68919. this._uvs = null;
  68920. this._colors = null;
  68921. if (!this._updatable) {
  68922. this.particles.length = 0;
  68923. }
  68924. return mesh;
  68925. };
  68926. /**
  68927. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  68928. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  68929. * Thus the particles generated from `digest()` have their property `position` set yet.
  68930. * @param mesh ( Mesh ) is the mesh to be digested
  68931. * @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
  68932. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  68933. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  68934. * @returns the current SPS
  68935. */
  68936. SolidParticleSystem.prototype.digest = function (mesh, options) {
  68937. var size = (options && options.facetNb) || 1;
  68938. var number = (options && options.number) || 0;
  68939. var delta = (options && options.delta) || 0;
  68940. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  68941. var meshInd = mesh.getIndices();
  68942. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  68943. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  68944. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  68945. var f = 0; // facet counter
  68946. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  68947. // compute size from number
  68948. if (number) {
  68949. number = (number > totalFacets) ? totalFacets : number;
  68950. size = Math.round(totalFacets / number);
  68951. delta = 0;
  68952. }
  68953. else {
  68954. size = (size > totalFacets) ? totalFacets : size;
  68955. }
  68956. var facetPos = []; // submesh positions
  68957. var facetInd = []; // submesh indices
  68958. var facetUV = []; // submesh UV
  68959. var facetCol = []; // submesh colors
  68960. var barycenter = BABYLON.Vector3.Zero();
  68961. var sizeO = size;
  68962. while (f < totalFacets) {
  68963. size = sizeO + Math.floor((1 + delta) * Math.random());
  68964. if (f > totalFacets - size) {
  68965. size = totalFacets - f;
  68966. }
  68967. // reset temp arrays
  68968. facetPos.length = 0;
  68969. facetInd.length = 0;
  68970. facetUV.length = 0;
  68971. facetCol.length = 0;
  68972. // iterate over "size" facets
  68973. var fi = 0;
  68974. for (var j = f * 3; j < (f + size) * 3; j++) {
  68975. facetInd.push(fi);
  68976. var i = meshInd[j];
  68977. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  68978. if (meshUV) {
  68979. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  68980. }
  68981. if (meshCol) {
  68982. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  68983. }
  68984. fi++;
  68985. }
  68986. // create a model shape for each single particle
  68987. var idx = this.nbParticles;
  68988. var shape = this._posToShape(facetPos);
  68989. var shapeUV = this._uvsToShapeUV(facetUV);
  68990. // compute the barycenter of the shape
  68991. var v;
  68992. for (v = 0; v < shape.length; v++) {
  68993. barycenter.addInPlace(shape[v]);
  68994. }
  68995. barycenter.scaleInPlace(1 / shape.length);
  68996. // shift the shape from its barycenter to the origin
  68997. for (v = 0; v < shape.length; v++) {
  68998. shape[v].subtractInPlace(barycenter);
  68999. }
  69000. var bInfo;
  69001. if (this._particlesIntersect) {
  69002. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  69003. }
  69004. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  69005. // add the particle in the SPS
  69006. var currentPos = this._positions.length;
  69007. var currentInd = this._indices.length;
  69008. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  69009. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  69010. // initialize the particle position
  69011. this.particles[this.nbParticles].position.addInPlace(barycenter);
  69012. this._index += shape.length;
  69013. idx++;
  69014. this.nbParticles++;
  69015. this._shapeCounter++;
  69016. f += size;
  69017. }
  69018. return this;
  69019. };
  69020. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  69021. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  69022. var index = 0;
  69023. var idx = 0;
  69024. var tmpNormal = BABYLON.Tmp.Vector3[0];
  69025. var quaternion = BABYLON.Tmp.Quaternion[0];
  69026. var invertedRotMatrix = BABYLON.Tmp.Matrix[0];
  69027. for (var p = 0; p < this.particles.length; p++) {
  69028. var particle = this.particles[p];
  69029. var shape = particle._model._shape;
  69030. // computing the inverse of the rotation matrix from the quaternion
  69031. // is equivalent to computing the matrix of the inverse quaternion, i.e of the conjugate quaternion
  69032. if (particle.rotationQuaternion) {
  69033. particle.rotationQuaternion.conjugateToRef(quaternion);
  69034. }
  69035. else {
  69036. var rotation = particle.rotation;
  69037. BABYLON.Quaternion.RotationYawPitchRollToRef(rotation.y, rotation.x, rotation.z, quaternion);
  69038. quaternion.conjugateInPlace();
  69039. }
  69040. quaternion.toRotationMatrix(invertedRotMatrix);
  69041. for (var pt = 0; pt < shape.length; pt++) {
  69042. idx = index + pt * 3;
  69043. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], invertedRotMatrix, tmpNormal);
  69044. tmpNormal.toArray(this._fixedNormal32, idx);
  69045. }
  69046. index = idx + 3;
  69047. }
  69048. };
  69049. //reset copy
  69050. SolidParticleSystem.prototype._resetCopy = function () {
  69051. var copy = this._copy;
  69052. copy.position.setAll(0);
  69053. copy.rotation.setAll(0);
  69054. copy.rotationQuaternion = null;
  69055. copy.scaling.setAll(1);
  69056. copy.uvs.copyFromFloats(0.0, 0.0, 1.0, 1.0);
  69057. copy.color = null;
  69058. copy.translateFromPivot = false;
  69059. };
  69060. // _meshBuilder : inserts the shape model in the global SPS mesh
  69061. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  69062. var i;
  69063. var u = 0;
  69064. var c = 0;
  69065. var n = 0;
  69066. this._resetCopy();
  69067. var copy = this._copy;
  69068. if (options && options.positionFunction) { // call to custom positionFunction
  69069. options.positionFunction(copy, idx, idxInShape);
  69070. this._mustUnrotateFixedNormals = true;
  69071. }
  69072. var rotMatrix = BABYLON.Tmp.Matrix[0];
  69073. var tmpVertex = BABYLON.Tmp.Vector3[0];
  69074. var tmpRotated = BABYLON.Tmp.Vector3[1];
  69075. var pivotBackTranslation = BABYLON.Tmp.Vector3[2];
  69076. var scaledPivot = BABYLON.Tmp.Vector3[3];
  69077. copy.getRotationMatrix(rotMatrix);
  69078. copy.pivot.multiplyToRef(copy.scaling, scaledPivot);
  69079. if (copy.translateFromPivot) {
  69080. pivotBackTranslation.setAll(0.0);
  69081. }
  69082. else {
  69083. pivotBackTranslation.copyFrom(scaledPivot);
  69084. }
  69085. for (i = 0; i < shape.length; i++) {
  69086. tmpVertex.copyFrom(shape[i]);
  69087. if (options && options.vertexFunction) {
  69088. options.vertexFunction(copy, tmpVertex, i);
  69089. }
  69090. tmpVertex.multiplyInPlace(copy.scaling).subtractInPlace(scaledPivot);
  69091. BABYLON.Vector3.TransformCoordinatesToRef(tmpVertex, rotMatrix, tmpRotated);
  69092. tmpRotated.addInPlace(pivotBackTranslation).addInPlace(copy.position);
  69093. positions.push(tmpRotated.x, tmpRotated.y, tmpRotated.z);
  69094. if (meshUV) {
  69095. var copyUvs = copy.uvs;
  69096. uvs.push((copyUvs.z - copyUvs.x) * meshUV[u] + copyUvs.x, (copyUvs.w - copyUvs.y) * meshUV[u + 1] + copyUvs.y);
  69097. u += 2;
  69098. }
  69099. if (copy.color) {
  69100. this._color = copy.color;
  69101. }
  69102. else {
  69103. var color = this._color;
  69104. if (meshCol && meshCol[c] !== undefined) {
  69105. color.r = meshCol[c];
  69106. color.g = meshCol[c + 1];
  69107. color.b = meshCol[c + 2];
  69108. color.a = meshCol[c + 3];
  69109. }
  69110. else {
  69111. color.r = 1.0;
  69112. color.g = 1.0;
  69113. color.b = 1.0;
  69114. color.a = 1.0;
  69115. }
  69116. }
  69117. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  69118. c += 4;
  69119. if (!this.recomputeNormals && meshNor) {
  69120. tmpVertex.x = meshNor[n];
  69121. tmpVertex.y = meshNor[n + 1];
  69122. tmpVertex.z = meshNor[n + 2];
  69123. BABYLON.Vector3.TransformNormalToRef(tmpVertex, rotMatrix, tmpVertex);
  69124. normals.push(tmpVertex.x, tmpVertex.y, tmpVertex.z);
  69125. n += 3;
  69126. }
  69127. }
  69128. for (i = 0; i < meshInd.length; i++) {
  69129. var current_ind = p + meshInd[i];
  69130. indices.push(current_ind);
  69131. if (current_ind > 65535) {
  69132. this._needs32Bits = true;
  69133. }
  69134. }
  69135. if (this._pickable) {
  69136. var nbfaces = meshInd.length / 3;
  69137. for (i = 0; i < nbfaces; i++) {
  69138. this.pickedParticles.push({ idx: idx, faceId: i });
  69139. }
  69140. }
  69141. if (this._depthSort) {
  69142. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  69143. }
  69144. return copy;
  69145. };
  69146. // returns a shape array from positions array
  69147. SolidParticleSystem.prototype._posToShape = function (positions) {
  69148. var shape = [];
  69149. for (var i = 0; i < positions.length; i += 3) {
  69150. shape.push(BABYLON.Vector3.FromArray(positions, i));
  69151. }
  69152. return shape;
  69153. };
  69154. // returns a shapeUV array from a Vector4 uvs
  69155. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  69156. var shapeUV = [];
  69157. if (uvs) {
  69158. for (var i = 0; i < uvs.length; i++) {
  69159. shapeUV.push(uvs[i]);
  69160. }
  69161. }
  69162. return shapeUV;
  69163. };
  69164. // adds a new particle object in the particles array
  69165. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  69166. if (bInfo === void 0) { bInfo = null; }
  69167. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  69168. this.particles.push(sp);
  69169. return sp;
  69170. };
  69171. /**
  69172. * Adds some particles to the SPS from the model shape. Returns the shape id.
  69173. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  69174. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  69175. * @param nb (positive integer) the number of particles to be created from this model
  69176. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  69177. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  69178. * @returns the number of shapes in the system
  69179. */
  69180. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  69181. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  69182. var meshInd = mesh.getIndices();
  69183. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  69184. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  69185. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  69186. var bbInfo;
  69187. if (this._particlesIntersect) {
  69188. bbInfo = mesh.getBoundingInfo();
  69189. }
  69190. var shape = this._posToShape(meshPos);
  69191. var shapeUV = this._uvsToShapeUV(meshUV);
  69192. var posfunc = options ? options.positionFunction : null;
  69193. var vtxfunc = options ? options.vertexFunction : null;
  69194. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  69195. // particles
  69196. var sp;
  69197. var currentCopy;
  69198. var idx = this.nbParticles;
  69199. for (var i = 0; i < nb; i++) {
  69200. var currentPos = this._positions.length;
  69201. var currentInd = this._indices.length;
  69202. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  69203. if (this._updatable) {
  69204. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  69205. sp.position.copyFrom(currentCopy.position);
  69206. sp.rotation.copyFrom(currentCopy.rotation);
  69207. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  69208. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  69209. }
  69210. if (currentCopy.color && sp.color) {
  69211. sp.color.copyFrom(currentCopy.color);
  69212. }
  69213. sp.scaling.copyFrom(currentCopy.scaling);
  69214. sp.uvs.copyFrom(currentCopy.uvs);
  69215. }
  69216. this._index += shape.length;
  69217. idx++;
  69218. }
  69219. this.nbParticles += nb;
  69220. this._shapeCounter++;
  69221. return this._shapeCounter - 1;
  69222. };
  69223. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  69224. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  69225. this._resetCopy();
  69226. var copy = this._copy;
  69227. if (particle._model._positionFunction) { // recall to stored custom positionFunction
  69228. particle._model._positionFunction(copy, particle.idx, particle.idxInShape);
  69229. }
  69230. var rotMatrix = BABYLON.Tmp.Matrix[0];
  69231. var tmpVertex = BABYLON.Tmp.Vector3[0];
  69232. var tmpRotated = BABYLON.Tmp.Vector3[1];
  69233. var pivotBackTranslation = BABYLON.Tmp.Vector3[2];
  69234. var scaledPivot = BABYLON.Tmp.Vector3[3];
  69235. copy.getRotationMatrix(rotMatrix);
  69236. particle.pivot.multiplyToRef(particle.scaling, scaledPivot);
  69237. if (copy.translateFromPivot) {
  69238. pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  69239. }
  69240. else {
  69241. pivotBackTranslation.copyFrom(scaledPivot);
  69242. }
  69243. var shape = particle._model._shape;
  69244. for (var pt = 0; pt < shape.length; pt++) {
  69245. tmpVertex.copyFrom(shape[pt]);
  69246. if (particle._model._vertexFunction) {
  69247. particle._model._vertexFunction(copy, tmpVertex, pt); // recall to stored vertexFunction
  69248. }
  69249. tmpVertex.multiplyInPlace(copy.scaling).subtractInPlace(scaledPivot);
  69250. BABYLON.Vector3.TransformCoordinatesToRef(tmpVertex, rotMatrix, tmpRotated);
  69251. tmpRotated.addInPlace(pivotBackTranslation).addInPlace(copy.position).toArray(this._positions32, particle._pos + pt * 3);
  69252. }
  69253. particle.position.setAll(0.0);
  69254. particle.rotation.setAll(0.0);
  69255. particle.rotationQuaternion = null;
  69256. particle.scaling.setAll(1.0);
  69257. particle.uvs.setAll(0.0);
  69258. particle.pivot.setAll(0.0);
  69259. particle.translateFromPivot = false;
  69260. particle.parentId = null;
  69261. };
  69262. /**
  69263. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  69264. * @returns the SPS.
  69265. */
  69266. SolidParticleSystem.prototype.rebuildMesh = function () {
  69267. for (var p = 0; p < this.particles.length; p++) {
  69268. this._rebuildParticle(this.particles[p]);
  69269. }
  69270. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  69271. return this;
  69272. };
  69273. /**
  69274. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  69275. * This method calls `updateParticle()` for each particle of the SPS.
  69276. * For an animated SPS, it is usually called within the render loop.
  69277. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  69278. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  69279. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  69280. * @returns the SPS.
  69281. */
  69282. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  69283. if (start === void 0) { start = 0; }
  69284. if (end === void 0) { end = this.nbParticles - 1; }
  69285. if (update === void 0) { update = true; }
  69286. if (!this._updatable) {
  69287. return this;
  69288. }
  69289. // custom beforeUpdate
  69290. this.beforeUpdateParticles(start, end, update);
  69291. var rotMatrix = BABYLON.Tmp.Matrix[0];
  69292. var invertedMatrix = BABYLON.Tmp.Matrix[1];
  69293. var mesh = this.mesh;
  69294. var colors32 = this._colors32;
  69295. var positions32 = this._positions32;
  69296. var normals32 = this._normals32;
  69297. var uvs32 = this._uvs32;
  69298. var indices32 = this._indices32;
  69299. var indices = this._indices;
  69300. var fixedNormal32 = this._fixedNormal32;
  69301. var tempVectors = BABYLON.Tmp.Vector3;
  69302. var camAxisX = tempVectors[5].copyFromFloats(1.0, 0.0, 0.0);
  69303. var camAxisY = tempVectors[6].copyFromFloats(0.0, 1.0, 0.0);
  69304. var camAxisZ = tempVectors[7].copyFromFloats(0.0, 0.0, 1.0);
  69305. var minimum = tempVectors[8].setAll(Number.MAX_VALUE);
  69306. var maximum = tempVectors[9].setAll(-Number.MAX_VALUE);
  69307. var camInvertedPosition = tempVectors[10].setAll(0);
  69308. // cases when the World Matrix is to be computed first
  69309. if (this.billboard || this._depthSort) {
  69310. this.mesh.computeWorldMatrix(true);
  69311. this.mesh._worldMatrix.invertToRef(invertedMatrix);
  69312. }
  69313. // if the particles will always face the camera
  69314. if (this.billboard) {
  69315. // compute the camera position and un-rotate it by the current mesh rotation
  69316. var tmpVertex = tempVectors[0];
  69317. this._camera.getDirectionToRef(BABYLON.Axis.Z, tmpVertex);
  69318. BABYLON.Vector3.TransformNormalToRef(tmpVertex, invertedMatrix, camAxisZ);
  69319. camAxisZ.normalize();
  69320. // same for camera up vector extracted from the cam view matrix
  69321. var view = this._camera.getViewMatrix(true);
  69322. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], invertedMatrix, camAxisY);
  69323. BABYLON.Vector3.CrossToRef(camAxisY, camAxisZ, camAxisX);
  69324. camAxisY.normalize();
  69325. camAxisX.normalize();
  69326. }
  69327. // if depthSort, compute the camera global position in the mesh local system
  69328. if (this._depthSort) {
  69329. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, invertedMatrix, camInvertedPosition); // then un-rotate the camera
  69330. }
  69331. BABYLON.Matrix.IdentityToRef(rotMatrix);
  69332. var idx = 0; // current position index in the global array positions32
  69333. var index = 0; // position start index in the global array positions32 of the current particle
  69334. var colidx = 0; // current color index in the global array colors32
  69335. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  69336. var uvidx = 0; // current uv index in the global array uvs32
  69337. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  69338. var pt = 0; // current index in the particle model shape
  69339. if (this.mesh.isFacetDataEnabled) {
  69340. this._computeBoundingBox = true;
  69341. }
  69342. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  69343. if (this._computeBoundingBox) {
  69344. if (start != 0 || end != this.nbParticles - 1) { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  69345. var boundingInfo = this.mesh._boundingInfo;
  69346. if (boundingInfo) {
  69347. minimum.copyFrom(boundingInfo.minimum);
  69348. maximum.copyFrom(boundingInfo.maximum);
  69349. }
  69350. }
  69351. }
  69352. // particle loop
  69353. index = this.particles[start]._pos;
  69354. var vpos = (index / 3) | 0;
  69355. colorIndex = vpos * 4;
  69356. uvIndex = vpos * 2;
  69357. for (var p = start; p <= end; p++) {
  69358. var particle = this.particles[p];
  69359. // call to custom user function to update the particle properties
  69360. this.updateParticle(particle);
  69361. var shape = particle._model._shape;
  69362. var shapeUV = particle._model._shapeUV;
  69363. var particleRotationMatrix = particle._rotationMatrix;
  69364. var particlePosition = particle.position;
  69365. var particleRotation = particle.rotation;
  69366. var particleScaling = particle.scaling;
  69367. var particleGlobalPosition = particle._globalPosition;
  69368. // camera-particle distance for depth sorting
  69369. if (this._depthSort && this._depthSortParticles) {
  69370. var dsp = this.depthSortedParticles[p];
  69371. dsp.ind = particle._ind;
  69372. dsp.indicesLength = particle._model._indicesLength;
  69373. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(particle.position, camInvertedPosition);
  69374. }
  69375. // skip the computations for inactive or already invisible particles
  69376. if (!particle.alive || (particle._stillInvisible && !particle.isVisible)) {
  69377. // increment indexes for the next particle
  69378. pt = shape.length;
  69379. index += pt * 3;
  69380. colorIndex += pt * 4;
  69381. uvIndex += pt * 2;
  69382. continue;
  69383. }
  69384. if (particle.isVisible) {
  69385. particle._stillInvisible = false; // un-mark permanent invisibility
  69386. var scaledPivot = tempVectors[12];
  69387. particle.pivot.multiplyToRef(particleScaling, scaledPivot);
  69388. // particle rotation matrix
  69389. if (this.billboard) {
  69390. particleRotation.x = 0.0;
  69391. particleRotation.y = 0.0;
  69392. }
  69393. if (this._computeParticleRotation || this.billboard) {
  69394. particle.getRotationMatrix(rotMatrix);
  69395. }
  69396. var particleHasParent = (particle.parentId !== null);
  69397. if (particleHasParent) {
  69398. var parent_1 = this.particles[particle.parentId];
  69399. var parentRotationMatrix = parent_1._rotationMatrix;
  69400. var parentGlobalPosition = parent_1._globalPosition;
  69401. var rotatedY = particlePosition.x * parentRotationMatrix[1] + particlePosition.y * parentRotationMatrix[4] + particlePosition.z * parentRotationMatrix[7];
  69402. var rotatedX = particlePosition.x * parentRotationMatrix[0] + particlePosition.y * parentRotationMatrix[3] + particlePosition.z * parentRotationMatrix[6];
  69403. var rotatedZ = particlePosition.x * parentRotationMatrix[2] + particlePosition.y * parentRotationMatrix[5] + particlePosition.z * parentRotationMatrix[8];
  69404. particleGlobalPosition.x = parentGlobalPosition.x + rotatedX;
  69405. particleGlobalPosition.y = parentGlobalPosition.y + rotatedY;
  69406. particleGlobalPosition.z = parentGlobalPosition.z + rotatedZ;
  69407. if (this._computeParticleRotation || this.billboard) {
  69408. var rotMatrixValues = rotMatrix.m;
  69409. particleRotationMatrix[0] = rotMatrixValues[0] * parentRotationMatrix[0] + rotMatrixValues[1] * parentRotationMatrix[3] + rotMatrixValues[2] * parentRotationMatrix[6];
  69410. particleRotationMatrix[1] = rotMatrixValues[0] * parentRotationMatrix[1] + rotMatrixValues[1] * parentRotationMatrix[4] + rotMatrixValues[2] * parentRotationMatrix[7];
  69411. particleRotationMatrix[2] = rotMatrixValues[0] * parentRotationMatrix[2] + rotMatrixValues[1] * parentRotationMatrix[5] + rotMatrixValues[2] * parentRotationMatrix[8];
  69412. particleRotationMatrix[3] = rotMatrixValues[4] * parentRotationMatrix[0] + rotMatrixValues[5] * parentRotationMatrix[3] + rotMatrixValues[6] * parentRotationMatrix[6];
  69413. particleRotationMatrix[4] = rotMatrixValues[4] * parentRotationMatrix[1] + rotMatrixValues[5] * parentRotationMatrix[4] + rotMatrixValues[6] * parentRotationMatrix[7];
  69414. particleRotationMatrix[5] = rotMatrixValues[4] * parentRotationMatrix[2] + rotMatrixValues[5] * parentRotationMatrix[5] + rotMatrixValues[6] * parentRotationMatrix[8];
  69415. particleRotationMatrix[6] = rotMatrixValues[8] * parentRotationMatrix[0] + rotMatrixValues[9] * parentRotationMatrix[3] + rotMatrixValues[10] * parentRotationMatrix[6];
  69416. particleRotationMatrix[7] = rotMatrixValues[8] * parentRotationMatrix[1] + rotMatrixValues[9] * parentRotationMatrix[4] + rotMatrixValues[10] * parentRotationMatrix[7];
  69417. particleRotationMatrix[8] = rotMatrixValues[8] * parentRotationMatrix[2] + rotMatrixValues[9] * parentRotationMatrix[5] + rotMatrixValues[10] * parentRotationMatrix[8];
  69418. }
  69419. }
  69420. else {
  69421. particleGlobalPosition.x = particlePosition.x;
  69422. particleGlobalPosition.y = particlePosition.y;
  69423. particleGlobalPosition.z = particlePosition.z;
  69424. if (this._computeParticleRotation || this.billboard) {
  69425. var rotMatrixValues = rotMatrix.m;
  69426. particleRotationMatrix[0] = rotMatrixValues[0];
  69427. particleRotationMatrix[1] = rotMatrixValues[1];
  69428. particleRotationMatrix[2] = rotMatrixValues[2];
  69429. particleRotationMatrix[3] = rotMatrixValues[4];
  69430. particleRotationMatrix[4] = rotMatrixValues[5];
  69431. particleRotationMatrix[5] = rotMatrixValues[6];
  69432. particleRotationMatrix[6] = rotMatrixValues[8];
  69433. particleRotationMatrix[7] = rotMatrixValues[9];
  69434. particleRotationMatrix[8] = rotMatrixValues[10];
  69435. }
  69436. }
  69437. var pivotBackTranslation = tempVectors[11];
  69438. if (particle.translateFromPivot) {
  69439. pivotBackTranslation.setAll(0.0);
  69440. }
  69441. else {
  69442. pivotBackTranslation.copyFrom(scaledPivot);
  69443. }
  69444. // particle vertex loop
  69445. for (pt = 0; pt < shape.length; pt++) {
  69446. idx = index + pt * 3;
  69447. colidx = colorIndex + pt * 4;
  69448. uvidx = uvIndex + pt * 2;
  69449. var tmpVertex = tempVectors[0];
  69450. tmpVertex.copyFrom(shape[pt]);
  69451. if (this._computeParticleVertex) {
  69452. this.updateParticleVertex(particle, tmpVertex, pt);
  69453. }
  69454. // positions
  69455. var vertexX = tmpVertex.x * particleScaling.x - scaledPivot.x;
  69456. var vertexY = tmpVertex.y * particleScaling.y - scaledPivot.y;
  69457. var vertexZ = tmpVertex.z * particleScaling.z - scaledPivot.z;
  69458. var rotatedX = vertexX * particleRotationMatrix[0] + vertexY * particleRotationMatrix[3] + vertexZ * particleRotationMatrix[6];
  69459. var rotatedY = vertexX * particleRotationMatrix[1] + vertexY * particleRotationMatrix[4] + vertexZ * particleRotationMatrix[7];
  69460. var rotatedZ = vertexX * particleRotationMatrix[2] + vertexY * particleRotationMatrix[5] + vertexZ * particleRotationMatrix[8];
  69461. rotatedX += pivotBackTranslation.x;
  69462. rotatedY += pivotBackTranslation.y;
  69463. rotatedZ += pivotBackTranslation.z;
  69464. var px = positions32[idx] = particleGlobalPosition.x + camAxisX.x * rotatedX + camAxisY.x * rotatedY + camAxisZ.x * rotatedZ;
  69465. var py = positions32[idx + 1] = particleGlobalPosition.y + camAxisX.y * rotatedX + camAxisY.y * rotatedY + camAxisZ.y * rotatedZ;
  69466. var pz = positions32[idx + 2] = particleGlobalPosition.z + camAxisX.z * rotatedX + camAxisY.z * rotatedY + camAxisZ.z * rotatedZ;
  69467. if (this._computeBoundingBox) {
  69468. minimum.minimizeInPlaceFromFloats(px, py, pz);
  69469. maximum.maximizeInPlaceFromFloats(px, py, pz);
  69470. }
  69471. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  69472. if (!this._computeParticleVertex) {
  69473. var normalx = fixedNormal32[idx];
  69474. var normaly = fixedNormal32[idx + 1];
  69475. var normalz = fixedNormal32[idx + 2];
  69476. var rotatedx = normalx * particleRotationMatrix[0] + normaly * particleRotationMatrix[3] + normalz * particleRotationMatrix[6];
  69477. var rotatedy = normalx * particleRotationMatrix[1] + normaly * particleRotationMatrix[4] + normalz * particleRotationMatrix[7];
  69478. var rotatedz = normalx * particleRotationMatrix[2] + normaly * particleRotationMatrix[5] + normalz * particleRotationMatrix[8];
  69479. normals32[idx] = camAxisX.x * rotatedx + camAxisY.x * rotatedy + camAxisZ.x * rotatedz;
  69480. normals32[idx + 1] = camAxisX.y * rotatedx + camAxisY.y * rotatedy + camAxisZ.y * rotatedz;
  69481. normals32[idx + 2] = camAxisX.z * rotatedx + camAxisY.z * rotatedy + camAxisZ.z * rotatedz;
  69482. }
  69483. if (this._computeParticleColor && particle.color) {
  69484. var color = particle.color;
  69485. var colors32_1 = this._colors32;
  69486. colors32_1[colidx] = color.r;
  69487. colors32_1[colidx + 1] = color.g;
  69488. colors32_1[colidx + 2] = color.b;
  69489. colors32_1[colidx + 3] = color.a;
  69490. }
  69491. if (this._computeParticleTexture) {
  69492. var uvs = particle.uvs;
  69493. uvs32[uvidx] = shapeUV[pt * 2] * (uvs.z - uvs.x) + uvs.x;
  69494. uvs32[uvidx + 1] = shapeUV[pt * 2 + 1] * (uvs.w - uvs.y) + uvs.y;
  69495. }
  69496. }
  69497. }
  69498. // particle just set invisible : scaled to zero and positioned at the origin
  69499. else {
  69500. particle._stillInvisible = true; // mark the particle as invisible
  69501. for (pt = 0; pt < shape.length; pt++) {
  69502. idx = index + pt * 3;
  69503. colidx = colorIndex + pt * 4;
  69504. uvidx = uvIndex + pt * 2;
  69505. positions32[idx] = positions32[idx + 1] = positions32[idx + 2] = 0;
  69506. normals32[idx] = normals32[idx + 1] = normals32[idx + 2] = 0;
  69507. if (this._computeParticleColor && particle.color) {
  69508. var color = particle.color;
  69509. colors32[colidx] = color.r;
  69510. colors32[colidx + 1] = color.g;
  69511. colors32[colidx + 2] = color.b;
  69512. colors32[colidx + 3] = color.a;
  69513. }
  69514. if (this._computeParticleTexture) {
  69515. var uvs = particle.uvs;
  69516. uvs32[uvidx] = shapeUV[pt * 2] * (uvs.z - uvs.x) + uvs.x;
  69517. uvs32[uvidx + 1] = shapeUV[pt * 2 + 1] * (uvs.w - uvs.y) + uvs.y;
  69518. }
  69519. }
  69520. }
  69521. // if the particle intersections must be computed : update the bbInfo
  69522. if (this._particlesIntersect) {
  69523. var bInfo = particle._boundingInfo;
  69524. var bBox = bInfo.boundingBox;
  69525. var bSphere = bInfo.boundingSphere;
  69526. var modelBoundingInfo = particle._modelBoundingInfo;
  69527. if (!this._bSphereOnly) {
  69528. // place, scale and rotate the particle bbox within the SPS local system, then update it
  69529. var modelBoundingInfoVectors = modelBoundingInfo.boundingBox.vectors;
  69530. var tempMin = tempVectors[1];
  69531. var tempMax = tempVectors[2];
  69532. tempMin.setAll(Number.MAX_VALUE);
  69533. tempMax.setAll(-Number.MAX_VALUE);
  69534. for (var b = 0; b < 8; b++) {
  69535. var scaledX = modelBoundingInfoVectors[b].x * particleScaling.x;
  69536. var scaledY = modelBoundingInfoVectors[b].y * particleScaling.y;
  69537. var scaledZ = modelBoundingInfoVectors[b].z * particleScaling.z;
  69538. var rotatedX = scaledX * particleRotationMatrix[0] + scaledY * particleRotationMatrix[3] + scaledZ * particleRotationMatrix[6];
  69539. var rotatedY = scaledX * particleRotationMatrix[1] + scaledY * particleRotationMatrix[4] + scaledZ * particleRotationMatrix[7];
  69540. var rotatedZ = scaledX * particleRotationMatrix[2] + scaledY * particleRotationMatrix[5] + scaledZ * particleRotationMatrix[8];
  69541. var x = particlePosition.x + camAxisX.x * rotatedX + camAxisY.x * rotatedY + camAxisZ.x * rotatedZ;
  69542. var y = particlePosition.y + camAxisX.y * rotatedX + camAxisY.y * rotatedY + camAxisZ.y * rotatedZ;
  69543. var z = particlePosition.z + camAxisX.z * rotatedX + camAxisY.z * rotatedY + camAxisZ.z * rotatedZ;
  69544. tempMin.minimizeInPlaceFromFloats(x, y, z);
  69545. tempMax.maximizeInPlaceFromFloats(x, y, z);
  69546. }
  69547. bBox.reConstruct(tempMin, tempMax, mesh._worldMatrix);
  69548. }
  69549. // place and scale the particle bouding sphere in the SPS local system, then update it
  69550. var minBbox = modelBoundingInfo.minimum.multiplyToRef(particleScaling, tempVectors[1]);
  69551. var maxBbox = modelBoundingInfo.maximum.multiplyToRef(particleScaling, tempVectors[2]);
  69552. var bSphereCenter = maxBbox.addToRef(minBbox, tempVectors[3]).scaleInPlace(0.5).addInPlace(particleGlobalPosition);
  69553. var halfDiag = maxBbox.subtractToRef(minBbox, tempVectors[4]).scaleInPlace(0.5 * this._bSphereRadiusFactor);
  69554. var bSphereMinBbox = bSphereCenter.subtractToRef(halfDiag, tempVectors[1]);
  69555. var bSphereMaxBbox = bSphereCenter.addToRef(halfDiag, tempVectors[2]);
  69556. bSphere.reConstruct(bSphereMinBbox, bSphereMaxBbox, mesh._worldMatrix);
  69557. }
  69558. // increment indexes for the next particle
  69559. index = idx + 3;
  69560. colorIndex = colidx + 4;
  69561. uvIndex = uvidx + 2;
  69562. }
  69563. // if the VBO must be updated
  69564. if (update) {
  69565. if (this._computeParticleColor) {
  69566. mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors32, false, false);
  69567. }
  69568. if (this._computeParticleTexture) {
  69569. mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs32, false, false);
  69570. }
  69571. mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions32, false, false);
  69572. if (!mesh.areNormalsFrozen || mesh.isFacetDataEnabled) {
  69573. if (this._computeParticleVertex || mesh.isFacetDataEnabled) {
  69574. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  69575. var params = mesh.isFacetDataEnabled ? mesh.getFacetDataParameters() : null;
  69576. BABYLON.VertexData.ComputeNormals(positions32, indices32, normals32, params);
  69577. for (var i = 0; i < normals32.length; i++) {
  69578. fixedNormal32[i] = normals32[i];
  69579. }
  69580. }
  69581. if (!mesh.areNormalsFrozen) {
  69582. mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals32, false, false);
  69583. }
  69584. }
  69585. if (this._depthSort && this._depthSortParticles) {
  69586. var depthSortedParticles = this.depthSortedParticles;
  69587. depthSortedParticles.sort(depthSortFunction);
  69588. var dspl = depthSortedParticles.length;
  69589. var sid = 0;
  69590. for (var sorted = 0; sorted < dspl; sorted++) {
  69591. var lind = depthSortedParticles[sorted].indicesLength;
  69592. var sind = depthSortedParticles[sorted].ind;
  69593. for (var i = 0; i < lind; i++) {
  69594. indices32[sid] = indices[sind + i];
  69595. sid++;
  69596. }
  69597. }
  69598. mesh.updateIndices(indices32);
  69599. }
  69600. }
  69601. if (this._computeBoundingBox) {
  69602. if (mesh._boundingInfo) {
  69603. mesh._boundingInfo.reConstruct(minimum, maximum, mesh._worldMatrix);
  69604. }
  69605. else {
  69606. mesh._boundingInfo = new BABYLON.BoundingInfo(minimum, maximum, mesh._worldMatrix);
  69607. }
  69608. }
  69609. this.afterUpdateParticles(start, end, update);
  69610. return this;
  69611. };
  69612. /**
  69613. * Disposes the SPS.
  69614. */
  69615. SolidParticleSystem.prototype.dispose = function () {
  69616. this.mesh.dispose();
  69617. this.vars = null;
  69618. // drop references to internal big arrays for the GC
  69619. this._positions = null;
  69620. this._indices = null;
  69621. this._normals = null;
  69622. this._uvs = null;
  69623. this._colors = null;
  69624. this._indices32 = null;
  69625. this._positions32 = null;
  69626. this._normals32 = null;
  69627. this._fixedNormal32 = null;
  69628. this._uvs32 = null;
  69629. this._colors32 = null;
  69630. this.pickedParticles = null;
  69631. };
  69632. /**
  69633. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  69634. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  69635. * @returns the SPS.
  69636. */
  69637. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  69638. if (!this._isVisibilityBoxLocked) {
  69639. this.mesh.refreshBoundingInfo();
  69640. }
  69641. return this;
  69642. };
  69643. /**
  69644. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  69645. * @param size the size (float) of the visibility box
  69646. * note : this doesn't lock the SPS mesh bounding box.
  69647. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  69648. */
  69649. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  69650. var vis = size / 2;
  69651. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  69652. };
  69653. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  69654. /**
  69655. * Gets whether the SPS as always visible or not
  69656. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  69657. */
  69658. get: function () {
  69659. return this._alwaysVisible;
  69660. },
  69661. /**
  69662. * Sets the SPS as always visible or not
  69663. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  69664. */
  69665. set: function (val) {
  69666. this._alwaysVisible = val;
  69667. this.mesh.alwaysSelectAsActiveMesh = val;
  69668. },
  69669. enumerable: true,
  69670. configurable: true
  69671. });
  69672. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  69673. /**
  69674. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  69675. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  69676. */
  69677. get: function () {
  69678. return this._isVisibilityBoxLocked;
  69679. },
  69680. /**
  69681. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  69682. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  69683. */
  69684. set: function (val) {
  69685. this._isVisibilityBoxLocked = val;
  69686. var boundingInfo = this.mesh.getBoundingInfo();
  69687. boundingInfo.isLocked = val;
  69688. },
  69689. enumerable: true,
  69690. configurable: true
  69691. });
  69692. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  69693. /**
  69694. * Gets if `setParticles()` computes the particle rotations or not.
  69695. * Default value : true. The SPS is faster when it's set to false.
  69696. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  69697. */
  69698. get: function () {
  69699. return this._computeParticleRotation;
  69700. },
  69701. /**
  69702. * Tells to `setParticles()` to compute the particle rotations or not.
  69703. * Default value : true. The SPS is faster when it's set to false.
  69704. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  69705. */
  69706. set: function (val) {
  69707. this._computeParticleRotation = val;
  69708. },
  69709. enumerable: true,
  69710. configurable: true
  69711. });
  69712. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  69713. /**
  69714. * Gets if `setParticles()` computes the particle colors or not.
  69715. * Default value : true. The SPS is faster when it's set to false.
  69716. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  69717. */
  69718. get: function () {
  69719. return this._computeParticleColor;
  69720. },
  69721. /**
  69722. * Tells to `setParticles()` to compute the particle colors or not.
  69723. * Default value : true. The SPS is faster when it's set to false.
  69724. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  69725. */
  69726. set: function (val) {
  69727. this._computeParticleColor = val;
  69728. },
  69729. enumerable: true,
  69730. configurable: true
  69731. });
  69732. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  69733. /**
  69734. * Gets if `setParticles()` computes the particle textures or not.
  69735. * Default value : true. The SPS is faster when it's set to false.
  69736. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  69737. */
  69738. get: function () {
  69739. return this._computeParticleTexture;
  69740. },
  69741. set: function (val) {
  69742. this._computeParticleTexture = val;
  69743. },
  69744. enumerable: true,
  69745. configurable: true
  69746. });
  69747. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  69748. /**
  69749. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  69750. * Default value : false. The SPS is faster when it's set to false.
  69751. * Note : the particle custom vertex positions aren't stored values.
  69752. */
  69753. get: function () {
  69754. return this._computeParticleVertex;
  69755. },
  69756. /**
  69757. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  69758. * Default value : false. The SPS is faster when it's set to false.
  69759. * Note : the particle custom vertex positions aren't stored values.
  69760. */
  69761. set: function (val) {
  69762. this._computeParticleVertex = val;
  69763. },
  69764. enumerable: true,
  69765. configurable: true
  69766. });
  69767. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  69768. /**
  69769. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  69770. */
  69771. get: function () {
  69772. return this._computeBoundingBox;
  69773. },
  69774. /**
  69775. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  69776. */
  69777. set: function (val) {
  69778. this._computeBoundingBox = val;
  69779. },
  69780. enumerable: true,
  69781. configurable: true
  69782. });
  69783. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  69784. /**
  69785. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  69786. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  69787. * Default : `true`
  69788. */
  69789. get: function () {
  69790. return this._depthSortParticles;
  69791. },
  69792. /**
  69793. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  69794. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  69795. * Default : `true`
  69796. */
  69797. set: function (val) {
  69798. this._depthSortParticles = val;
  69799. },
  69800. enumerable: true,
  69801. configurable: true
  69802. });
  69803. // =======================================================================
  69804. // Particle behavior logic
  69805. // these following methods may be overwritten by the user to fit his needs
  69806. /**
  69807. * This function does nothing. It may be overwritten to set all the particle first values.
  69808. * The SPS doesn't call this function, you may have to call it by your own.
  69809. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  69810. */
  69811. SolidParticleSystem.prototype.initParticles = function () {
  69812. };
  69813. /**
  69814. * This function does nothing. It may be overwritten to recycle a particle.
  69815. * The SPS doesn't call this function, you may have to call it by your own.
  69816. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  69817. * @param particle The particle to recycle
  69818. * @returns the recycled particle
  69819. */
  69820. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  69821. return particle;
  69822. };
  69823. /**
  69824. * Updates a particle : this function should be overwritten by the user.
  69825. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  69826. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  69827. * @example : just set a particle position or velocity and recycle conditions
  69828. * @param particle The particle to update
  69829. * @returns the updated particle
  69830. */
  69831. SolidParticleSystem.prototype.updateParticle = function (particle) {
  69832. return particle;
  69833. };
  69834. /**
  69835. * Updates a vertex of a particle : it can be overwritten by the user.
  69836. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  69837. * @param particle the current particle
  69838. * @param vertex the current index of the current particle
  69839. * @param pt the index of the current vertex in the particle shape
  69840. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  69841. * @example : just set a vertex particle position
  69842. * @returns the updated vertex
  69843. */
  69844. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  69845. return vertex;
  69846. };
  69847. /**
  69848. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  69849. * This does nothing and may be overwritten by the user.
  69850. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  69851. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  69852. * @param update the boolean update value actually passed to setParticles()
  69853. */
  69854. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  69855. };
  69856. /**
  69857. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  69858. * This will be passed three parameters.
  69859. * This does nothing and may be overwritten by the user.
  69860. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  69861. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  69862. * @param update the boolean update value actually passed to setParticles()
  69863. */
  69864. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  69865. };
  69866. return SolidParticleSystem;
  69867. }());
  69868. BABYLON.SolidParticleSystem = SolidParticleSystem;
  69869. })(BABYLON || (BABYLON = {}));
  69870. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  69871. var BABYLON;
  69872. (function (BABYLON) {
  69873. /**
  69874. * Class containing static functions to help procedurally build meshes
  69875. */
  69876. var MeshBuilder = /** @class */ (function () {
  69877. function MeshBuilder() {
  69878. }
  69879. MeshBuilder._UpdateSideOrientation = function (orientation) {
  69880. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  69881. return BABYLON.Mesh.DOUBLESIDE;
  69882. }
  69883. if (orientation === undefined || orientation === null) {
  69884. return BABYLON.Mesh.FRONTSIDE;
  69885. }
  69886. return orientation;
  69887. };
  69888. /**
  69889. * Creates a box mesh
  69890. * * The parameter `size` sets the size (float) of each box side (default 1)
  69891. * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value of `size`)
  69892. * * 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)
  69893. * * Please read this tutorial : https://doc.babylonjs.com/how_to/createbox_per_face_textures_and_colors
  69894. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  69895. * * 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 : https://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  69896. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  69897. * @see https://doc.babylonjs.com/how_to/set_shapes#box
  69898. * @param name defines the name of the mesh
  69899. * @param options defines the options used to create the mesh
  69900. * @param scene defines the hosting scene
  69901. * @returns the box mesh
  69902. */
  69903. MeshBuilder.CreateBox = function (name, options, scene) {
  69904. if (scene === void 0) { scene = null; }
  69905. var box = new BABYLON.Mesh(name, scene);
  69906. options.sideOrientation = MeshBuilder._UpdateSideOrientation(options.sideOrientation);
  69907. box._originalBuilderSideOrientation = options.sideOrientation;
  69908. var vertexData = BABYLON.VertexData.CreateBox(options);
  69909. vertexData.applyToMesh(box, options.updatable);
  69910. return box;
  69911. };
  69912. /**
  69913. * Creates a sphere mesh
  69914. * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
  69915. * * 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`)
  69916. * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
  69917. * * 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
  69918. * * 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)
  69919. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  69920. * * 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 : https://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  69921. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  69922. * @param name defines the name of the mesh
  69923. * @param options defines the options used to create the mesh
  69924. * @param scene defines the hosting scene
  69925. * @returns the sphere mesh
  69926. * @see https://doc.babylonjs.com/how_to/set_shapes#sphere
  69927. */
  69928. MeshBuilder.CreateSphere = function (name, options, scene) {
  69929. var sphere = new BABYLON.Mesh(name, scene);
  69930. options.sideOrientation = MeshBuilder._UpdateSideOrientation(options.sideOrientation);
  69931. sphere._originalBuilderSideOrientation = options.sideOrientation;
  69932. var vertexData = BABYLON.VertexData.CreateSphere(options);
  69933. vertexData.applyToMesh(sphere, options.updatable);
  69934. return sphere;
  69935. };
  69936. /**
  69937. * Creates a plane polygonal mesh. By default, this is a disc
  69938. * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
  69939. * * 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
  69940. * * 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
  69941. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  69942. * * 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 : https://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  69943. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  69944. * @param name defines the name of the mesh
  69945. * @param options defines the options used to create the mesh
  69946. * @param scene defines the hosting scene
  69947. * @returns the plane polygonal mesh
  69948. * @see https://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  69949. */
  69950. MeshBuilder.CreateDisc = function (name, options, scene) {
  69951. if (scene === void 0) { scene = null; }
  69952. var disc = new BABYLON.Mesh(name, scene);
  69953. options.sideOrientation = MeshBuilder._UpdateSideOrientation(options.sideOrientation);
  69954. disc._originalBuilderSideOrientation = options.sideOrientation;
  69955. var vertexData = BABYLON.VertexData.CreateDisc(options);
  69956. vertexData.applyToMesh(disc, options.updatable);
  69957. return disc;
  69958. };
  69959. /**
  69960. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  69961. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  69962. * * 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`)
  69963. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  69964. * * 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
  69965. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  69966. * * 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 : https://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  69967. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  69968. * @param name defines the name of the mesh
  69969. * @param options defines the options used to create the mesh
  69970. * @param scene defines the hosting scene
  69971. * @returns the icosahedron mesh
  69972. * @see https://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  69973. */
  69974. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  69975. var sphere = new BABYLON.Mesh(name, scene);
  69976. options.sideOrientation = MeshBuilder._UpdateSideOrientation(options.sideOrientation);
  69977. sphere._originalBuilderSideOrientation = options.sideOrientation;
  69978. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  69979. vertexData.applyToMesh(sphere, options.updatable);
  69980. return sphere;
  69981. };
  69982. /**
  69983. * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  69984. * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
  69985. * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
  69986. * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
  69987. * * 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
  69988. * * 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
  69989. * * The optional parameter `instance` is an instance of an existing Ribbon object to be updated with the passed `pathArray` parameter : https://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh#ribbon
  69990. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  69991. * * 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 : https://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  69992. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  69993. * * 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
  69994. * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
  69995. * * 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
  69996. * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
  69997. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  69998. * @param name defines the name of the mesh
  69999. * @param options defines the options used to create the mesh
  70000. * @param scene defines the hosting scene
  70001. * @returns the ribbon mesh
  70002. * @see https://doc.babylonjs.com/how_to/ribbon_tutorial
  70003. * @see https://doc.babylonjs.com/how_to/parametric_shapes
  70004. */
  70005. MeshBuilder.CreateRibbon = function (name, options, scene) {
  70006. if (scene === void 0) { scene = null; }
  70007. var pathArray = options.pathArray;
  70008. var closeArray = options.closeArray;
  70009. var closePath = options.closePath;
  70010. var sideOrientation = MeshBuilder._UpdateSideOrientation(options.sideOrientation);
  70011. var instance = options.instance;
  70012. var updatable = options.updatable;
  70013. if (instance) { // existing ribbon instance update
  70014. // positionFunction : ribbon case
  70015. // only pathArray and sideOrientation parameters are taken into account for positions update
  70016. var minimum_1 = BABYLON.Tmp.Vector3[0].setAll(Number.MAX_VALUE);
  70017. var maximum_1 = BABYLON.Tmp.Vector3[1].setAll(-Number.MAX_VALUE);
  70018. var positionFunction = function (positions) {
  70019. var minlg = pathArray[0].length;
  70020. var mesh = instance;
  70021. var i = 0;
  70022. var ns = (mesh._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  70023. for (var si = 1; si <= ns; ++si) {
  70024. for (var p = 0; p < pathArray.length; ++p) {
  70025. var path = pathArray[p];
  70026. var l = path.length;
  70027. minlg = (minlg < l) ? minlg : l;
  70028. for (var j = 0; j < minlg; ++j) {
  70029. var pathPoint = path[j];
  70030. positions[i] = pathPoint.x;
  70031. positions[i + 1] = pathPoint.y;
  70032. positions[i + 2] = pathPoint.z;
  70033. minimum_1.minimizeInPlaceFromFloats(pathPoint.x, pathPoint.y, pathPoint.z);
  70034. maximum_1.maximizeInPlaceFromFloats(pathPoint.x, pathPoint.y, pathPoint.z);
  70035. i += 3;
  70036. }
  70037. if (mesh._creationDataStorage && mesh._creationDataStorage.closePath) {
  70038. var pathPoint = path[0];
  70039. positions[i] = pathPoint.x;
  70040. positions[i + 1] = pathPoint.y;
  70041. positions[i + 2] = pathPoint.z;
  70042. i += 3;
  70043. }
  70044. }
  70045. }
  70046. };
  70047. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  70048. positionFunction(positions);
  70049. if (instance._boundingInfo) {
  70050. instance._boundingInfo.reConstruct(minimum_1, maximum_1, instance._worldMatrix);
  70051. }
  70052. else {
  70053. instance._boundingInfo = new BABYLON.BoundingInfo(minimum_1, maximum_1, instance._worldMatrix);
  70054. }
  70055. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  70056. if (options.colors) {
  70057. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  70058. for (var c = 0, colorIndex = 0; c < options.colors.length; c++, colorIndex += 4) {
  70059. var color = options.colors[c];
  70060. colors[colorIndex] = color.r;
  70061. colors[colorIndex + 1] = color.g;
  70062. colors[colorIndex + 2] = color.b;
  70063. colors[colorIndex + 3] = color.a;
  70064. }
  70065. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  70066. }
  70067. if (options.uvs) {
  70068. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  70069. for (var i = 0; i < options.uvs.length; i++) {
  70070. uvs[i * 2] = options.uvs[i].x;
  70071. uvs[i * 2 + 1] = options.uvs[i].y;
  70072. }
  70073. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  70074. }
  70075. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  70076. var indices = instance.getIndices();
  70077. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  70078. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  70079. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  70080. if (instance._creationDataStorage && instance._creationDataStorage.closePath) {
  70081. var indexFirst = 0;
  70082. var indexLast = 0;
  70083. for (var p = 0; p < pathArray.length; p++) {
  70084. indexFirst = instance._creationDataStorage.idx[p] * 3;
  70085. if (p + 1 < pathArray.length) {
  70086. indexLast = (instance._creationDataStorage.idx[p + 1] - 1) * 3;
  70087. }
  70088. else {
  70089. indexLast = normals.length - 3;
  70090. }
  70091. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  70092. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  70093. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  70094. normals[indexLast] = normals[indexFirst];
  70095. normals[indexLast + 1] = normals[indexFirst + 1];
  70096. normals[indexLast + 2] = normals[indexFirst + 2];
  70097. }
  70098. }
  70099. if (!(instance.areNormalsFrozen)) {
  70100. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  70101. }
  70102. }
  70103. return instance;
  70104. }
  70105. else { // new ribbon creation
  70106. var ribbon = new BABYLON.Mesh(name, scene);
  70107. ribbon._originalBuilderSideOrientation = sideOrientation;
  70108. ribbon._creationDataStorage = new BABYLON._CreationDataStorage();
  70109. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  70110. if (closePath) {
  70111. ribbon._creationDataStorage.idx = vertexData._idx;
  70112. }
  70113. ribbon._creationDataStorage.closePath = closePath;
  70114. ribbon._creationDataStorage.closeArray = closeArray;
  70115. vertexData.applyToMesh(ribbon, updatable);
  70116. return ribbon;
  70117. }
  70118. };
  70119. /**
  70120. * Creates a cylinder or a cone mesh
  70121. * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  70122. * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  70123. * * 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.
  70124. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  70125. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  70126. * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  70127. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  70128. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  70129. * * 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).
  70130. * * 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
  70131. * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  70132. * * 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
  70133. * * 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.
  70134. * * If `enclose` is false, a ring surface is one element.
  70135. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  70136. * * Example how to set colors and textures on a sliced cylinder : https://www.html5gamedevs.com/topic/17945-creating-a-closed-slice-of-a-cylinder/#comment-106379
  70137. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  70138. * * 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 : https://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  70139. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  70140. * @param name defines the name of the mesh
  70141. * @param options defines the options used to create the mesh
  70142. * @param scene defines the hosting scene
  70143. * @returns the cylinder mesh
  70144. * @see https://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  70145. */
  70146. MeshBuilder.CreateCylinder = function (name, options, scene) {
  70147. var cylinder = new BABYLON.Mesh(name, scene);
  70148. options.sideOrientation = MeshBuilder._UpdateSideOrientation(options.sideOrientation);
  70149. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  70150. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  70151. vertexData.applyToMesh(cylinder, options.updatable);
  70152. return cylinder;
  70153. };
  70154. /**
  70155. * Creates a torus mesh
  70156. * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
  70157. * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
  70158. * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
  70159. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  70160. * * 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 : https://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  70161. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  70162. * @param name defines the name of the mesh
  70163. * @param options defines the options used to create the mesh
  70164. * @param scene defines the hosting scene
  70165. * @returns the torus mesh
  70166. * @see https://doc.babylonjs.com/how_to/set_shapes#torus
  70167. */
  70168. MeshBuilder.CreateTorus = function (name, options, scene) {
  70169. var torus = new BABYLON.Mesh(name, scene);
  70170. options.sideOrientation = MeshBuilder._UpdateSideOrientation(options.sideOrientation);
  70171. torus._originalBuilderSideOrientation = options.sideOrientation;
  70172. var vertexData = BABYLON.VertexData.CreateTorus(options);
  70173. vertexData.applyToMesh(torus, options.updatable);
  70174. return torus;
  70175. };
  70176. /**
  70177. * Creates a torus knot mesh
  70178. * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
  70179. * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
  70180. * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
  70181. * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
  70182. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  70183. * * 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 : https://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  70184. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  70185. * @param name defines the name of the mesh
  70186. * @param options defines the options used to create the mesh
  70187. * @param scene defines the hosting scene
  70188. * @returns the torus knot mesh
  70189. * @see https://doc.babylonjs.com/how_to/set_shapes#torus-knot
  70190. */
  70191. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  70192. var torusKnot = new BABYLON.Mesh(name, scene);
  70193. options.sideOrientation = MeshBuilder._UpdateSideOrientation(options.sideOrientation);
  70194. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  70195. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  70196. vertexData.applyToMesh(torusKnot, options.updatable);
  70197. return torusKnot;
  70198. };
  70199. /**
  70200. * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
  70201. * * 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
  70202. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
  70203. * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
  70204. * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
  70205. * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
  70206. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
  70207. * * Updating a simple Line mesh, you just need to update every line in the `lines` array : https://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh#lines-and-dashedlines
  70208. * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
  70209. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  70210. * @see https://doc.babylonjs.com/how_to/parametric_shapes#line-system
  70211. * @param name defines the name of the new line system
  70212. * @param options defines the options used to create the line system
  70213. * @param scene defines the hosting scene
  70214. * @returns a new line system mesh
  70215. */
  70216. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  70217. var instance = options.instance;
  70218. var lines = options.lines;
  70219. var colors = options.colors;
  70220. if (instance) { // lines update
  70221. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  70222. var vertexColor;
  70223. var lineColors;
  70224. if (colors) {
  70225. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  70226. }
  70227. var i = 0;
  70228. var c = 0;
  70229. for (var l = 0; l < lines.length; l++) {
  70230. var points = lines[l];
  70231. for (var p = 0; p < points.length; p++) {
  70232. positions[i] = points[p].x;
  70233. positions[i + 1] = points[p].y;
  70234. positions[i + 2] = points[p].z;
  70235. if (colors && vertexColor) {
  70236. lineColors = colors[l];
  70237. vertexColor[c] = lineColors[p].r;
  70238. vertexColor[c + 1] = lineColors[p].g;
  70239. vertexColor[c + 2] = lineColors[p].b;
  70240. vertexColor[c + 3] = lineColors[p].a;
  70241. c += 4;
  70242. }
  70243. i += 3;
  70244. }
  70245. }
  70246. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  70247. if (colors && vertexColor) {
  70248. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  70249. }
  70250. return instance;
  70251. }
  70252. // line system creation
  70253. var useVertexColor = (colors) ? true : false;
  70254. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  70255. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  70256. vertexData.applyToMesh(lineSystem, options.updatable);
  70257. return lineSystem;
  70258. };
  70259. /**
  70260. * Creates a line mesh
  70261. * 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
  70262. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  70263. * * The parameter `points` is an array successive Vector3
  70264. * * The optional parameter `instance` is an instance of an existing LineMesh object to be updated with the passed `points` parameter : https://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh#lines-and-dashedlines
  70265. * * The optional parameter `colors` is an array of successive Color4, one per line point
  70266. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
  70267. * * When updating an instance, remember that only point positions can change, not the number of points
  70268. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  70269. * @see https://doc.babylonjs.com/how_to/parametric_shapes#lines
  70270. * @param name defines the name of the new line system
  70271. * @param options defines the options used to create the line system
  70272. * @param scene defines the hosting scene
  70273. * @returns a new line mesh
  70274. */
  70275. MeshBuilder.CreateLines = function (name, options, scene) {
  70276. if (scene === void 0) { scene = null; }
  70277. var colors = (options.colors) ? [options.colors] : null;
  70278. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  70279. return lines;
  70280. };
  70281. /**
  70282. * Creates a dashed line mesh
  70283. * * 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
  70284. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  70285. * * The parameter `points` is an array successive Vector3
  70286. * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
  70287. * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
  70288. * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  70289. * * The optional parameter `instance` is an instance of an existing LineMesh object to be updated with the passed `points` parameter : https://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh#lines-and-dashedlines
  70290. * * When updating an instance, remember that only point positions can change, not the number of points
  70291. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  70292. * @param name defines the name of the mesh
  70293. * @param options defines the options used to create the mesh
  70294. * @param scene defines the hosting scene
  70295. * @returns the dashed line mesh
  70296. * @see https://doc.babylonjs.com/how_to/parametric_shapes#dashed-lines
  70297. */
  70298. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  70299. if (scene === void 0) { scene = null; }
  70300. var points = options.points;
  70301. var instance = options.instance;
  70302. var gapSize = options.gapSize || 1;
  70303. var dashSize = options.dashSize || 3;
  70304. if (instance) { // dashed lines update
  70305. var positionFunction = function (positions) {
  70306. var curvect = BABYLON.Vector3.Zero();
  70307. var nbSeg = positions.length / 6;
  70308. var lg = 0;
  70309. var nb = 0;
  70310. var shft = 0;
  70311. var dashshft = 0;
  70312. var curshft = 0;
  70313. var p = 0;
  70314. var i = 0;
  70315. var j = 0;
  70316. for (i = 0; i < points.length - 1; i++) {
  70317. points[i + 1].subtractToRef(points[i], curvect);
  70318. lg += curvect.length();
  70319. }
  70320. shft = lg / nbSeg;
  70321. var dashSize = instance._creationDataStorage.dashSize;
  70322. var gapSize = instance._creationDataStorage.gapSize;
  70323. dashshft = dashSize * shft / (dashSize + gapSize);
  70324. for (i = 0; i < points.length - 1; i++) {
  70325. points[i + 1].subtractToRef(points[i], curvect);
  70326. nb = Math.floor(curvect.length() / shft);
  70327. curvect.normalize();
  70328. j = 0;
  70329. while (j < nb && p < positions.length) {
  70330. curshft = shft * j;
  70331. positions[p] = points[i].x + curshft * curvect.x;
  70332. positions[p + 1] = points[i].y + curshft * curvect.y;
  70333. positions[p + 2] = points[i].z + curshft * curvect.z;
  70334. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  70335. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  70336. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  70337. p += 6;
  70338. j++;
  70339. }
  70340. }
  70341. while (p < positions.length) {
  70342. positions[p] = points[i].x;
  70343. positions[p + 1] = points[i].y;
  70344. positions[p + 2] = points[i].z;
  70345. p += 3;
  70346. }
  70347. };
  70348. instance.updateMeshPositions(positionFunction, false);
  70349. return instance;
  70350. }
  70351. // dashed lines creation
  70352. var dashedLines = new BABYLON.LinesMesh(name, scene);
  70353. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  70354. vertexData.applyToMesh(dashedLines, options.updatable);
  70355. dashedLines._creationDataStorage = new BABYLON._CreationDataStorage();
  70356. dashedLines._creationDataStorage.dashSize = dashSize;
  70357. dashedLines._creationDataStorage.gapSize = gapSize;
  70358. return dashedLines;
  70359. };
  70360. /**
  70361. * 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.
  70362. * * 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.
  70363. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  70364. * * 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.
  70365. * * The parameter `scale` (float, default 1) is the value to scale the shape.
  70366. * * 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
  70367. * * The optional parameter `instance` is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters : https://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh#extruded-shape
  70368. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  70369. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  70370. * * 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 : https://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  70371. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  70372. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  70373. * @param name defines the name of the mesh
  70374. * @param options defines the options used to create the mesh
  70375. * @param scene defines the hosting scene
  70376. * @returns the extruded shape mesh
  70377. * @see https://doc.babylonjs.com/how_to/parametric_shapes
  70378. * @see https://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  70379. */
  70380. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  70381. if (scene === void 0) { scene = null; }
  70382. var path = options.path;
  70383. var shape = options.shape;
  70384. var scale = options.scale || 1;
  70385. var rotation = options.rotation || 0;
  70386. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  70387. var updatable = options.updatable;
  70388. var sideOrientation = MeshBuilder._UpdateSideOrientation(options.sideOrientation);
  70389. var instance = options.instance || null;
  70390. var invertUV = options.invertUV || false;
  70391. 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);
  70392. };
  70393. /**
  70394. * Creates an custom extruded shape mesh.
  70395. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  70396. * * 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.
  70397. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  70398. * * 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
  70399. * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  70400. * * 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
  70401. * * It must returns a float value that will be the scale value applied to the shape on each path point
  70402. * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  70403. * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
  70404. * * 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
  70405. * * The optional parameter `instance` is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters : https://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh#extruded-shape
  70406. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
  70407. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  70408. * * 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 : https://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  70409. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  70410. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  70411. * @param name defines the name of the mesh
  70412. * @param options defines the options used to create the mesh
  70413. * @param scene defines the hosting scene
  70414. * @returns the custom extruded shape mesh
  70415. * @see https://doc.babylonjs.com/how_to/parametric_shapes#custom-extruded-shapes
  70416. * @see https://doc.babylonjs.com/how_to/parametric_shapes
  70417. * @see https://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  70418. */
  70419. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  70420. var path = options.path;
  70421. var shape = options.shape;
  70422. var scaleFunction = options.scaleFunction || (function () { return 1; });
  70423. var rotationFunction = options.rotationFunction || (function () { return 0; });
  70424. var ribbonCloseArray = options.ribbonCloseArray || false;
  70425. var ribbonClosePath = options.ribbonClosePath || false;
  70426. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  70427. var updatable = options.updatable;
  70428. var sideOrientation = MeshBuilder._UpdateSideOrientation(options.sideOrientation);
  70429. var instance = options.instance;
  70430. var invertUV = options.invertUV || false;
  70431. 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);
  70432. };
  70433. /**
  70434. * Creates lathe mesh.
  70435. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
  70436. * * 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
  70437. * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
  70438. * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
  70439. * * The parameter `clip` (positive integer, default 0) is the number of sides to not create without effecting the general shape of the sides
  70440. * * 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
  70441. * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
  70442. * * 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
  70443. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  70444. * * 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 : https://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  70445. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  70446. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  70447. * @param name defines the name of the mesh
  70448. * @param options defines the options used to create the mesh
  70449. * @param scene defines the hosting scene
  70450. * @returns the lathe mesh
  70451. * @see https://doc.babylonjs.com/how_to/parametric_shapes#lathe
  70452. */
  70453. MeshBuilder.CreateLathe = function (name, options, scene) {
  70454. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  70455. var closed = (options.closed === undefined) ? true : options.closed;
  70456. var shape = options.shape;
  70457. var radius = options.radius || 1;
  70458. var tessellation = options.tessellation || 64;
  70459. var clip = options.clip || 0;
  70460. var updatable = options.updatable;
  70461. var sideOrientation = MeshBuilder._UpdateSideOrientation(options.sideOrientation);
  70462. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  70463. var pi2 = Math.PI * 2;
  70464. var paths = new Array();
  70465. var invertUV = options.invertUV || false;
  70466. var i = 0;
  70467. var p = 0;
  70468. var step = pi2 / tessellation * arc;
  70469. var rotated;
  70470. var path = new Array();
  70471. for (i = 0; i <= tessellation - clip; i++) {
  70472. var path = [];
  70473. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  70474. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  70475. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  70476. }
  70477. for (p = 0; p < shape.length; p++) {
  70478. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  70479. path.push(rotated);
  70480. }
  70481. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  70482. 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));
  70483. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  70484. }
  70485. paths.push(path);
  70486. }
  70487. // lathe ribbon
  70488. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  70489. return lathe;
  70490. };
  70491. /**
  70492. * Creates a plane mesh
  70493. * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
  70494. * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value of `size`)
  70495. * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
  70496. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  70497. * * 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 : https://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  70498. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  70499. * @param name defines the name of the mesh
  70500. * @param options defines the options used to create the mesh
  70501. * @param scene defines the hosting scene
  70502. * @returns the plane mesh
  70503. * @see https://doc.babylonjs.com/how_to/set_shapes#plane
  70504. */
  70505. MeshBuilder.CreatePlane = function (name, options, scene) {
  70506. var plane = new BABYLON.Mesh(name, scene);
  70507. options.sideOrientation = MeshBuilder._UpdateSideOrientation(options.sideOrientation);
  70508. plane._originalBuilderSideOrientation = options.sideOrientation;
  70509. var vertexData = BABYLON.VertexData.CreatePlane(options);
  70510. vertexData.applyToMesh(plane, options.updatable);
  70511. if (options.sourcePlane) {
  70512. plane.translate(options.sourcePlane.normal, -options.sourcePlane.d);
  70513. plane.setDirection(options.sourcePlane.normal.scale(-1));
  70514. }
  70515. return plane;
  70516. };
  70517. /**
  70518. * Creates a ground mesh
  70519. * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
  70520. * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
  70521. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  70522. * @param name defines the name of the mesh
  70523. * @param options defines the options used to create the mesh
  70524. * @param scene defines the hosting scene
  70525. * @returns the ground mesh
  70526. * @see https://doc.babylonjs.com/how_to/set_shapes#ground
  70527. */
  70528. MeshBuilder.CreateGround = function (name, options, scene) {
  70529. var ground = new BABYLON.GroundMesh(name, scene);
  70530. ground._setReady(false);
  70531. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  70532. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  70533. ground._width = options.width || 1;
  70534. ground._height = options.height || 1;
  70535. ground._maxX = ground._width / 2;
  70536. ground._maxZ = ground._height / 2;
  70537. ground._minX = -ground._maxX;
  70538. ground._minZ = -ground._maxZ;
  70539. var vertexData = BABYLON.VertexData.CreateGround(options);
  70540. vertexData.applyToMesh(ground, options.updatable);
  70541. ground._setReady(true);
  70542. return ground;
  70543. };
  70544. /**
  70545. * Creates a tiled ground mesh
  70546. * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
  70547. * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
  70548. * * 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
  70549. * * 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
  70550. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  70551. * @param name defines the name of the mesh
  70552. * @param options defines the options used to create the mesh
  70553. * @param scene defines the hosting scene
  70554. * @returns the tiled ground mesh
  70555. * @see https://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  70556. */
  70557. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  70558. var tiledGround = new BABYLON.Mesh(name, scene);
  70559. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  70560. vertexData.applyToMesh(tiledGround, options.updatable);
  70561. return tiledGround;
  70562. };
  70563. /**
  70564. * Creates a ground mesh from a height map
  70565. * * The parameter `url` sets the URL of the height map image resource.
  70566. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  70567. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  70568. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  70569. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  70570. * * 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.
  70571. * * 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).
  70572. * * The parameter `alphaFilter` will filter any data where the alpha channel is below this value, defaults 0 (all data visible)
  70573. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  70574. * @param name defines the name of the mesh
  70575. * @param url defines the url to the height map
  70576. * @param options defines the options used to create the mesh
  70577. * @param scene defines the hosting scene
  70578. * @returns the ground mesh
  70579. * @see https://doc.babylonjs.com/babylon101/height_map
  70580. * @see https://doc.babylonjs.com/how_to/set_shapes#ground-from-a-height-map
  70581. */
  70582. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  70583. var width = options.width || 10.0;
  70584. var height = options.height || 10.0;
  70585. var subdivisions = options.subdivisions || 1 | 0;
  70586. var minHeight = options.minHeight || 0.0;
  70587. var maxHeight = options.maxHeight || 1.0;
  70588. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  70589. var alphaFilter = options.alphaFilter || 0.0;
  70590. var updatable = options.updatable;
  70591. var onReady = options.onReady;
  70592. var ground = new BABYLON.GroundMesh(name, scene);
  70593. ground._subdivisionsX = subdivisions;
  70594. ground._subdivisionsY = subdivisions;
  70595. ground._width = width;
  70596. ground._height = height;
  70597. ground._maxX = ground._width / 2.0;
  70598. ground._maxZ = ground._height / 2.0;
  70599. ground._minX = -ground._maxX;
  70600. ground._minZ = -ground._maxZ;
  70601. ground._setReady(false);
  70602. var onload = function (img) {
  70603. // Getting height map data
  70604. var canvas = document.createElement("canvas");
  70605. var context = canvas.getContext("2d");
  70606. if (!context) {
  70607. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  70608. }
  70609. if (scene.isDisposed) {
  70610. return;
  70611. }
  70612. var bufferWidth = img.width;
  70613. var bufferHeight = img.height;
  70614. canvas.width = bufferWidth;
  70615. canvas.height = bufferHeight;
  70616. context.drawImage(img, 0, 0);
  70617. // Create VertexData from map data
  70618. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  70619. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  70620. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  70621. width: width, height: height,
  70622. subdivisions: subdivisions,
  70623. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  70624. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight,
  70625. alphaFilter: alphaFilter
  70626. });
  70627. vertexData.applyToMesh(ground, updatable);
  70628. //execute ready callback, if set
  70629. if (onReady) {
  70630. onReady(ground);
  70631. }
  70632. ground._setReady(true);
  70633. };
  70634. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.offlineProvider);
  70635. return ground;
  70636. };
  70637. /**
  70638. * Creates a polygon mesh
  70639. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
  70640. * * 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
  70641. * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  70642. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  70643. * * 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)
  70644. * * Remember you can only change the shape positions, not their number when updating a polygon
  70645. * @param name defines the name of the mesh
  70646. * @param options defines the options used to create the mesh
  70647. * @param scene defines the hosting scene
  70648. * @returns the polygon mesh
  70649. */
  70650. MeshBuilder.CreatePolygon = function (name, options, scene) {
  70651. options.sideOrientation = MeshBuilder._UpdateSideOrientation(options.sideOrientation);
  70652. var shape = options.shape;
  70653. var holes = options.holes || [];
  70654. var depth = options.depth || 0;
  70655. var contours = [];
  70656. var hole = [];
  70657. for (var i = 0; i < shape.length; i++) {
  70658. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  70659. }
  70660. var epsilon = 0.00000001;
  70661. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  70662. contours.pop();
  70663. }
  70664. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  70665. for (var hNb = 0; hNb < holes.length; hNb++) {
  70666. hole = [];
  70667. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  70668. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  70669. }
  70670. polygonTriangulation.addHole(hole);
  70671. }
  70672. var polygon = polygonTriangulation.build(options.updatable, depth);
  70673. polygon._originalBuilderSideOrientation = options.sideOrientation;
  70674. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  70675. vertexData.applyToMesh(polygon, options.updatable);
  70676. return polygon;
  70677. };
  70678. /**
  70679. * Creates an extruded polygon mesh, with depth in the Y direction.
  70680. * * 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)
  70681. * @see https://doc.babylonjs.com/how_to/createbox_per_face_textures_and_colors
  70682. * @param name defines the name of the mesh
  70683. * @param options defines the options used to create the mesh
  70684. * @param scene defines the hosting scene
  70685. * @returns the polygon mesh
  70686. */
  70687. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  70688. return MeshBuilder.CreatePolygon(name, options, scene);
  70689. };
  70690. /**
  70691. * Creates a tube mesh.
  70692. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  70693. * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
  70694. * * The parameter `radius` (positive float, default 1) sets the tube radius size
  70695. * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
  70696. * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
  70697. * * 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)
  70698. * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
  70699. * * 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
  70700. * * The optional parameter `instance` is an instance of an existing Tube object to be updated with the passed `pathArray` parameter : https://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh#tube
  70701. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  70702. * * 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 : https://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  70703. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  70704. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  70705. * @param name defines the name of the mesh
  70706. * @param options defines the options used to create the mesh
  70707. * @param scene defines the hosting scene
  70708. * @returns the tube mesh
  70709. * @see https://doc.babylonjs.com/how_to/parametric_shapes
  70710. * @see https://doc.babylonjs.com/how_to/set_shapes#tube
  70711. */
  70712. MeshBuilder.CreateTube = function (name, options, scene) {
  70713. var path = options.path;
  70714. var instance = options.instance;
  70715. var radius = 1.0;
  70716. if (options.radius !== undefined) {
  70717. radius = options.radius;
  70718. }
  70719. else if (instance) {
  70720. radius = instance._creationDataStorage.radius;
  70721. }
  70722. var tessellation = options.tessellation || 64 | 0;
  70723. var radiusFunction = options.radiusFunction || null;
  70724. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  70725. var invertUV = options.invertUV || false;
  70726. var updatable = options.updatable;
  70727. var sideOrientation = MeshBuilder._UpdateSideOrientation(options.sideOrientation);
  70728. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  70729. // tube geometry
  70730. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  70731. var tangents = path3D.getTangents();
  70732. var normals = path3D.getNormals();
  70733. var distances = path3D.getDistances();
  70734. var pi2 = Math.PI * 2;
  70735. var step = pi2 / tessellation * arc;
  70736. var returnRadius = function () { return radius; };
  70737. var radiusFunctionFinal = radiusFunction || returnRadius;
  70738. var circlePath;
  70739. var rad;
  70740. var normal;
  70741. var rotated;
  70742. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  70743. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  70744. for (var i = 0; i < path.length; i++) {
  70745. rad = radiusFunctionFinal(i, distances[i]); // current radius
  70746. circlePath = Array(); // current circle array
  70747. normal = normals[i]; // current normal
  70748. for (var t = 0; t < tessellation; t++) {
  70749. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  70750. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  70751. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  70752. rotated.scaleInPlace(rad).addInPlace(path[i]);
  70753. circlePath[t] = rotated;
  70754. }
  70755. circlePaths[index] = circlePath;
  70756. index++;
  70757. }
  70758. // cap
  70759. var capPath = function (nbPoints, pathIndex) {
  70760. var pointCap = Array();
  70761. for (var i = 0; i < nbPoints; i++) {
  70762. pointCap.push(path[pathIndex]);
  70763. }
  70764. return pointCap;
  70765. };
  70766. switch (cap) {
  70767. case BABYLON.Mesh.NO_CAP:
  70768. break;
  70769. case BABYLON.Mesh.CAP_START:
  70770. circlePaths[0] = capPath(tessellation, 0);
  70771. circlePaths[1] = circlePaths[2].slice(0);
  70772. break;
  70773. case BABYLON.Mesh.CAP_END:
  70774. circlePaths[index] = circlePaths[index - 1].slice(0);
  70775. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  70776. break;
  70777. case BABYLON.Mesh.CAP_ALL:
  70778. circlePaths[0] = capPath(tessellation, 0);
  70779. circlePaths[1] = circlePaths[2].slice(0);
  70780. circlePaths[index] = circlePaths[index - 1].slice(0);
  70781. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  70782. break;
  70783. default:
  70784. break;
  70785. }
  70786. return circlePaths;
  70787. };
  70788. var path3D;
  70789. var pathArray;
  70790. if (instance) { // tube update
  70791. var storage = instance._creationDataStorage;
  70792. var arc = options.arc || storage.arc;
  70793. path3D = storage.path3D.update(path);
  70794. pathArray = tubePathArray(path, path3D, storage.pathArray, radius, storage.tessellation, radiusFunction, storage.cap, arc);
  70795. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  70796. // Update mode, no need to recreate the storage.
  70797. storage.path3D = path3D;
  70798. storage.pathArray = pathArray;
  70799. storage.arc = arc;
  70800. storage.radius = radius;
  70801. return instance;
  70802. }
  70803. // tube creation
  70804. path3D = new BABYLON.Path3D(path);
  70805. var newPathArray = new Array();
  70806. cap = (cap < 0 || cap > 3) ? 0 : cap;
  70807. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  70808. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  70809. tube._creationDataStorage.pathArray = pathArray;
  70810. tube._creationDataStorage.path3D = path3D;
  70811. tube._creationDataStorage.tessellation = tessellation;
  70812. tube._creationDataStorage.cap = cap;
  70813. tube._creationDataStorage.arc = options.arc;
  70814. tube._creationDataStorage.radius = radius;
  70815. return tube;
  70816. };
  70817. /**
  70818. * Creates a polyhedron mesh
  70819. * * 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
  70820. * * The parameter `size` (positive float, default 1) sets the polygon size
  70821. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  70822. * * 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`
  70823. * * 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
  70824. * * 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)`)
  70825. * * 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 : https://doc.babylonjs.com/how_to/createbox_per_face_textures_and_colors
  70826. * * 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
  70827. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  70828. * * 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 : https://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  70829. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  70830. * @param name defines the name of the mesh
  70831. * @param options defines the options used to create the mesh
  70832. * @param scene defines the hosting scene
  70833. * @returns the polyhedron mesh
  70834. * @see https://doc.babylonjs.com/how_to/polyhedra_shapes
  70835. */
  70836. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  70837. var polyhedron = new BABYLON.Mesh(name, scene);
  70838. options.sideOrientation = MeshBuilder._UpdateSideOrientation(options.sideOrientation);
  70839. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  70840. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  70841. vertexData.applyToMesh(polyhedron, options.updatable);
  70842. return polyhedron;
  70843. };
  70844. /**
  70845. * Creates a decal mesh.
  70846. * 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
  70847. * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
  70848. * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
  70849. * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
  70850. * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
  70851. * @param name defines the name of the mesh
  70852. * @param sourceMesh defines the mesh where the decal must be applied
  70853. * @param options defines the options used to create the mesh
  70854. * @param scene defines the hosting scene
  70855. * @returns the decal mesh
  70856. * @see https://doc.babylonjs.com/how_to/decals
  70857. */
  70858. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  70859. var indices = sourceMesh.getIndices();
  70860. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  70861. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  70862. var position = options.position || BABYLON.Vector3.Zero();
  70863. var normal = options.normal || BABYLON.Vector3.Up();
  70864. var size = options.size || BABYLON.Vector3.One();
  70865. var angle = options.angle || 0;
  70866. // Getting correct rotation
  70867. if (!normal) {
  70868. var target = new BABYLON.Vector3(0, 0, 1);
  70869. var camera = sourceMesh.getScene().activeCamera;
  70870. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  70871. normal = camera.globalPosition.subtract(cameraWorldTarget);
  70872. }
  70873. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  70874. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  70875. var pitch = Math.atan2(normal.y, len);
  70876. // Matrix
  70877. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  70878. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  70879. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  70880. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  70881. var vertexData = new BABYLON.VertexData();
  70882. vertexData.indices = [];
  70883. vertexData.positions = [];
  70884. vertexData.normals = [];
  70885. vertexData.uvs = [];
  70886. var currentVertexDataIndex = 0;
  70887. var extractDecalVector3 = function (indexId) {
  70888. var result = new BABYLON.PositionNormalVertex();
  70889. if (!indices || !positions || !normals) {
  70890. return result;
  70891. }
  70892. var vertexId = indices[indexId];
  70893. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  70894. // Send vector to decal local world
  70895. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  70896. // Get normal
  70897. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  70898. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  70899. return result;
  70900. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  70901. var clip = function (vertices, axis) {
  70902. if (vertices.length === 0) {
  70903. return vertices;
  70904. }
  70905. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  70906. var clipVertices = function (v0, v1) {
  70907. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  70908. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  70909. };
  70910. var result = new Array();
  70911. for (var index = 0; index < vertices.length; index += 3) {
  70912. var v1Out;
  70913. var v2Out;
  70914. var v3Out;
  70915. var total = 0;
  70916. var nV1 = null;
  70917. var nV2 = null;
  70918. var nV3 = null;
  70919. var nV4 = null;
  70920. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  70921. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  70922. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  70923. v1Out = d1 > 0;
  70924. v2Out = d2 > 0;
  70925. v3Out = d3 > 0;
  70926. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  70927. switch (total) {
  70928. case 0:
  70929. result.push(vertices[index]);
  70930. result.push(vertices[index + 1]);
  70931. result.push(vertices[index + 2]);
  70932. break;
  70933. case 1:
  70934. if (v1Out) {
  70935. nV1 = vertices[index + 1];
  70936. nV2 = vertices[index + 2];
  70937. nV3 = clipVertices(vertices[index], nV1);
  70938. nV4 = clipVertices(vertices[index], nV2);
  70939. }
  70940. if (v2Out) {
  70941. nV1 = vertices[index];
  70942. nV2 = vertices[index + 2];
  70943. nV3 = clipVertices(vertices[index + 1], nV1);
  70944. nV4 = clipVertices(vertices[index + 1], nV2);
  70945. result.push(nV3);
  70946. result.push(nV2.clone());
  70947. result.push(nV1.clone());
  70948. result.push(nV2.clone());
  70949. result.push(nV3.clone());
  70950. result.push(nV4);
  70951. break;
  70952. }
  70953. if (v3Out) {
  70954. nV1 = vertices[index];
  70955. nV2 = vertices[index + 1];
  70956. nV3 = clipVertices(vertices[index + 2], nV1);
  70957. nV4 = clipVertices(vertices[index + 2], nV2);
  70958. }
  70959. if (nV1 && nV2 && nV3 && nV4) {
  70960. result.push(nV1.clone());
  70961. result.push(nV2.clone());
  70962. result.push(nV3);
  70963. result.push(nV4);
  70964. result.push(nV3.clone());
  70965. result.push(nV2.clone());
  70966. }
  70967. break;
  70968. case 2:
  70969. if (!v1Out) {
  70970. nV1 = vertices[index].clone();
  70971. nV2 = clipVertices(nV1, vertices[index + 1]);
  70972. nV3 = clipVertices(nV1, vertices[index + 2]);
  70973. result.push(nV1);
  70974. result.push(nV2);
  70975. result.push(nV3);
  70976. }
  70977. if (!v2Out) {
  70978. nV1 = vertices[index + 1].clone();
  70979. nV2 = clipVertices(nV1, vertices[index + 2]);
  70980. nV3 = clipVertices(nV1, vertices[index]);
  70981. result.push(nV1);
  70982. result.push(nV2);
  70983. result.push(nV3);
  70984. }
  70985. if (!v3Out) {
  70986. nV1 = vertices[index + 2].clone();
  70987. nV2 = clipVertices(nV1, vertices[index]);
  70988. nV3 = clipVertices(nV1, vertices[index + 1]);
  70989. result.push(nV1);
  70990. result.push(nV2);
  70991. result.push(nV3);
  70992. }
  70993. break;
  70994. case 3:
  70995. break;
  70996. }
  70997. }
  70998. return result;
  70999. };
  71000. for (var index = 0; index < indices.length; index += 3) {
  71001. var faceVertices = new Array();
  71002. faceVertices.push(extractDecalVector3(index));
  71003. faceVertices.push(extractDecalVector3(index + 1));
  71004. faceVertices.push(extractDecalVector3(index + 2));
  71005. // Clip
  71006. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  71007. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  71008. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  71009. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  71010. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  71011. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  71012. if (faceVertices.length === 0) {
  71013. continue;
  71014. }
  71015. // Add UVs and get back to world
  71016. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  71017. var vertex = faceVertices[vIndex];
  71018. //TODO check for Int32Array | Uint32Array | Uint16Array
  71019. vertexData.indices.push(currentVertexDataIndex);
  71020. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  71021. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  71022. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  71023. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  71024. currentVertexDataIndex++;
  71025. }
  71026. }
  71027. // Return mesh
  71028. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  71029. vertexData.applyToMesh(decal);
  71030. decal.position = position.clone();
  71031. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  71032. return decal;
  71033. };
  71034. // Privates
  71035. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  71036. // extrusion geometry
  71037. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  71038. var tangents = path3D.getTangents();
  71039. var normals = path3D.getNormals();
  71040. var binormals = path3D.getBinormals();
  71041. var distances = path3D.getDistances();
  71042. var angle = 0;
  71043. var returnScale = function () { return scale !== null ? scale : 1; };
  71044. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  71045. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  71046. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  71047. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  71048. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  71049. for (var i = 0; i < curve.length; i++) {
  71050. var shapePath = new Array();
  71051. var angleStep = rotate(i, distances[i]);
  71052. var scaleRatio = scl(i, distances[i]);
  71053. for (var p = 0; p < shape.length; p++) {
  71054. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  71055. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  71056. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  71057. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  71058. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  71059. shapePath[p] = rotated;
  71060. }
  71061. shapePaths[index] = shapePath;
  71062. angle += angleStep;
  71063. index++;
  71064. }
  71065. // cap
  71066. var capPath = function (shapePath) {
  71067. var pointCap = Array();
  71068. var barycenter = BABYLON.Vector3.Zero();
  71069. var i;
  71070. for (i = 0; i < shapePath.length; i++) {
  71071. barycenter.addInPlace(shapePath[i]);
  71072. }
  71073. barycenter.scaleInPlace(1.0 / shapePath.length);
  71074. for (i = 0; i < shapePath.length; i++) {
  71075. pointCap.push(barycenter);
  71076. }
  71077. return pointCap;
  71078. };
  71079. switch (cap) {
  71080. case BABYLON.Mesh.NO_CAP:
  71081. break;
  71082. case BABYLON.Mesh.CAP_START:
  71083. shapePaths[0] = capPath(shapePaths[2]);
  71084. shapePaths[1] = shapePaths[2];
  71085. break;
  71086. case BABYLON.Mesh.CAP_END:
  71087. shapePaths[index] = shapePaths[index - 1];
  71088. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  71089. break;
  71090. case BABYLON.Mesh.CAP_ALL:
  71091. shapePaths[0] = capPath(shapePaths[2]);
  71092. shapePaths[1] = shapePaths[2];
  71093. shapePaths[index] = shapePaths[index - 1];
  71094. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  71095. break;
  71096. default:
  71097. break;
  71098. }
  71099. return shapePaths;
  71100. };
  71101. var path3D;
  71102. var pathArray;
  71103. if (instance) { // instance update
  71104. var storage = instance._creationDataStorage;
  71105. path3D = storage.path3D.update(curve);
  71106. pathArray = extrusionPathArray(shape, curve, storage.path3D, storage.pathArray, scale, rotation, scaleFunction, rotateFunction, storage.cap, custom);
  71107. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  71108. return instance;
  71109. }
  71110. // extruded shape creation
  71111. path3D = new BABYLON.Path3D(curve);
  71112. var newShapePaths = new Array();
  71113. cap = (cap < 0 || cap > 3) ? 0 : cap;
  71114. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  71115. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  71116. extrudedGeneric._creationDataStorage.pathArray = pathArray;
  71117. extrudedGeneric._creationDataStorage.path3D = path3D;
  71118. extrudedGeneric._creationDataStorage.cap = cap;
  71119. return extrudedGeneric;
  71120. };
  71121. return MeshBuilder;
  71122. }());
  71123. BABYLON.MeshBuilder = MeshBuilder;
  71124. })(BABYLON || (BABYLON = {}));
  71125. //# sourceMappingURL=babylon.meshBuilder.js.map
  71126. var BABYLON;
  71127. (function (BABYLON) {
  71128. /**
  71129. * Draco compression (https://google.github.io/draco/)
  71130. *
  71131. * This class wraps the Draco module.
  71132. *
  71133. * **Encoder**
  71134. *
  71135. * The encoder is not currently implemented.
  71136. *
  71137. * **Decoder**
  71138. *
  71139. * 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.
  71140. *
  71141. * To update the configuration, use the following code:
  71142. * ```javascript
  71143. * BABYLON.DracoCompression.Configuration = {
  71144. * decoder: {
  71145. * wasmUrl: "<url to the WebAssembly library>",
  71146. * wasmBinaryUrl: "<url to the WebAssembly binary>",
  71147. * fallbackUrl: "<url to the fallback JavaScript library>",
  71148. * }
  71149. * };
  71150. * ```
  71151. *
  71152. * 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.
  71153. * Decoding will automatically fallback to the JavaScript version if WebAssembly version is not configured or if WebAssembly is not supported by the browser.
  71154. * Use `BABYLON.DracoCompression.DecoderAvailable` to determine if the decoder is available for the current session.
  71155. *
  71156. * To decode Draco compressed data, create a DracoCompression object and call decodeMeshAsync:
  71157. * ```javascript
  71158. * var dracoCompression = new BABYLON.DracoCompression();
  71159. * var vertexData = await dracoCompression.decodeMeshAsync(data, {
  71160. * [BABYLON.VertexBuffer.PositionKind]: 0
  71161. * });
  71162. * ```
  71163. *
  71164. * @see https://www.babylonjs-playground.com/#N3EK4B#0
  71165. */
  71166. var DracoCompression = /** @class */ (function () {
  71167. /**
  71168. * Constructor
  71169. */
  71170. function DracoCompression() {
  71171. }
  71172. Object.defineProperty(DracoCompression, "DecoderAvailable", {
  71173. /**
  71174. * Returns true if the decoder is available.
  71175. */
  71176. get: function () {
  71177. if (typeof DracoDecoderModule !== "undefined") {
  71178. return true;
  71179. }
  71180. var decoder = DracoCompression.Configuration.decoder;
  71181. if (decoder) {
  71182. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  71183. return true;
  71184. }
  71185. if (decoder.fallbackUrl) {
  71186. return true;
  71187. }
  71188. }
  71189. return false;
  71190. },
  71191. enumerable: true,
  71192. configurable: true
  71193. });
  71194. /**
  71195. * Stop all async operations and release resources.
  71196. */
  71197. DracoCompression.prototype.dispose = function () {
  71198. };
  71199. /**
  71200. * Decode Draco compressed mesh data to vertex data.
  71201. * @param data The ArrayBuffer or ArrayBufferView for the Draco compression data
  71202. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  71203. * @returns A promise that resolves with the decoded vertex data
  71204. */
  71205. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  71206. var dataView = data instanceof ArrayBuffer ? new Uint8Array(data) : data;
  71207. return DracoCompression._GetDecoderModule().then(function (wrappedModule) {
  71208. var module = wrappedModule.module;
  71209. var vertexData = new BABYLON.VertexData();
  71210. var buffer = new module.DecoderBuffer();
  71211. buffer.Init(dataView, dataView.byteLength);
  71212. var decoder = new module.Decoder();
  71213. var geometry;
  71214. var status;
  71215. try {
  71216. var type = decoder.GetEncodedGeometryType(buffer);
  71217. switch (type) {
  71218. case module.TRIANGULAR_MESH:
  71219. geometry = new module.Mesh();
  71220. status = decoder.DecodeBufferToMesh(buffer, geometry);
  71221. break;
  71222. case module.POINT_CLOUD:
  71223. geometry = new module.PointCloud();
  71224. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  71225. break;
  71226. default:
  71227. throw new Error("Invalid geometry type " + type);
  71228. }
  71229. if (!status.ok() || !geometry.ptr) {
  71230. throw new Error(status.error_msg());
  71231. }
  71232. var numPoints = geometry.num_points();
  71233. if (type === module.TRIANGULAR_MESH) {
  71234. var numFaces = geometry.num_faces();
  71235. var faceIndices = new module.DracoInt32Array();
  71236. try {
  71237. var indices = new Uint32Array(numFaces * 3);
  71238. for (var i = 0; i < numFaces; i++) {
  71239. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  71240. var offset = i * 3;
  71241. indices[offset + 0] = faceIndices.GetValue(0);
  71242. indices[offset + 1] = faceIndices.GetValue(1);
  71243. indices[offset + 2] = faceIndices.GetValue(2);
  71244. }
  71245. vertexData.indices = indices;
  71246. }
  71247. finally {
  71248. module.destroy(faceIndices);
  71249. }
  71250. }
  71251. for (var kind in attributes) {
  71252. var uniqueId = attributes[kind];
  71253. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  71254. var dracoData = new module.DracoFloat32Array();
  71255. try {
  71256. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  71257. var babylonData = new Float32Array(numPoints * attribute.num_components());
  71258. for (var i = 0; i < babylonData.length; i++) {
  71259. babylonData[i] = dracoData.GetValue(i);
  71260. }
  71261. vertexData.set(babylonData, kind);
  71262. }
  71263. finally {
  71264. module.destroy(dracoData);
  71265. }
  71266. }
  71267. }
  71268. finally {
  71269. if (geometry) {
  71270. module.destroy(geometry);
  71271. }
  71272. module.destroy(decoder);
  71273. module.destroy(buffer);
  71274. }
  71275. return vertexData;
  71276. });
  71277. };
  71278. DracoCompression._GetDecoderModule = function () {
  71279. if (!DracoCompression._DecoderModulePromise) {
  71280. var promise = null;
  71281. var config_1 = {};
  71282. if (typeof DracoDecoderModule !== "undefined") {
  71283. promise = Promise.resolve();
  71284. }
  71285. else {
  71286. var decoder = DracoCompression.Configuration.decoder;
  71287. if (decoder) {
  71288. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  71289. promise = Promise.all([
  71290. DracoCompression._LoadScriptAsync(decoder.wasmUrl),
  71291. DracoCompression._LoadFileAsync(decoder.wasmBinaryUrl).then(function (data) {
  71292. config_1.wasmBinary = data;
  71293. })
  71294. ]);
  71295. }
  71296. else if (decoder.fallbackUrl) {
  71297. promise = DracoCompression._LoadScriptAsync(decoder.fallbackUrl);
  71298. }
  71299. }
  71300. }
  71301. if (!promise) {
  71302. throw new Error("Draco decoder module is not available");
  71303. }
  71304. DracoCompression._DecoderModulePromise = promise.then(function () {
  71305. return new Promise(function (resolve) {
  71306. config_1.onModuleLoaded = function (decoderModule) {
  71307. // decoderModule is Promise-like. Wrap before resolving to avoid loop.
  71308. resolve({ module: decoderModule });
  71309. };
  71310. DracoDecoderModule(config_1);
  71311. });
  71312. });
  71313. }
  71314. return DracoCompression._DecoderModulePromise;
  71315. };
  71316. DracoCompression._LoadScriptAsync = function (url) {
  71317. return new Promise(function (resolve, reject) {
  71318. BABYLON.Tools.LoadScript(url, function () {
  71319. resolve();
  71320. }, function (message) {
  71321. reject(new Error(message));
  71322. });
  71323. });
  71324. };
  71325. DracoCompression._LoadFileAsync = function (url) {
  71326. return new Promise(function (resolve, reject) {
  71327. BABYLON.Tools.LoadFile(url, function (data) {
  71328. resolve(data);
  71329. }, undefined, undefined, true, function (request, exception) {
  71330. reject(exception);
  71331. });
  71332. });
  71333. };
  71334. /**
  71335. * The configuration. Defaults to the following urls:
  71336. * - wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js"
  71337. * - wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm"
  71338. * - fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  71339. */
  71340. DracoCompression.Configuration = {
  71341. decoder: {
  71342. wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",
  71343. wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm",
  71344. fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  71345. }
  71346. };
  71347. return DracoCompression;
  71348. }());
  71349. BABYLON.DracoCompression = DracoCompression;
  71350. })(BABYLON || (BABYLON = {}));
  71351. //# sourceMappingURL=babylon.dracoCompression.js.map
  71352. var BABYLON;
  71353. (function (BABYLON) {
  71354. // Sets the default audio engine to Babylon.js
  71355. BABYLON.Engine.AudioEngineFactory = function (hostElement) { return new AudioEngine(hostElement); };
  71356. /**
  71357. * This represents the default audio engine used in babylon.
  71358. * It is responsible to play, synchronize and analyse sounds throughout the application.
  71359. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  71360. */
  71361. var AudioEngine = /** @class */ (function () {
  71362. /**
  71363. * Instantiates a new audio engine.
  71364. *
  71365. * There should be only one per page as some browsers restrict the number
  71366. * of audio contexts you can create.
  71367. * @param hostElement defines the host element where to display the mute icon if necessary
  71368. */
  71369. function AudioEngine(hostElement) {
  71370. if (hostElement === void 0) { hostElement = null; }
  71371. var _this = this;
  71372. this._audioContext = null;
  71373. this._audioContextInitialized = false;
  71374. this._muteButton = null;
  71375. /**
  71376. * Gets whether the current host supports Web Audio and thus could create AudioContexts.
  71377. */
  71378. this.canUseWebAudio = false;
  71379. /**
  71380. * Defines if Babylon should emit a warning if WebAudio is not supported.
  71381. * @ignoreNaming
  71382. */
  71383. this.WarnedWebAudioUnsupported = false;
  71384. /**
  71385. * Gets whether or not mp3 are supported by your browser.
  71386. */
  71387. this.isMP3supported = false;
  71388. /**
  71389. * Gets whether or not ogg are supported by your browser.
  71390. */
  71391. this.isOGGsupported = false;
  71392. /**
  71393. * Gets whether audio has been unlocked on the device.
  71394. * Some Browsers have strong restrictions about Audio and won t autoplay unless
  71395. * a user interaction has happened.
  71396. */
  71397. this.unlocked = true;
  71398. /**
  71399. * Defines if the audio engine relies on a custom unlocked button.
  71400. * In this case, the embedded button will not be displayed.
  71401. */
  71402. this.useCustomUnlockedButton = false;
  71403. /**
  71404. * Event raised when audio has been unlocked on the browser.
  71405. */
  71406. this.onAudioUnlockedObservable = new BABYLON.Observable();
  71407. /**
  71408. * Event raised when audio has been locked on the browser.
  71409. */
  71410. this.onAudioLockedObservable = new BABYLON.Observable();
  71411. this._tryToRun = false;
  71412. this._onResize = function () {
  71413. _this._moveButtonToTopLeft();
  71414. };
  71415. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  71416. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  71417. this.canUseWebAudio = true;
  71418. }
  71419. var audioElem = document.createElement('audio');
  71420. this._hostElement = hostElement;
  71421. try {
  71422. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  71423. this.isMP3supported = true;
  71424. }
  71425. }
  71426. catch (e) {
  71427. // protect error during capability check.
  71428. }
  71429. try {
  71430. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  71431. this.isOGGsupported = true;
  71432. }
  71433. }
  71434. catch (e) {
  71435. // protect error during capability check.
  71436. }
  71437. }
  71438. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  71439. /**
  71440. * Gets the current AudioContext if available.
  71441. */
  71442. get: function () {
  71443. if (!this._audioContextInitialized) {
  71444. this._initializeAudioContext();
  71445. }
  71446. else {
  71447. if (!this.unlocked && !this._muteButton) {
  71448. this._displayMuteButton();
  71449. }
  71450. }
  71451. return this._audioContext;
  71452. },
  71453. enumerable: true,
  71454. configurable: true
  71455. });
  71456. /**
  71457. * Flags the audio engine in Locked state.
  71458. * This happens due to new browser policies preventing audio to autoplay.
  71459. */
  71460. AudioEngine.prototype.lock = function () {
  71461. this._triggerSuspendedState();
  71462. };
  71463. /**
  71464. * Unlocks the audio engine once a user action has been done on the dom.
  71465. * This is helpful to resume play once browser policies have been satisfied.
  71466. */
  71467. AudioEngine.prototype.unlock = function () {
  71468. this._triggerRunningState();
  71469. };
  71470. AudioEngine.prototype._resumeAudioContext = function () {
  71471. var result;
  71472. if (this._audioContext.resume) {
  71473. result = this._audioContext.resume();
  71474. }
  71475. return result || Promise.resolve();
  71476. };
  71477. AudioEngine.prototype._initializeAudioContext = function () {
  71478. try {
  71479. if (this.canUseWebAudio) {
  71480. this._audioContext = new AudioContext();
  71481. // create a global volume gain node
  71482. this.masterGain = this._audioContext.createGain();
  71483. this.masterGain.gain.value = 1;
  71484. this.masterGain.connect(this._audioContext.destination);
  71485. this._audioContextInitialized = true;
  71486. if (this._audioContext.state === "running") {
  71487. // Do not wait for the promise to unlock.
  71488. this._triggerRunningState();
  71489. }
  71490. }
  71491. }
  71492. catch (e) {
  71493. this.canUseWebAudio = false;
  71494. BABYLON.Tools.Error("Web Audio: " + e.message);
  71495. }
  71496. };
  71497. AudioEngine.prototype._triggerRunningState = function () {
  71498. var _this = this;
  71499. if (this._tryToRun) {
  71500. return;
  71501. }
  71502. this._tryToRun = true;
  71503. this._resumeAudioContext()
  71504. .then(function () {
  71505. _this._tryToRun = false;
  71506. if (_this._muteButton) {
  71507. _this._hideMuteButton();
  71508. }
  71509. }).catch(function () {
  71510. _this._tryToRun = false;
  71511. _this.unlocked = false;
  71512. });
  71513. // Notify users that the audio stack is unlocked/unmuted
  71514. this.unlocked = true;
  71515. this.onAudioUnlockedObservable.notifyObservers(this);
  71516. };
  71517. AudioEngine.prototype._triggerSuspendedState = function () {
  71518. this.unlocked = false;
  71519. this.onAudioLockedObservable.notifyObservers(this);
  71520. this._displayMuteButton();
  71521. };
  71522. AudioEngine.prototype._displayMuteButton = function () {
  71523. var _this = this;
  71524. if (this.useCustomUnlockedButton) {
  71525. return;
  71526. }
  71527. this._muteButton = document.createElement("BUTTON");
  71528. this._muteButton.className = "babylonUnmuteIcon";
  71529. this._muteButton.id = "babylonUnmuteIconBtn";
  71530. this._muteButton.title = "Unmute";
  71531. 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) }";
  71532. var style = document.createElement('style');
  71533. style.appendChild(document.createTextNode(css));
  71534. document.getElementsByTagName('head')[0].appendChild(style);
  71535. document.body.appendChild(this._muteButton);
  71536. this._moveButtonToTopLeft();
  71537. this._muteButton.addEventListener('touchend', function () {
  71538. _this._triggerRunningState();
  71539. }, true);
  71540. this._muteButton.addEventListener('click', function () {
  71541. _this._triggerRunningState();
  71542. }, true);
  71543. window.addEventListener("resize", this._onResize);
  71544. };
  71545. AudioEngine.prototype._moveButtonToTopLeft = function () {
  71546. if (this._hostElement && this._muteButton) {
  71547. this._muteButton.style.top = this._hostElement.offsetTop + 20 + "px";
  71548. this._muteButton.style.left = this._hostElement.offsetLeft + 20 + "px";
  71549. }
  71550. };
  71551. AudioEngine.prototype._hideMuteButton = function () {
  71552. if (this._muteButton) {
  71553. document.body.removeChild(this._muteButton);
  71554. this._muteButton = null;
  71555. }
  71556. };
  71557. /**
  71558. * Destroy and release the resources associated with the audio ccontext.
  71559. */
  71560. AudioEngine.prototype.dispose = function () {
  71561. if (this.canUseWebAudio && this._audioContextInitialized) {
  71562. if (this._connectedAnalyser && this._audioContext) {
  71563. this._connectedAnalyser.stopDebugCanvas();
  71564. this._connectedAnalyser.dispose();
  71565. this.masterGain.disconnect();
  71566. this.masterGain.connect(this._audioContext.destination);
  71567. this._connectedAnalyser = null;
  71568. }
  71569. this.masterGain.gain.value = 1;
  71570. }
  71571. this.WarnedWebAudioUnsupported = false;
  71572. this._hideMuteButton();
  71573. window.removeEventListener("resize", this._onResize);
  71574. this.onAudioUnlockedObservable.clear();
  71575. this.onAudioLockedObservable.clear();
  71576. };
  71577. /**
  71578. * Gets the global volume sets on the master gain.
  71579. * @returns the global volume if set or -1 otherwise
  71580. */
  71581. AudioEngine.prototype.getGlobalVolume = function () {
  71582. if (this.canUseWebAudio && this._audioContextInitialized) {
  71583. return this.masterGain.gain.value;
  71584. }
  71585. else {
  71586. return -1;
  71587. }
  71588. };
  71589. /**
  71590. * Sets the global volume of your experience (sets on the master gain).
  71591. * @param newVolume Defines the new global volume of the application
  71592. */
  71593. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  71594. if (this.canUseWebAudio && this._audioContextInitialized) {
  71595. this.masterGain.gain.value = newVolume;
  71596. }
  71597. };
  71598. /**
  71599. * Connect the audio engine to an audio analyser allowing some amazing
  71600. * synchornization between the sounds/music and your visualization (VuMeter for instance).
  71601. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#using-the-analyser
  71602. * @param analyser The analyser to connect to the engine
  71603. */
  71604. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  71605. if (this._connectedAnalyser) {
  71606. this._connectedAnalyser.stopDebugCanvas();
  71607. }
  71608. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  71609. this._connectedAnalyser = analyser;
  71610. this.masterGain.disconnect();
  71611. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  71612. }
  71613. };
  71614. return AudioEngine;
  71615. }());
  71616. BABYLON.AudioEngine = AudioEngine;
  71617. })(BABYLON || (BABYLON = {}));
  71618. //# sourceMappingURL=babylon.audioEngine.js.map
  71619. var BABYLON;
  71620. (function (BABYLON) {
  71621. /**
  71622. * Defines a sound that can be played in the application.
  71623. * The sound can either be an ambient track or a simple sound played in reaction to a user action.
  71624. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  71625. */
  71626. var Sound = /** @class */ (function () {
  71627. /**
  71628. * Create a sound and attach it to a scene
  71629. * @param name Name of your sound
  71630. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer, it also works with MediaStreams
  71631. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  71632. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  71633. */
  71634. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  71635. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  71636. var _this = this;
  71637. /**
  71638. * Does the sound autoplay once loaded.
  71639. */
  71640. this.autoplay = false;
  71641. /**
  71642. * Does the sound loop after it finishes playing once.
  71643. */
  71644. this.loop = false;
  71645. /**
  71646. * Does the sound use a custom attenuation curve to simulate the falloff
  71647. * happening when the source gets further away from the camera.
  71648. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-your-own-custom-attenuation-function
  71649. */
  71650. this.useCustomAttenuation = false;
  71651. /**
  71652. * Is this sound currently played.
  71653. */
  71654. this.isPlaying = false;
  71655. /**
  71656. * Is this sound currently paused.
  71657. */
  71658. this.isPaused = false;
  71659. /**
  71660. * Does this sound enables spatial sound.
  71661. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  71662. */
  71663. this.spatialSound = false;
  71664. /**
  71665. * Define the reference distance the sound should be heard perfectly.
  71666. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  71667. */
  71668. this.refDistance = 1;
  71669. /**
  71670. * Define the roll off factor of spatial sounds.
  71671. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  71672. */
  71673. this.rolloffFactor = 1;
  71674. /**
  71675. * Define the max distance the sound should be heard (intensity just became 0 at this point).
  71676. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  71677. */
  71678. this.maxDistance = 100;
  71679. /**
  71680. * Define the distance attenuation model the sound will follow.
  71681. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  71682. */
  71683. this.distanceModel = "linear";
  71684. /**
  71685. * Observable event when the current playing sound finishes.
  71686. */
  71687. this.onEndedObservable = new BABYLON.Observable();
  71688. this._panningModel = "equalpower";
  71689. this._playbackRate = 1;
  71690. this._streaming = false;
  71691. this._startTime = 0;
  71692. this._startOffset = 0;
  71693. this._position = BABYLON.Vector3.Zero();
  71694. /** @hidden */
  71695. this._positionInEmitterSpace = false;
  71696. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  71697. this._volume = 1;
  71698. this._isReadyToPlay = false;
  71699. this._isDirectional = false;
  71700. // Used if you'd like to create a directional sound.
  71701. // If not set, the sound will be omnidirectional
  71702. this._coneInnerAngle = 360;
  71703. this._coneOuterAngle = 360;
  71704. this._coneOuterGain = 0;
  71705. this._isOutputConnected = false;
  71706. this._urlType = "Unknown";
  71707. this.name = name;
  71708. this._scene = scene;
  71709. var compo = scene._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  71710. if (!compo) {
  71711. compo = new BABYLON.AudioSceneComponent(scene);
  71712. scene._addComponent(compo);
  71713. }
  71714. this._readyToPlayCallback = readyToPlayCallback;
  71715. // Default custom attenuation function is a linear attenuation
  71716. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  71717. if (currentDistance < maxDistance) {
  71718. return currentVolume * (1 - currentDistance / maxDistance);
  71719. }
  71720. else {
  71721. return 0;
  71722. }
  71723. };
  71724. if (options) {
  71725. this.autoplay = options.autoplay || false;
  71726. this.loop = options.loop || false;
  71727. // if volume === 0, we need another way to check this option
  71728. if (options.volume !== undefined) {
  71729. this._volume = options.volume;
  71730. }
  71731. this.spatialSound = options.spatialSound || false;
  71732. this.maxDistance = options.maxDistance || 100;
  71733. this.useCustomAttenuation = options.useCustomAttenuation || false;
  71734. this.rolloffFactor = options.rolloffFactor || 1;
  71735. this.refDistance = options.refDistance || 1;
  71736. this.distanceModel = options.distanceModel || "linear";
  71737. this._playbackRate = options.playbackRate || 1;
  71738. this._streaming = options.streaming || false;
  71739. }
  71740. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  71741. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  71742. this._soundGain.gain.value = this._volume;
  71743. this._inputAudioNode = this._soundGain;
  71744. this._outputAudioNode = this._soundGain;
  71745. if (this.spatialSound) {
  71746. this._createSpatialParameters();
  71747. }
  71748. this._scene.mainSoundTrack.AddSound(this);
  71749. var validParameter = true;
  71750. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  71751. if (urlOrArrayBuffer) {
  71752. try {
  71753. if (typeof (urlOrArrayBuffer) === "string") {
  71754. this._urlType = "String";
  71755. }
  71756. else if (urlOrArrayBuffer instanceof ArrayBuffer) {
  71757. this._urlType = "ArrayBuffer";
  71758. }
  71759. else if (urlOrArrayBuffer instanceof MediaStream) {
  71760. this._urlType = "MediaStream";
  71761. }
  71762. else if (Array.isArray(urlOrArrayBuffer)) {
  71763. this._urlType = "Array";
  71764. }
  71765. var urls = [];
  71766. var codecSupportedFound = false;
  71767. switch (this._urlType) {
  71768. case "MediaStream":
  71769. this._streaming = true;
  71770. this._isReadyToPlay = true;
  71771. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(urlOrArrayBuffer);
  71772. if (this.autoplay) {
  71773. this.play();
  71774. }
  71775. if (this._readyToPlayCallback) {
  71776. this._readyToPlayCallback();
  71777. }
  71778. break;
  71779. case "ArrayBuffer":
  71780. if (urlOrArrayBuffer.byteLength > 0) {
  71781. codecSupportedFound = true;
  71782. this._soundLoaded(urlOrArrayBuffer);
  71783. }
  71784. break;
  71785. case "String":
  71786. urls.push(urlOrArrayBuffer);
  71787. case "Array":
  71788. if (urls.length === 0) {
  71789. urls = urlOrArrayBuffer;
  71790. }
  71791. // If we found a supported format, we load it immediately and stop the loop
  71792. for (var i = 0; i < urls.length; i++) {
  71793. var url = urls[i];
  71794. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  71795. codecSupportedFound = true;
  71796. }
  71797. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  71798. codecSupportedFound = true;
  71799. }
  71800. if (url.indexOf(".wav", url.length - 4) !== -1) {
  71801. codecSupportedFound = true;
  71802. }
  71803. if (url.indexOf("blob:") !== -1) {
  71804. codecSupportedFound = true;
  71805. }
  71806. if (codecSupportedFound) {
  71807. // Loading sound using XHR2
  71808. if (!this._streaming) {
  71809. this._scene._loadFile(url, function (data) {
  71810. _this._soundLoaded(data);
  71811. }, undefined, true, true, function (exception) {
  71812. if (exception) {
  71813. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  71814. }
  71815. BABYLON.Tools.Error("Sound creation aborted.");
  71816. _this._scene.mainSoundTrack.RemoveSound(_this);
  71817. });
  71818. }
  71819. // Streaming sound using HTML5 Audio tag
  71820. else {
  71821. this._htmlAudioElement = new Audio(url);
  71822. this._htmlAudioElement.controls = false;
  71823. this._htmlAudioElement.loop = this.loop;
  71824. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  71825. this._htmlAudioElement.preload = "auto";
  71826. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  71827. _this._isReadyToPlay = true;
  71828. if (_this.autoplay) {
  71829. _this.play();
  71830. }
  71831. if (_this._readyToPlayCallback) {
  71832. _this._readyToPlayCallback();
  71833. }
  71834. });
  71835. document.body.appendChild(this._htmlAudioElement);
  71836. this._htmlAudioElement.load();
  71837. }
  71838. break;
  71839. }
  71840. }
  71841. break;
  71842. default:
  71843. validParameter = false;
  71844. break;
  71845. }
  71846. if (!validParameter) {
  71847. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  71848. }
  71849. else {
  71850. if (!codecSupportedFound) {
  71851. this._isReadyToPlay = true;
  71852. // Simulating a ready to play event to avoid breaking code path
  71853. if (this._readyToPlayCallback) {
  71854. window.setTimeout(function () {
  71855. if (_this._readyToPlayCallback) {
  71856. _this._readyToPlayCallback();
  71857. }
  71858. }, 1000);
  71859. }
  71860. }
  71861. }
  71862. }
  71863. catch (ex) {
  71864. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  71865. this._scene.mainSoundTrack.RemoveSound(this);
  71866. }
  71867. }
  71868. }
  71869. else {
  71870. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  71871. this._scene.mainSoundTrack.AddSound(this);
  71872. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  71873. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  71874. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  71875. }
  71876. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  71877. if (this._readyToPlayCallback) {
  71878. window.setTimeout(function () {
  71879. if (_this._readyToPlayCallback) {
  71880. _this._readyToPlayCallback();
  71881. }
  71882. }, 1000);
  71883. }
  71884. }
  71885. }
  71886. /**
  71887. * Release the sound and its associated resources
  71888. */
  71889. Sound.prototype.dispose = function () {
  71890. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  71891. if (this.isPlaying) {
  71892. this.stop();
  71893. }
  71894. this._isReadyToPlay = false;
  71895. if (this.soundTrackId === -1) {
  71896. this._scene.mainSoundTrack.RemoveSound(this);
  71897. }
  71898. else if (this._scene.soundTracks) {
  71899. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  71900. }
  71901. if (this._soundGain) {
  71902. this._soundGain.disconnect();
  71903. this._soundGain = null;
  71904. }
  71905. if (this._soundPanner) {
  71906. this._soundPanner.disconnect();
  71907. this._soundPanner = null;
  71908. }
  71909. if (this._soundSource) {
  71910. this._soundSource.disconnect();
  71911. this._soundSource = null;
  71912. }
  71913. this._audioBuffer = null;
  71914. if (this._htmlAudioElement) {
  71915. this._htmlAudioElement.pause();
  71916. this._htmlAudioElement.src = "";
  71917. document.body.removeChild(this._htmlAudioElement);
  71918. }
  71919. if (this._streamingSource) {
  71920. this._streamingSource.disconnect();
  71921. }
  71922. if (this._connectedTransformNode && this._registerFunc) {
  71923. this._connectedTransformNode.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  71924. this._connectedTransformNode = null;
  71925. }
  71926. }
  71927. };
  71928. /**
  71929. * Gets if the sounds is ready to be played or not.
  71930. * @returns true if ready, otherwise false
  71931. */
  71932. Sound.prototype.isReady = function () {
  71933. return this._isReadyToPlay;
  71934. };
  71935. Sound.prototype._soundLoaded = function (audioData) {
  71936. var _this = this;
  71937. if (!BABYLON.Engine.audioEngine.audioContext) {
  71938. return;
  71939. }
  71940. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  71941. _this._audioBuffer = buffer;
  71942. _this._isReadyToPlay = true;
  71943. if (_this.autoplay) {
  71944. _this.play();
  71945. }
  71946. if (_this._readyToPlayCallback) {
  71947. _this._readyToPlayCallback();
  71948. }
  71949. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  71950. };
  71951. /**
  71952. * Sets the data of the sound from an audiobuffer
  71953. * @param audioBuffer The audioBuffer containing the data
  71954. */
  71955. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  71956. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  71957. this._audioBuffer = audioBuffer;
  71958. this._isReadyToPlay = true;
  71959. }
  71960. };
  71961. /**
  71962. * Updates the current sounds options such as maxdistance, loop...
  71963. * @param options A JSON object containing values named as the object properties
  71964. */
  71965. Sound.prototype.updateOptions = function (options) {
  71966. if (options) {
  71967. this.loop = options.loop || this.loop;
  71968. this.maxDistance = options.maxDistance || this.maxDistance;
  71969. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  71970. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  71971. this.refDistance = options.refDistance || this.refDistance;
  71972. this.distanceModel = options.distanceModel || this.distanceModel;
  71973. this._playbackRate = options.playbackRate || this._playbackRate;
  71974. this._updateSpatialParameters();
  71975. if (this.isPlaying) {
  71976. if (this._streaming && this._htmlAudioElement) {
  71977. this._htmlAudioElement.playbackRate = this._playbackRate;
  71978. }
  71979. else {
  71980. if (this._soundSource) {
  71981. this._soundSource.playbackRate.value = this._playbackRate;
  71982. }
  71983. }
  71984. }
  71985. }
  71986. };
  71987. Sound.prototype._createSpatialParameters = function () {
  71988. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  71989. if (this._scene.headphone) {
  71990. this._panningModel = "HRTF";
  71991. }
  71992. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  71993. this._updateSpatialParameters();
  71994. this._soundPanner.connect(this._outputAudioNode);
  71995. this._inputAudioNode = this._soundPanner;
  71996. }
  71997. };
  71998. Sound.prototype._updateSpatialParameters = function () {
  71999. if (this.spatialSound && this._soundPanner) {
  72000. if (this.useCustomAttenuation) {
  72001. // Tricks to disable in a way embedded Web Audio attenuation
  72002. this._soundPanner.distanceModel = "linear";
  72003. this._soundPanner.maxDistance = Number.MAX_VALUE;
  72004. this._soundPanner.refDistance = 1;
  72005. this._soundPanner.rolloffFactor = 1;
  72006. this._soundPanner.panningModel = this._panningModel;
  72007. }
  72008. else {
  72009. this._soundPanner.distanceModel = this.distanceModel;
  72010. this._soundPanner.maxDistance = this.maxDistance;
  72011. this._soundPanner.refDistance = this.refDistance;
  72012. this._soundPanner.rolloffFactor = this.rolloffFactor;
  72013. this._soundPanner.panningModel = this._panningModel;
  72014. }
  72015. }
  72016. };
  72017. /**
  72018. * Switch the panning model to HRTF:
  72019. * Renders a stereo output of higher quality than equalpower — it uses a convolution with measured impulse responses from human subjects.
  72020. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  72021. */
  72022. Sound.prototype.switchPanningModelToHRTF = function () {
  72023. this._panningModel = "HRTF";
  72024. this._switchPanningModel();
  72025. };
  72026. /**
  72027. * Switch the panning model to Equal Power:
  72028. * Represents the equal-power panning algorithm, generally regarded as simple and efficient. equalpower is the default value.
  72029. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  72030. */
  72031. Sound.prototype.switchPanningModelToEqualPower = function () {
  72032. this._panningModel = "equalpower";
  72033. this._switchPanningModel();
  72034. };
  72035. Sound.prototype._switchPanningModel = function () {
  72036. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  72037. this._soundPanner.panningModel = this._panningModel;
  72038. }
  72039. };
  72040. /**
  72041. * Connect this sound to a sound track audio node like gain...
  72042. * @param soundTrackAudioNode the sound track audio node to connect to
  72043. */
  72044. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  72045. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  72046. if (this._isOutputConnected) {
  72047. this._outputAudioNode.disconnect();
  72048. }
  72049. this._outputAudioNode.connect(soundTrackAudioNode);
  72050. this._isOutputConnected = true;
  72051. }
  72052. };
  72053. /**
  72054. * Transform this sound into a directional source
  72055. * @param coneInnerAngle Size of the inner cone in degree
  72056. * @param coneOuterAngle Size of the outer cone in degree
  72057. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  72058. */
  72059. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  72060. if (coneOuterAngle < coneInnerAngle) {
  72061. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  72062. return;
  72063. }
  72064. this._coneInnerAngle = coneInnerAngle;
  72065. this._coneOuterAngle = coneOuterAngle;
  72066. this._coneOuterGain = coneOuterGain;
  72067. this._isDirectional = true;
  72068. if (this.isPlaying && this.loop) {
  72069. this.stop();
  72070. this.play();
  72071. }
  72072. };
  72073. Object.defineProperty(Sound.prototype, "directionalConeInnerAngle", {
  72074. /**
  72075. * Gets or sets the inner angle for the directional cone.
  72076. */
  72077. get: function () {
  72078. return this._coneInnerAngle;
  72079. },
  72080. /**
  72081. * Gets or sets the inner angle for the directional cone.
  72082. */
  72083. set: function (value) {
  72084. if (value != this._coneInnerAngle) {
  72085. if (this._coneOuterAngle < value) {
  72086. BABYLON.Tools.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");
  72087. return;
  72088. }
  72089. this._coneInnerAngle = value;
  72090. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  72091. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  72092. }
  72093. }
  72094. },
  72095. enumerable: true,
  72096. configurable: true
  72097. });
  72098. Object.defineProperty(Sound.prototype, "directionalConeOuterAngle", {
  72099. /**
  72100. * Gets or sets the outer angle for the directional cone.
  72101. */
  72102. get: function () {
  72103. return this._coneOuterAngle;
  72104. },
  72105. /**
  72106. * Gets or sets the outer angle for the directional cone.
  72107. */
  72108. set: function (value) {
  72109. if (value != this._coneOuterAngle) {
  72110. if (value < this._coneInnerAngle) {
  72111. BABYLON.Tools.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");
  72112. return;
  72113. }
  72114. this._coneOuterAngle = value;
  72115. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  72116. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  72117. }
  72118. }
  72119. },
  72120. enumerable: true,
  72121. configurable: true
  72122. });
  72123. /**
  72124. * Sets the position of the emitter if spatial sound is enabled
  72125. * @param newPosition Defines the new posisiton
  72126. */
  72127. Sound.prototype.setPosition = function (newPosition) {
  72128. this._position = newPosition;
  72129. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner && !isNaN(this._position.x) && !isNaN(this._position.y) && !isNaN(this._position.z)) {
  72130. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  72131. }
  72132. };
  72133. /**
  72134. * Sets the local direction of the emitter if spatial sound is enabled
  72135. * @param newLocalDirection Defines the new local direction
  72136. */
  72137. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  72138. this._localDirection = newLocalDirection;
  72139. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedTransformNode && this.isPlaying) {
  72140. this._updateDirection();
  72141. }
  72142. };
  72143. Sound.prototype._updateDirection = function () {
  72144. if (!this._connectedTransformNode || !this._soundPanner) {
  72145. return;
  72146. }
  72147. var mat = this._connectedTransformNode.getWorldMatrix();
  72148. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  72149. direction.normalize();
  72150. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  72151. };
  72152. /** @hidden */
  72153. Sound.prototype.updateDistanceFromListener = function () {
  72154. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedTransformNode && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  72155. var distance = this._connectedTransformNode.getDistanceToCamera(this._scene.activeCamera);
  72156. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  72157. }
  72158. };
  72159. /**
  72160. * Sets a new custom attenuation function for the sound.
  72161. * @param callback Defines the function used for the attenuation
  72162. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-your-own-custom-attenuation-function
  72163. */
  72164. Sound.prototype.setAttenuationFunction = function (callback) {
  72165. this._customAttenuationFunction = callback;
  72166. };
  72167. /**
  72168. * Play the sound
  72169. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  72170. * @param offset (optional) Start the sound setting it at a specific time
  72171. */
  72172. Sound.prototype.play = function (time, offset) {
  72173. var _this = this;
  72174. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  72175. try {
  72176. if (this._startOffset < 0) {
  72177. time = -this._startOffset;
  72178. this._startOffset = 0;
  72179. }
  72180. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  72181. if (!this._soundSource || !this._streamingSource) {
  72182. if (this.spatialSound && this._soundPanner) {
  72183. if (!isNaN(this._position.x) && !isNaN(this._position.y) && !isNaN(this._position.z)) {
  72184. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  72185. }
  72186. if (this._isDirectional) {
  72187. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  72188. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  72189. this._soundPanner.coneOuterGain = this._coneOuterGain;
  72190. if (this._connectedTransformNode) {
  72191. this._updateDirection();
  72192. }
  72193. else {
  72194. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  72195. }
  72196. }
  72197. }
  72198. }
  72199. if (this._streaming) {
  72200. if (!this._streamingSource) {
  72201. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  72202. this._htmlAudioElement.onended = function () { _this._onended(); };
  72203. this._htmlAudioElement.playbackRate = this._playbackRate;
  72204. }
  72205. this._streamingSource.disconnect();
  72206. this._streamingSource.connect(this._inputAudioNode);
  72207. if (this._htmlAudioElement) {
  72208. // required to manage properly the new suspended default state of Chrome
  72209. // When the option 'streaming: true' is used, we need first to wait for
  72210. // the audio engine to be unlocked by a user gesture before trying to play
  72211. // an HTML Audio elememt
  72212. var tryToPlay = function () {
  72213. if (BABYLON.Engine.audioEngine.unlocked) {
  72214. var playPromise = _this._htmlAudioElement.play();
  72215. // In browsers that don’t yet support this functionality,
  72216. // playPromise won’t be defined.
  72217. if (playPromise !== undefined) {
  72218. playPromise.catch(function (error) {
  72219. // Automatic playback failed.
  72220. // Waiting for the audio engine to be unlocked by user click on unmute
  72221. BABYLON.Engine.audioEngine.lock();
  72222. BABYLON.Engine.audioEngine.onAudioUnlockedObservable.addOnce(function () { tryToPlay(); });
  72223. });
  72224. }
  72225. }
  72226. else {
  72227. BABYLON.Engine.audioEngine.onAudioUnlockedObservable.addOnce(function () { tryToPlay(); });
  72228. }
  72229. };
  72230. tryToPlay();
  72231. }
  72232. }
  72233. else {
  72234. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  72235. this._soundSource.buffer = this._audioBuffer;
  72236. this._soundSource.connect(this._inputAudioNode);
  72237. this._soundSource.loop = this.loop;
  72238. this._soundSource.playbackRate.value = this._playbackRate;
  72239. this._soundSource.onended = function () { _this._onended(); };
  72240. if (this._soundSource.buffer) {
  72241. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  72242. }
  72243. }
  72244. this._startTime = startTime;
  72245. this.isPlaying = true;
  72246. this.isPaused = false;
  72247. }
  72248. catch (ex) {
  72249. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  72250. }
  72251. }
  72252. };
  72253. Sound.prototype._onended = function () {
  72254. this.isPlaying = false;
  72255. if (this.onended) {
  72256. this.onended();
  72257. }
  72258. this.onEndedObservable.notifyObservers(this);
  72259. };
  72260. /**
  72261. * Stop the sound
  72262. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  72263. */
  72264. Sound.prototype.stop = function (time) {
  72265. if (this.isPlaying) {
  72266. if (this._streaming) {
  72267. if (this._htmlAudioElement) {
  72268. this._htmlAudioElement.pause();
  72269. // Test needed for Firefox or it will generate an Invalid State Error
  72270. if (this._htmlAudioElement.currentTime > 0) {
  72271. this._htmlAudioElement.currentTime = 0;
  72272. }
  72273. }
  72274. else {
  72275. this._streamingSource.disconnect();
  72276. }
  72277. }
  72278. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  72279. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  72280. this._soundSource.stop(stopTime);
  72281. this._soundSource.onended = function () { };
  72282. if (!this.isPaused) {
  72283. this._startOffset = 0;
  72284. }
  72285. }
  72286. this.isPlaying = false;
  72287. }
  72288. };
  72289. /**
  72290. * Put the sound in pause
  72291. */
  72292. Sound.prototype.pause = function () {
  72293. if (this.isPlaying) {
  72294. this.isPaused = true;
  72295. if (this._streaming) {
  72296. if (this._htmlAudioElement) {
  72297. this._htmlAudioElement.pause();
  72298. }
  72299. else {
  72300. this._streamingSource.disconnect();
  72301. }
  72302. }
  72303. else if (BABYLON.Engine.audioEngine.audioContext) {
  72304. this.stop(0);
  72305. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  72306. }
  72307. }
  72308. };
  72309. /**
  72310. * Sets a dedicated volume for this sounds
  72311. * @param newVolume Define the new volume of the sound
  72312. * @param time Define in how long the sound should be at this value
  72313. */
  72314. Sound.prototype.setVolume = function (newVolume, time) {
  72315. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  72316. if (time && BABYLON.Engine.audioEngine.audioContext) {
  72317. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  72318. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  72319. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  72320. }
  72321. else {
  72322. this._soundGain.gain.value = newVolume;
  72323. }
  72324. }
  72325. this._volume = newVolume;
  72326. };
  72327. /**
  72328. * Set the sound play back rate
  72329. * @param newPlaybackRate Define the playback rate the sound should be played at
  72330. */
  72331. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  72332. this._playbackRate = newPlaybackRate;
  72333. if (this.isPlaying) {
  72334. if (this._streaming && this._htmlAudioElement) {
  72335. this._htmlAudioElement.playbackRate = this._playbackRate;
  72336. }
  72337. else if (this._soundSource) {
  72338. this._soundSource.playbackRate.value = this._playbackRate;
  72339. }
  72340. }
  72341. };
  72342. /**
  72343. * Gets the volume of the sound.
  72344. * @returns the volume of the sound
  72345. */
  72346. Sound.prototype.getVolume = function () {
  72347. return this._volume;
  72348. };
  72349. /**
  72350. * Attach the sound to a dedicated mesh
  72351. * @param transformNode The transform node to connect the sound with
  72352. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#attaching-a-sound-to-a-mesh
  72353. */
  72354. Sound.prototype.attachToMesh = function (transformNode) {
  72355. var _this = this;
  72356. if (this._connectedTransformNode && this._registerFunc) {
  72357. this._connectedTransformNode.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  72358. this._registerFunc = null;
  72359. }
  72360. this._connectedTransformNode = transformNode;
  72361. if (!this.spatialSound) {
  72362. this.spatialSound = true;
  72363. this._createSpatialParameters();
  72364. if (this.isPlaying && this.loop) {
  72365. this.stop();
  72366. this.play();
  72367. }
  72368. }
  72369. this._onRegisterAfterWorldMatrixUpdate(this._connectedTransformNode);
  72370. this._registerFunc = function (transformNode) { return _this._onRegisterAfterWorldMatrixUpdate(transformNode); };
  72371. this._connectedTransformNode.registerAfterWorldMatrixUpdate(this._registerFunc);
  72372. };
  72373. /**
  72374. * Detach the sound from the previously attached mesh
  72375. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#attaching-a-sound-to-a-mesh
  72376. */
  72377. Sound.prototype.detachFromMesh = function () {
  72378. if (this._connectedTransformNode && this._registerFunc) {
  72379. this._connectedTransformNode.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  72380. this._registerFunc = null;
  72381. this._connectedTransformNode = null;
  72382. }
  72383. };
  72384. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  72385. if (!node.getBoundingInfo) {
  72386. return;
  72387. }
  72388. var mesh = node;
  72389. if (this._positionInEmitterSpace) {
  72390. mesh.worldMatrixFromCache.invertToRef(BABYLON.Tmp.Matrix[0]);
  72391. this.setPosition(BABYLON.Tmp.Matrix[0].getTranslation());
  72392. }
  72393. else {
  72394. var boundingInfo = mesh.getBoundingInfo();
  72395. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  72396. }
  72397. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  72398. this._updateDirection();
  72399. }
  72400. };
  72401. /**
  72402. * Clone the current sound in the scene.
  72403. * @returns the new sound clone
  72404. */
  72405. Sound.prototype.clone = function () {
  72406. var _this = this;
  72407. if (!this._streaming) {
  72408. var setBufferAndRun = function () {
  72409. if (_this._isReadyToPlay) {
  72410. clonedSound._audioBuffer = _this.getAudioBuffer();
  72411. clonedSound._isReadyToPlay = true;
  72412. if (clonedSound.autoplay) {
  72413. clonedSound.play();
  72414. }
  72415. }
  72416. else {
  72417. window.setTimeout(setBufferAndRun, 300);
  72418. }
  72419. };
  72420. var currentOptions = {
  72421. autoplay: this.autoplay, loop: this.loop,
  72422. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  72423. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  72424. refDistance: this.refDistance, distanceModel: this.distanceModel
  72425. };
  72426. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  72427. if (this.useCustomAttenuation) {
  72428. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  72429. }
  72430. clonedSound.setPosition(this._position);
  72431. clonedSound.setPlaybackRate(this._playbackRate);
  72432. setBufferAndRun();
  72433. return clonedSound;
  72434. }
  72435. // Can't clone a streaming sound
  72436. else {
  72437. return null;
  72438. }
  72439. };
  72440. /**
  72441. * Gets the current underlying audio buffer containing the data
  72442. * @returns the audio buffer
  72443. */
  72444. Sound.prototype.getAudioBuffer = function () {
  72445. return this._audioBuffer;
  72446. };
  72447. /**
  72448. * Serializes the Sound in a JSON representation
  72449. * @returns the JSON representation of the sound
  72450. */
  72451. Sound.prototype.serialize = function () {
  72452. var serializationObject = {
  72453. name: this.name,
  72454. url: this.name,
  72455. autoplay: this.autoplay,
  72456. loop: this.loop,
  72457. volume: this._volume,
  72458. spatialSound: this.spatialSound,
  72459. maxDistance: this.maxDistance,
  72460. rolloffFactor: this.rolloffFactor,
  72461. refDistance: this.refDistance,
  72462. distanceModel: this.distanceModel,
  72463. playbackRate: this._playbackRate,
  72464. panningModel: this._panningModel,
  72465. soundTrackId: this.soundTrackId
  72466. };
  72467. if (this.spatialSound) {
  72468. if (this._connectedTransformNode) {
  72469. serializationObject.connectedMeshId = this._connectedTransformNode.id;
  72470. }
  72471. serializationObject.position = this._position.asArray();
  72472. serializationObject.refDistance = this.refDistance;
  72473. serializationObject.distanceModel = this.distanceModel;
  72474. serializationObject.isDirectional = this._isDirectional;
  72475. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  72476. serializationObject.coneInnerAngle = this._coneInnerAngle;
  72477. serializationObject.coneOuterAngle = this._coneOuterAngle;
  72478. serializationObject.coneOuterGain = this._coneOuterGain;
  72479. }
  72480. return serializationObject;
  72481. };
  72482. /**
  72483. * Parse a JSON representation of a sound to innstantiate in a given scene
  72484. * @param parsedSound Define the JSON representation of the sound (usually coming from the serialize method)
  72485. * @param scene Define the scene the new parsed sound should be created in
  72486. * @param rootUrl Define the rooturl of the load in case we need to fetch relative dependencies
  72487. * @param sourceSound Define a cound place holder if do not need to instantiate a new one
  72488. * @returns the newly parsed sound
  72489. */
  72490. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  72491. var soundName = parsedSound.name;
  72492. var soundUrl;
  72493. if (parsedSound.url) {
  72494. soundUrl = rootUrl + parsedSound.url;
  72495. }
  72496. else {
  72497. soundUrl = rootUrl + soundName;
  72498. }
  72499. var options = {
  72500. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  72501. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  72502. rolloffFactor: parsedSound.rolloffFactor,
  72503. refDistance: parsedSound.refDistance,
  72504. distanceModel: parsedSound.distanceModel,
  72505. playbackRate: parsedSound.playbackRate
  72506. };
  72507. var newSound;
  72508. if (!sourceSound) {
  72509. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  72510. scene._addPendingData(newSound);
  72511. }
  72512. else {
  72513. var setBufferAndRun = function () {
  72514. if (sourceSound._isReadyToPlay) {
  72515. newSound._audioBuffer = sourceSound.getAudioBuffer();
  72516. newSound._isReadyToPlay = true;
  72517. if (newSound.autoplay) {
  72518. newSound.play();
  72519. }
  72520. }
  72521. else {
  72522. window.setTimeout(setBufferAndRun, 300);
  72523. }
  72524. };
  72525. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  72526. setBufferAndRun();
  72527. }
  72528. if (parsedSound.position) {
  72529. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  72530. newSound.setPosition(soundPosition);
  72531. }
  72532. if (parsedSound.isDirectional) {
  72533. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  72534. if (parsedSound.localDirectionToMesh) {
  72535. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  72536. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  72537. }
  72538. }
  72539. if (parsedSound.connectedMeshId) {
  72540. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  72541. if (connectedMesh) {
  72542. newSound.attachToMesh(connectedMesh);
  72543. }
  72544. }
  72545. return newSound;
  72546. };
  72547. return Sound;
  72548. }());
  72549. BABYLON.Sound = Sound;
  72550. })(BABYLON || (BABYLON = {}));
  72551. //# sourceMappingURL=babylon.sound.js.map
  72552. var BABYLON;
  72553. (function (BABYLON) {
  72554. /**
  72555. * It could be useful to isolate your music & sounds on several tracks to better manage volume on a grouped instance of sounds.
  72556. * It will be also used in a future release to apply effects on a specific track.
  72557. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#using-sound-tracks
  72558. */
  72559. var SoundTrack = /** @class */ (function () {
  72560. /**
  72561. * Creates a new sound track.
  72562. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#using-sound-tracks
  72563. * @param scene Define the scene the sound track belongs to
  72564. * @param options
  72565. */
  72566. function SoundTrack(scene, options) {
  72567. if (options === void 0) { options = {}; }
  72568. /**
  72569. * The unique identifier of the sound track in the scene.
  72570. */
  72571. this.id = -1;
  72572. this._isMainTrack = false;
  72573. this._isInitialized = false;
  72574. this._scene = scene;
  72575. this.soundCollection = new Array();
  72576. this._options = options;
  72577. if (!this._isMainTrack && this._scene.soundTracks) {
  72578. this._scene.soundTracks.push(this);
  72579. this.id = this._scene.soundTracks.length - 1;
  72580. }
  72581. }
  72582. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  72583. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  72584. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  72585. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  72586. if (this._options) {
  72587. if (this._options.volume) {
  72588. this._outputAudioNode.gain.value = this._options.volume;
  72589. }
  72590. if (this._options.mainTrack) {
  72591. this._isMainTrack = this._options.mainTrack;
  72592. }
  72593. }
  72594. this._isInitialized = true;
  72595. }
  72596. };
  72597. /**
  72598. * Release the sound track and its associated resources
  72599. */
  72600. SoundTrack.prototype.dispose = function () {
  72601. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  72602. if (this._connectedAnalyser) {
  72603. this._connectedAnalyser.stopDebugCanvas();
  72604. }
  72605. while (this.soundCollection.length) {
  72606. this.soundCollection[0].dispose();
  72607. }
  72608. if (this._outputAudioNode) {
  72609. this._outputAudioNode.disconnect();
  72610. }
  72611. this._outputAudioNode = null;
  72612. }
  72613. };
  72614. /**
  72615. * Adds a sound to this sound track
  72616. * @param sound define the cound to add
  72617. * @ignoreNaming
  72618. */
  72619. SoundTrack.prototype.AddSound = function (sound) {
  72620. if (!this._isInitialized) {
  72621. this._initializeSoundTrackAudioGraph();
  72622. }
  72623. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  72624. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  72625. }
  72626. if (sound.soundTrackId) {
  72627. if (sound.soundTrackId === -1) {
  72628. this._scene.mainSoundTrack.RemoveSound(sound);
  72629. }
  72630. else if (this._scene.soundTracks) {
  72631. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  72632. }
  72633. }
  72634. this.soundCollection.push(sound);
  72635. sound.soundTrackId = this.id;
  72636. };
  72637. /**
  72638. * Removes a sound to this sound track
  72639. * @param sound define the cound to remove
  72640. * @ignoreNaming
  72641. */
  72642. SoundTrack.prototype.RemoveSound = function (sound) {
  72643. var index = this.soundCollection.indexOf(sound);
  72644. if (index !== -1) {
  72645. this.soundCollection.splice(index, 1);
  72646. }
  72647. };
  72648. /**
  72649. * Set a global volume for the full sound track.
  72650. * @param newVolume Define the new volume of the sound track
  72651. */
  72652. SoundTrack.prototype.setVolume = function (newVolume) {
  72653. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  72654. this._outputAudioNode.gain.value = newVolume;
  72655. }
  72656. };
  72657. /**
  72658. * Switch the panning model to HRTF:
  72659. * Renders a stereo output of higher quality than equalpower — it uses a convolution with measured impulse responses from human subjects.
  72660. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  72661. */
  72662. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  72663. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  72664. for (var i = 0; i < this.soundCollection.length; i++) {
  72665. this.soundCollection[i].switchPanningModelToHRTF();
  72666. }
  72667. }
  72668. };
  72669. /**
  72670. * Switch the panning model to Equal Power:
  72671. * Represents the equal-power panning algorithm, generally regarded as simple and efficient. equalpower is the default value.
  72672. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  72673. */
  72674. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  72675. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  72676. for (var i = 0; i < this.soundCollection.length; i++) {
  72677. this.soundCollection[i].switchPanningModelToEqualPower();
  72678. }
  72679. }
  72680. };
  72681. /**
  72682. * Connect the sound track to an audio analyser allowing some amazing
  72683. * synchornization between the sounds/music and your visualization (VuMeter for instance).
  72684. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#using-the-analyser
  72685. * @param analyser The analyser to connect to the engine
  72686. */
  72687. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  72688. if (this._connectedAnalyser) {
  72689. this._connectedAnalyser.stopDebugCanvas();
  72690. }
  72691. this._connectedAnalyser = analyser;
  72692. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  72693. this._outputAudioNode.disconnect();
  72694. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  72695. }
  72696. };
  72697. return SoundTrack;
  72698. }());
  72699. BABYLON.SoundTrack = SoundTrack;
  72700. })(BABYLON || (BABYLON = {}));
  72701. //# sourceMappingURL=babylon.soundtrack.js.map
  72702. var BABYLON;
  72703. (function (BABYLON) {
  72704. /**
  72705. * Class used to work with sound analyzer using fast fourier transform (FFT)
  72706. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  72707. */
  72708. var Analyser = /** @class */ (function () {
  72709. /**
  72710. * Creates a new analyser
  72711. * @param scene defines hosting scene
  72712. */
  72713. function Analyser(scene) {
  72714. /**
  72715. * Gets or sets the smoothing
  72716. * @ignorenaming
  72717. */
  72718. this.SMOOTHING = 0.75;
  72719. /**
  72720. * Gets or sets the FFT table size
  72721. * @ignorenaming
  72722. */
  72723. this.FFT_SIZE = 512;
  72724. /**
  72725. * Gets or sets the bar graph amplitude
  72726. * @ignorenaming
  72727. */
  72728. this.BARGRAPHAMPLITUDE = 256;
  72729. /**
  72730. * Gets or sets the position of the debug canvas
  72731. * @ignorenaming
  72732. */
  72733. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  72734. /**
  72735. * Gets or sets the debug canvas size
  72736. * @ignorenaming
  72737. */
  72738. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  72739. this._scene = scene;
  72740. this._audioEngine = BABYLON.Engine.audioEngine;
  72741. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  72742. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  72743. this._webAudioAnalyser.minDecibels = -140;
  72744. this._webAudioAnalyser.maxDecibels = 0;
  72745. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  72746. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  72747. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  72748. }
  72749. }
  72750. /**
  72751. * Get the number of data values you will have to play with for the visualization
  72752. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/frequencyBinCount
  72753. * @returns a number
  72754. */
  72755. Analyser.prototype.getFrequencyBinCount = function () {
  72756. if (this._audioEngine.canUseWebAudio) {
  72757. return this._webAudioAnalyser.frequencyBinCount;
  72758. }
  72759. else {
  72760. return 0;
  72761. }
  72762. };
  72763. /**
  72764. * Gets the current frequency data as a byte array
  72765. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  72766. * @returns a Uint8Array
  72767. */
  72768. Analyser.prototype.getByteFrequencyData = function () {
  72769. if (this._audioEngine.canUseWebAudio) {
  72770. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  72771. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  72772. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  72773. }
  72774. return this._byteFreqs;
  72775. };
  72776. /**
  72777. * Gets the current waveform as a byte array
  72778. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteTimeDomainData
  72779. * @returns a Uint8Array
  72780. */
  72781. Analyser.prototype.getByteTimeDomainData = function () {
  72782. if (this._audioEngine.canUseWebAudio) {
  72783. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  72784. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  72785. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  72786. }
  72787. return this._byteTime;
  72788. };
  72789. /**
  72790. * Gets the current frequency data as a float array
  72791. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  72792. * @returns a Float32Array
  72793. */
  72794. Analyser.prototype.getFloatFrequencyData = function () {
  72795. if (this._audioEngine.canUseWebAudio) {
  72796. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  72797. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  72798. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  72799. }
  72800. return this._floatFreqs;
  72801. };
  72802. /**
  72803. * Renders the debug canvas
  72804. */
  72805. Analyser.prototype.drawDebugCanvas = function () {
  72806. var _this = this;
  72807. if (this._audioEngine.canUseWebAudio) {
  72808. if (!this._debugCanvas) {
  72809. this._debugCanvas = document.createElement("canvas");
  72810. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  72811. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  72812. this._debugCanvas.style.position = "absolute";
  72813. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  72814. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  72815. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  72816. document.body.appendChild(this._debugCanvas);
  72817. this._registerFunc = function () {
  72818. _this.drawDebugCanvas();
  72819. };
  72820. this._scene.registerBeforeRender(this._registerFunc);
  72821. }
  72822. if (this._registerFunc && this._debugCanvasContext) {
  72823. var workingArray = this.getByteFrequencyData();
  72824. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  72825. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  72826. // Draw the frequency domain chart.
  72827. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  72828. var value = workingArray[i];
  72829. var percent = value / this.BARGRAPHAMPLITUDE;
  72830. var height = this.DEBUGCANVASSIZE.height * percent;
  72831. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  72832. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  72833. var hue = i / this.getFrequencyBinCount() * 360;
  72834. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  72835. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  72836. }
  72837. }
  72838. }
  72839. };
  72840. /**
  72841. * Stops rendering the debug canvas and removes it
  72842. */
  72843. Analyser.prototype.stopDebugCanvas = function () {
  72844. if (this._debugCanvas) {
  72845. if (this._registerFunc) {
  72846. this._scene.unregisterBeforeRender(this._registerFunc);
  72847. this._registerFunc = null;
  72848. }
  72849. document.body.removeChild(this._debugCanvas);
  72850. this._debugCanvas = null;
  72851. this._debugCanvasContext = null;
  72852. }
  72853. };
  72854. /**
  72855. * Connects two audio nodes
  72856. * @param inputAudioNode defines first node to connect
  72857. * @param outputAudioNode defines second node to connect
  72858. */
  72859. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  72860. if (this._audioEngine.canUseWebAudio) {
  72861. inputAudioNode.connect(this._webAudioAnalyser);
  72862. this._webAudioAnalyser.connect(outputAudioNode);
  72863. }
  72864. };
  72865. /**
  72866. * Releases all associated resources
  72867. */
  72868. Analyser.prototype.dispose = function () {
  72869. if (this._audioEngine.canUseWebAudio) {
  72870. this._webAudioAnalyser.disconnect();
  72871. }
  72872. };
  72873. return Analyser;
  72874. }());
  72875. BABYLON.Analyser = Analyser;
  72876. })(BABYLON || (BABYLON = {}));
  72877. //# sourceMappingURL=babylon.analyser.js.map
  72878. var BABYLON;
  72879. (function (BABYLON) {
  72880. /**
  72881. * Wraps one or more Sound objects and selects one with random weight for playback.
  72882. */
  72883. var WeightedSound = /** @class */ (function () {
  72884. /**
  72885. * Creates a new WeightedSound from the list of sounds given.
  72886. * @param loop When true a Sound will be selected and played when the current playing Sound completes.
  72887. * @param sounds Array of Sounds that will be selected from.
  72888. * @param weights Array of number values for selection weights; length must equal sounds, values will be normalized to 1
  72889. */
  72890. function WeightedSound(loop, sounds, weights) {
  72891. var _this = this;
  72892. /** When true a Sound will be selected and played when the current playing Sound completes. */
  72893. this.loop = false;
  72894. this._coneInnerAngle = 360;
  72895. this._coneOuterAngle = 360;
  72896. this._volume = 1;
  72897. /** A Sound is currently playing. */
  72898. this.isPlaying = false;
  72899. /** A Sound is currently paused. */
  72900. this.isPaused = false;
  72901. this._sounds = [];
  72902. this._weights = [];
  72903. if (sounds.length !== weights.length) {
  72904. throw new Error('Sounds length does not equal weights length');
  72905. }
  72906. this.loop = loop;
  72907. this._weights = weights;
  72908. // Normalize the weights
  72909. var weightSum = 0;
  72910. for (var _i = 0, weights_1 = weights; _i < weights_1.length; _i++) {
  72911. var weight = weights_1[_i];
  72912. weightSum += weight;
  72913. }
  72914. var invWeightSum = weightSum > 0 ? 1 / weightSum : 0;
  72915. for (var i = 0; i < this._weights.length; i++) {
  72916. this._weights[i] *= invWeightSum;
  72917. }
  72918. this._sounds = sounds;
  72919. for (var _a = 0, _b = this._sounds; _a < _b.length; _a++) {
  72920. var sound = _b[_a];
  72921. sound.onEndedObservable.add(function () { _this._onended(); });
  72922. }
  72923. }
  72924. Object.defineProperty(WeightedSound.prototype, "directionalConeInnerAngle", {
  72925. /**
  72926. * The size of cone in degrees for a directional sound in which there will be no attenuation.
  72927. */
  72928. get: function () {
  72929. return this._coneInnerAngle;
  72930. },
  72931. /**
  72932. * The size of cone in degress for a directional sound in which there will be no attenuation.
  72933. */
  72934. set: function (value) {
  72935. if (value !== this._coneInnerAngle) {
  72936. if (this._coneOuterAngle < value) {
  72937. BABYLON.Tools.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");
  72938. return;
  72939. }
  72940. this._coneInnerAngle = value;
  72941. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  72942. var sound = _a[_i];
  72943. sound.directionalConeInnerAngle = value;
  72944. }
  72945. }
  72946. },
  72947. enumerable: true,
  72948. configurable: true
  72949. });
  72950. Object.defineProperty(WeightedSound.prototype, "directionalConeOuterAngle", {
  72951. /**
  72952. * Size of cone in degrees for a directional sound outside of which there will be no sound.
  72953. * Listener angles between innerAngle and outerAngle will falloff linearly.
  72954. */
  72955. get: function () {
  72956. return this._coneOuterAngle;
  72957. },
  72958. /**
  72959. * Size of cone in degrees for a directional sound outside of which there will be no sound.
  72960. * Listener angles between innerAngle and outerAngle will falloff linearly.
  72961. */
  72962. set: function (value) {
  72963. if (value !== this._coneOuterAngle) {
  72964. if (value < this._coneInnerAngle) {
  72965. BABYLON.Tools.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");
  72966. return;
  72967. }
  72968. this._coneOuterAngle = value;
  72969. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  72970. var sound = _a[_i];
  72971. sound.directionalConeOuterAngle = value;
  72972. }
  72973. }
  72974. },
  72975. enumerable: true,
  72976. configurable: true
  72977. });
  72978. Object.defineProperty(WeightedSound.prototype, "volume", {
  72979. /**
  72980. * Playback volume.
  72981. */
  72982. get: function () {
  72983. return this._volume;
  72984. },
  72985. /**
  72986. * Playback volume.
  72987. */
  72988. set: function (value) {
  72989. if (value !== this._volume) {
  72990. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  72991. var sound = _a[_i];
  72992. sound.setVolume(value);
  72993. }
  72994. }
  72995. },
  72996. enumerable: true,
  72997. configurable: true
  72998. });
  72999. WeightedSound.prototype._onended = function () {
  73000. if (this._currentIndex !== undefined) {
  73001. this._sounds[this._currentIndex].autoplay = false;
  73002. }
  73003. if (this.loop && this.isPlaying) {
  73004. this.play();
  73005. }
  73006. else {
  73007. this.isPlaying = false;
  73008. }
  73009. };
  73010. /**
  73011. * Suspend playback
  73012. */
  73013. WeightedSound.prototype.pause = function () {
  73014. this.isPaused = true;
  73015. if (this._currentIndex !== undefined) {
  73016. this._sounds[this._currentIndex].pause();
  73017. }
  73018. };
  73019. /**
  73020. * Stop playback
  73021. */
  73022. WeightedSound.prototype.stop = function () {
  73023. this.isPlaying = false;
  73024. if (this._currentIndex !== undefined) {
  73025. this._sounds[this._currentIndex].stop();
  73026. }
  73027. };
  73028. /**
  73029. * Start playback.
  73030. * @param startOffset Position the clip head at a specific time in seconds.
  73031. */
  73032. WeightedSound.prototype.play = function (startOffset) {
  73033. if (!this.isPaused) {
  73034. this.stop();
  73035. var randomValue = Math.random();
  73036. var total = 0;
  73037. for (var i = 0; i < this._weights.length; i++) {
  73038. total += this._weights[i];
  73039. if (randomValue <= total) {
  73040. this._currentIndex = i;
  73041. break;
  73042. }
  73043. }
  73044. }
  73045. var sound = this._sounds[this._currentIndex];
  73046. if (sound.isReady()) {
  73047. sound.play(0, this.isPaused ? undefined : startOffset);
  73048. }
  73049. else {
  73050. sound.autoplay = true;
  73051. }
  73052. this.isPlaying = true;
  73053. this.isPaused = false;
  73054. };
  73055. return WeightedSound;
  73056. }());
  73057. BABYLON.WeightedSound = WeightedSound;
  73058. })(BABYLON || (BABYLON = {}));
  73059. //# sourceMappingURL=babylon.weightedsound.js.map
  73060. var BABYLON;
  73061. (function (BABYLON) {
  73062. // Adds the parser to the scene parsers.
  73063. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_AUDIO, function (parsedData, scene, container, rootUrl) {
  73064. // TODO: add sound
  73065. var loadedSounds = [];
  73066. var loadedSound;
  73067. container.sounds = container.sounds || [];
  73068. if (parsedData.sounds !== undefined && parsedData.sounds !== null) {
  73069. for (var index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  73070. var parsedSound = parsedData.sounds[index];
  73071. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  73072. if (!parsedSound.url) {
  73073. parsedSound.url = parsedSound.name;
  73074. }
  73075. if (!loadedSounds[parsedSound.url]) {
  73076. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  73077. loadedSounds[parsedSound.url] = loadedSound;
  73078. container.sounds.push(loadedSound);
  73079. }
  73080. else {
  73081. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  73082. }
  73083. }
  73084. else {
  73085. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  73086. }
  73087. }
  73088. }
  73089. loadedSounds = [];
  73090. });
  73091. Object.defineProperty(BABYLON.Scene.prototype, "mainSoundTrack", {
  73092. get: function () {
  73093. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  73094. if (!compo) {
  73095. compo = new AudioSceneComponent(this);
  73096. this._addComponent(compo);
  73097. }
  73098. if (!this._mainSoundTrack) {
  73099. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  73100. }
  73101. return this._mainSoundTrack;
  73102. },
  73103. enumerable: true,
  73104. configurable: true
  73105. });
  73106. BABYLON.Scene.prototype.getSoundByName = function (name) {
  73107. var index;
  73108. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  73109. if (this.mainSoundTrack.soundCollection[index].name === name) {
  73110. return this.mainSoundTrack.soundCollection[index];
  73111. }
  73112. }
  73113. if (this.soundTracks) {
  73114. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  73115. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  73116. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  73117. return this.soundTracks[sdIndex].soundCollection[index];
  73118. }
  73119. }
  73120. }
  73121. }
  73122. return null;
  73123. };
  73124. Object.defineProperty(BABYLON.Scene.prototype, "audioEnabled", {
  73125. get: function () {
  73126. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  73127. if (!compo) {
  73128. compo = new AudioSceneComponent(this);
  73129. this._addComponent(compo);
  73130. }
  73131. return compo.audioEnabled;
  73132. },
  73133. set: function (value) {
  73134. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  73135. if (!compo) {
  73136. compo = new AudioSceneComponent(this);
  73137. this._addComponent(compo);
  73138. }
  73139. if (value) {
  73140. compo.enableAudio();
  73141. }
  73142. else {
  73143. compo.disableAudio();
  73144. }
  73145. },
  73146. enumerable: true,
  73147. configurable: true
  73148. });
  73149. Object.defineProperty(BABYLON.Scene.prototype, "headphone", {
  73150. get: function () {
  73151. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  73152. if (!compo) {
  73153. compo = new AudioSceneComponent(this);
  73154. this._addComponent(compo);
  73155. }
  73156. return compo.headphone;
  73157. },
  73158. set: function (value) {
  73159. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  73160. if (!compo) {
  73161. compo = new AudioSceneComponent(this);
  73162. this._addComponent(compo);
  73163. }
  73164. if (value) {
  73165. compo.switchAudioModeForHeadphones();
  73166. }
  73167. else {
  73168. compo.switchAudioModeForNormalSpeakers();
  73169. }
  73170. },
  73171. enumerable: true,
  73172. configurable: true
  73173. });
  73174. /**
  73175. * Defines the sound scene component responsible to manage any sounds
  73176. * in a given scene.
  73177. */
  73178. var AudioSceneComponent = /** @class */ (function () {
  73179. /**
  73180. * Creates a new instance of the component for the given scene
  73181. * @param scene Defines the scene to register the component in
  73182. */
  73183. function AudioSceneComponent(scene) {
  73184. /**
  73185. * The component name helpfull to identify the component in the list of scene components.
  73186. */
  73187. this.name = BABYLON.SceneComponentConstants.NAME_AUDIO;
  73188. this._audioEnabled = true;
  73189. this._headphone = false;
  73190. this.scene = scene;
  73191. scene.soundTracks = new Array();
  73192. scene.sounds = new Array();
  73193. }
  73194. Object.defineProperty(AudioSceneComponent.prototype, "audioEnabled", {
  73195. /**
  73196. * Gets whether audio is enabled or not.
  73197. * Please use related enable/disable method to switch state.
  73198. */
  73199. get: function () {
  73200. return this._audioEnabled;
  73201. },
  73202. enumerable: true,
  73203. configurable: true
  73204. });
  73205. Object.defineProperty(AudioSceneComponent.prototype, "headphone", {
  73206. /**
  73207. * Gets whether audio is outputing to headphone or not.
  73208. * Please use the according Switch methods to change output.
  73209. */
  73210. get: function () {
  73211. return this._headphone;
  73212. },
  73213. enumerable: true,
  73214. configurable: true
  73215. });
  73216. /**
  73217. * Registers the component in a given scene
  73218. */
  73219. AudioSceneComponent.prototype.register = function () {
  73220. this.scene._afterRenderStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDER_AUDIO, this, this._afterRender);
  73221. };
  73222. /**
  73223. * Rebuilds the elements related to this component in case of
  73224. * context lost for instance.
  73225. */
  73226. AudioSceneComponent.prototype.rebuild = function () {
  73227. // Nothing to do here. (Not rendering related)
  73228. };
  73229. /**
  73230. * Serializes the component data to the specified json object
  73231. * @param serializationObject The object to serialize to
  73232. */
  73233. AudioSceneComponent.prototype.serialize = function (serializationObject) {
  73234. serializationObject.sounds = [];
  73235. if (this.scene.soundTracks) {
  73236. for (var index = 0; index < this.scene.soundTracks.length; index++) {
  73237. var soundtrack = this.scene.soundTracks[index];
  73238. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  73239. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  73240. }
  73241. }
  73242. }
  73243. };
  73244. /**
  73245. * Adds all the element from the container to the scene
  73246. * @param container the container holding the elements
  73247. */
  73248. AudioSceneComponent.prototype.addFromContainer = function (container) {
  73249. var _this = this;
  73250. if (!container.sounds) {
  73251. return;
  73252. }
  73253. container.sounds.forEach(function (sound) {
  73254. sound.play();
  73255. sound.autoplay = true;
  73256. _this.scene.mainSoundTrack.AddSound(sound);
  73257. });
  73258. };
  73259. /**
  73260. * Removes all the elements in the container from the scene
  73261. * @param container contains the elements to remove
  73262. */
  73263. AudioSceneComponent.prototype.removeFromContainer = function (container) {
  73264. var _this = this;
  73265. if (!container.sounds) {
  73266. return;
  73267. }
  73268. container.sounds.forEach(function (sound) {
  73269. sound.stop();
  73270. sound.autoplay = false;
  73271. _this.scene.mainSoundTrack.RemoveSound(sound);
  73272. });
  73273. };
  73274. /**
  73275. * Disposes the component and the associated ressources.
  73276. */
  73277. AudioSceneComponent.prototype.dispose = function () {
  73278. var scene = this.scene;
  73279. if (scene._mainSoundTrack) {
  73280. scene.mainSoundTrack.dispose();
  73281. }
  73282. if (scene.soundTracks) {
  73283. for (var scIndex = 0; scIndex < scene.soundTracks.length; scIndex++) {
  73284. scene.soundTracks[scIndex].dispose();
  73285. }
  73286. }
  73287. };
  73288. /**
  73289. * Disables audio in the associated scene.
  73290. */
  73291. AudioSceneComponent.prototype.disableAudio = function () {
  73292. var scene = this.scene;
  73293. this._audioEnabled = false;
  73294. var i;
  73295. for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) {
  73296. scene.mainSoundTrack.soundCollection[i].pause();
  73297. }
  73298. if (scene.soundTracks) {
  73299. for (i = 0; i < scene.soundTracks.length; i++) {
  73300. for (var j = 0; j < scene.soundTracks[i].soundCollection.length; j++) {
  73301. scene.soundTracks[i].soundCollection[j].pause();
  73302. }
  73303. }
  73304. }
  73305. };
  73306. /**
  73307. * Enables audio in the associated scene.
  73308. */
  73309. AudioSceneComponent.prototype.enableAudio = function () {
  73310. var scene = this.scene;
  73311. this._audioEnabled = true;
  73312. var i;
  73313. for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) {
  73314. if (scene.mainSoundTrack.soundCollection[i].isPaused) {
  73315. scene.mainSoundTrack.soundCollection[i].play();
  73316. }
  73317. }
  73318. if (scene.soundTracks) {
  73319. for (i = 0; i < scene.soundTracks.length; i++) {
  73320. for (var j = 0; j < scene.soundTracks[i].soundCollection.length; j++) {
  73321. if (scene.soundTracks[i].soundCollection[j].isPaused) {
  73322. scene.soundTracks[i].soundCollection[j].play();
  73323. }
  73324. }
  73325. }
  73326. }
  73327. };
  73328. /**
  73329. * Switch audio to headphone output.
  73330. */
  73331. AudioSceneComponent.prototype.switchAudioModeForHeadphones = function () {
  73332. var scene = this.scene;
  73333. this._headphone = true;
  73334. scene.mainSoundTrack.switchPanningModelToHRTF();
  73335. if (scene.soundTracks) {
  73336. for (var i = 0; i < scene.soundTracks.length; i++) {
  73337. scene.soundTracks[i].switchPanningModelToHRTF();
  73338. }
  73339. }
  73340. };
  73341. /**
  73342. * Switch audio to normal speakers.
  73343. */
  73344. AudioSceneComponent.prototype.switchAudioModeForNormalSpeakers = function () {
  73345. var scene = this.scene;
  73346. this._headphone = false;
  73347. scene.mainSoundTrack.switchPanningModelToEqualPower();
  73348. if (scene.soundTracks) {
  73349. for (var i = 0; i < scene.soundTracks.length; i++) {
  73350. scene.soundTracks[i].switchPanningModelToEqualPower();
  73351. }
  73352. }
  73353. };
  73354. AudioSceneComponent.prototype._afterRender = function () {
  73355. var scene = this.scene;
  73356. if (!this._audioEnabled || !scene._mainSoundTrack || !scene.soundTracks || (scene._mainSoundTrack.soundCollection.length === 0 && scene.soundTracks.length === 1)) {
  73357. return;
  73358. }
  73359. var listeningCamera;
  73360. var audioEngine = BABYLON.Engine.audioEngine;
  73361. if (scene.activeCameras.length > 0) {
  73362. listeningCamera = scene.activeCameras[0];
  73363. }
  73364. else {
  73365. listeningCamera = scene.activeCamera;
  73366. }
  73367. if (listeningCamera && audioEngine.audioContext) {
  73368. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  73369. // for VR cameras
  73370. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  73371. listeningCamera = listeningCamera.rigCameras[0];
  73372. }
  73373. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  73374. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  73375. cameraDirection.normalize();
  73376. // To avoid some errors on GearVR
  73377. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  73378. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  73379. }
  73380. var i;
  73381. for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) {
  73382. var sound = scene.mainSoundTrack.soundCollection[i];
  73383. if (sound.useCustomAttenuation) {
  73384. sound.updateDistanceFromListener();
  73385. }
  73386. }
  73387. if (scene.soundTracks) {
  73388. for (i = 0; i < scene.soundTracks.length; i++) {
  73389. for (var j = 0; j < scene.soundTracks[i].soundCollection.length; j++) {
  73390. sound = scene.soundTracks[i].soundCollection[j];
  73391. if (sound.useCustomAttenuation) {
  73392. sound.updateDistanceFromListener();
  73393. }
  73394. }
  73395. }
  73396. }
  73397. }
  73398. };
  73399. return AudioSceneComponent;
  73400. }());
  73401. BABYLON.AudioSceneComponent = AudioSceneComponent;
  73402. })(BABYLON || (BABYLON = {}));
  73403. //# sourceMappingURL=babylon.audioSceneComponent.js.map
  73404. var BABYLON;
  73405. (function (BABYLON) {
  73406. /**
  73407. * This defines an action helpful to play a defined sound on a triggered action.
  73408. */
  73409. var PlaySoundAction = /** @class */ (function (_super) {
  73410. __extends(PlaySoundAction, _super);
  73411. /**
  73412. * Instantiate the action
  73413. * @param triggerOptions defines the trigger options
  73414. * @param sound defines the sound to play
  73415. * @param condition defines the trigger related conditions
  73416. */
  73417. function PlaySoundAction(triggerOptions, sound, condition) {
  73418. var _this = _super.call(this, triggerOptions, condition) || this;
  73419. _this._sound = sound;
  73420. return _this;
  73421. }
  73422. /** @hidden */
  73423. PlaySoundAction.prototype._prepare = function () {
  73424. };
  73425. /**
  73426. * Execute the action and play the sound.
  73427. */
  73428. PlaySoundAction.prototype.execute = function () {
  73429. if (this._sound !== undefined) {
  73430. this._sound.play();
  73431. }
  73432. };
  73433. /**
  73434. * Serializes the actions and its related information.
  73435. * @param parent defines the object to serialize in
  73436. * @returns the serialized object
  73437. */
  73438. PlaySoundAction.prototype.serialize = function (parent) {
  73439. return _super.prototype._serialize.call(this, {
  73440. name: "PlaySoundAction",
  73441. properties: [{ name: "sound", value: this._sound.name }]
  73442. }, parent);
  73443. };
  73444. return PlaySoundAction;
  73445. }(BABYLON.Action));
  73446. BABYLON.PlaySoundAction = PlaySoundAction;
  73447. /**
  73448. * This defines an action helpful to stop a defined sound on a triggered action.
  73449. */
  73450. var StopSoundAction = /** @class */ (function (_super) {
  73451. __extends(StopSoundAction, _super);
  73452. /**
  73453. * Instantiate the action
  73454. * @param triggerOptions defines the trigger options
  73455. * @param sound defines the sound to stop
  73456. * @param condition defines the trigger related conditions
  73457. */
  73458. function StopSoundAction(triggerOptions, sound, condition) {
  73459. var _this = _super.call(this, triggerOptions, condition) || this;
  73460. _this._sound = sound;
  73461. return _this;
  73462. }
  73463. /** @hidden */
  73464. StopSoundAction.prototype._prepare = function () {
  73465. };
  73466. /**
  73467. * Execute the action and stop the sound.
  73468. */
  73469. StopSoundAction.prototype.execute = function () {
  73470. if (this._sound !== undefined) {
  73471. this._sound.stop();
  73472. }
  73473. };
  73474. /**
  73475. * Serializes the actions and its related information.
  73476. * @param parent defines the object to serialize in
  73477. * @returns the serialized object
  73478. */
  73479. StopSoundAction.prototype.serialize = function (parent) {
  73480. return _super.prototype._serialize.call(this, {
  73481. name: "StopSoundAction",
  73482. properties: [{ name: "sound", value: this._sound.name }]
  73483. }, parent);
  73484. };
  73485. return StopSoundAction;
  73486. }(BABYLON.Action));
  73487. BABYLON.StopSoundAction = StopSoundAction;
  73488. })(BABYLON || (BABYLON = {}));
  73489. //# sourceMappingURL=babylon.directAudioActions.js.map
  73490. var BABYLON;
  73491. (function (BABYLON) {
  73492. /**
  73493. * Class for creating a cube texture
  73494. */
  73495. var CubeTexture = /** @class */ (function (_super) {
  73496. __extends(CubeTexture, _super);
  73497. /**
  73498. * Creates a cube texture to use with reflection for instance. It can be based upon dds or six images as well
  73499. * as prefiltered data.
  73500. * @param rootUrl defines the url of the texture or the root name of the six images
  73501. * @param scene defines the scene the texture is attached to
  73502. * @param extensions defines the suffixes add to the picture name in case six images are in use like _px.jpg...
  73503. * @param noMipmap defines if mipmaps should be created or not
  73504. * @param files defines the six files to load for the different faces
  73505. * @param onLoad defines a callback triggered at the end of the file load if no errors occured
  73506. * @param onError defines a callback triggered in case of error during load
  73507. * @param format defines the internal format to use for the texture once loaded
  73508. * @param prefiltered defines whether or not the texture is created from prefiltered data
  73509. * @param forcedExtension defines the extensions to use (force a special type of file to load) in case it is different from the file name
  73510. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  73511. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  73512. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  73513. * @return the cube texture
  73514. */
  73515. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension, createPolynomials, lodScale, lodOffset) {
  73516. if (extensions === void 0) { extensions = null; }
  73517. if (noMipmap === void 0) { noMipmap = false; }
  73518. if (files === void 0) { files = null; }
  73519. if (onLoad === void 0) { onLoad = null; }
  73520. if (onError === void 0) { onError = null; }
  73521. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  73522. if (prefiltered === void 0) { prefiltered = false; }
  73523. if (forcedExtension === void 0) { forcedExtension = null; }
  73524. if (createPolynomials === void 0) { createPolynomials = false; }
  73525. if (lodScale === void 0) { lodScale = 0.8; }
  73526. if (lodOffset === void 0) { lodOffset = 0; }
  73527. var _this = _super.call(this, scene) || this;
  73528. /**
  73529. * Gets or sets the center of the bounding box associated with the cube texture.
  73530. * It must define where the camera used to render the texture was set
  73531. * @see http://doc.babylonjs.com/how_to/reflect#using-local-cubemap-mode
  73532. */
  73533. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  73534. _this._rotationY = 0;
  73535. /** @hidden */
  73536. _this._prefiltered = false;
  73537. _this.name = rootUrl;
  73538. _this.url = rootUrl;
  73539. _this._noMipmap = noMipmap;
  73540. _this.hasAlpha = false;
  73541. _this._format = format;
  73542. _this.isCube = true;
  73543. _this._textureMatrix = BABYLON.Matrix.Identity();
  73544. _this._createPolynomials = createPolynomials;
  73545. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  73546. if (!rootUrl && !files) {
  73547. return _this;
  73548. }
  73549. var lastDot = rootUrl.lastIndexOf(".");
  73550. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  73551. var isDDS = (extension === ".dds");
  73552. var isEnv = (extension === ".env");
  73553. if (isEnv) {
  73554. _this.gammaSpace = false;
  73555. _this._prefiltered = false;
  73556. }
  73557. else {
  73558. _this._prefiltered = prefiltered;
  73559. if (prefiltered) {
  73560. _this.gammaSpace = false;
  73561. }
  73562. }
  73563. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  73564. if (!files) {
  73565. if (!isEnv && !isDDS && !extensions) {
  73566. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  73567. }
  73568. files = [];
  73569. if (extensions) {
  73570. for (var index = 0; index < extensions.length; index++) {
  73571. files.push(rootUrl + extensions[index]);
  73572. }
  73573. }
  73574. }
  73575. _this._files = files;
  73576. if (!_this._texture) {
  73577. if (!scene.useDelayedTextureLoading) {
  73578. if (prefiltered) {
  73579. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, _this._createPolynomials);
  73580. }
  73581. else {
  73582. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension, false, lodScale, lodOffset);
  73583. }
  73584. }
  73585. else {
  73586. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  73587. }
  73588. }
  73589. else if (onLoad) {
  73590. if (_this._texture.isReady) {
  73591. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  73592. }
  73593. else {
  73594. _this._texture.onLoadedObservable.add(onLoad);
  73595. }
  73596. }
  73597. return _this;
  73598. }
  73599. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  73600. /**
  73601. * Returns the bounding box size
  73602. * @see http://doc.babylonjs.com/how_to/reflect#using-local-cubemap-mode
  73603. */
  73604. get: function () {
  73605. return this._boundingBoxSize;
  73606. },
  73607. /**
  73608. * Gets or sets the size of the bounding box associated with the cube texture
  73609. * When defined, the cubemap will switch to local mode
  73610. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  73611. * @example https://www.babylonjs-playground.com/#RNASML
  73612. */
  73613. set: function (value) {
  73614. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  73615. return;
  73616. }
  73617. this._boundingBoxSize = value;
  73618. var scene = this.getScene();
  73619. if (scene) {
  73620. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  73621. }
  73622. },
  73623. enumerable: true,
  73624. configurable: true
  73625. });
  73626. Object.defineProperty(CubeTexture.prototype, "rotationY", {
  73627. /**
  73628. * Gets texture matrix rotation angle around Y axis radians.
  73629. */
  73630. get: function () {
  73631. return this._rotationY;
  73632. },
  73633. /**
  73634. * Sets texture matrix rotation angle around Y axis in radians.
  73635. */
  73636. set: function (value) {
  73637. this._rotationY = value;
  73638. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  73639. },
  73640. enumerable: true,
  73641. configurable: true
  73642. });
  73643. Object.defineProperty(CubeTexture.prototype, "noMipmap", {
  73644. /**
  73645. * Are mip maps generated for this texture or not.
  73646. */
  73647. get: function () {
  73648. return this._noMipmap;
  73649. },
  73650. enumerable: true,
  73651. configurable: true
  73652. });
  73653. /**
  73654. * Creates a cube texture from an array of image urls
  73655. * @param files defines an array of image urls
  73656. * @param scene defines the hosting scene
  73657. * @param noMipmap specifies if mip maps are not used
  73658. * @returns a cube texture
  73659. */
  73660. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  73661. var rootUrlKey = "";
  73662. files.forEach(function (url) { return rootUrlKey += url; });
  73663. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  73664. };
  73665. /**
  73666. * Creates and return a texture created from prefilterd data by tools like IBL Baker or Lys.
  73667. * @param url defines the url of the prefiltered texture
  73668. * @param scene defines the scene the texture is attached to
  73669. * @param forcedExtension defines the extension of the file if different from the url
  73670. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  73671. * @return the prefiltered texture
  73672. */
  73673. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension, createPolynomials) {
  73674. if (forcedExtension === void 0) { forcedExtension = null; }
  73675. if (createPolynomials === void 0) { createPolynomials = true; }
  73676. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension, createPolynomials);
  73677. };
  73678. /**
  73679. * Get the current class name of the texture useful for serialization or dynamic coding.
  73680. * @returns "CubeTexture"
  73681. */
  73682. CubeTexture.prototype.getClassName = function () {
  73683. return "CubeTexture";
  73684. };
  73685. /**
  73686. * Update the url (and optional buffer) of this texture if url was null during construction.
  73687. * @param url the url of the texture
  73688. * @param forcedExtension defines the extension to use
  73689. * @param onLoad callback called when the texture is loaded (defaults to null)
  73690. */
  73691. CubeTexture.prototype.updateURL = function (url, forcedExtension, onLoad) {
  73692. if (this.url) {
  73693. this.releaseInternalTexture();
  73694. this.getScene().markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  73695. }
  73696. this.url = url;
  73697. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  73698. this._prefiltered = false;
  73699. if (onLoad) {
  73700. this._delayedOnLoad = onLoad;
  73701. }
  73702. this.delayLoad(forcedExtension);
  73703. };
  73704. /**
  73705. * Delays loading of the cube texture
  73706. * @param forcedExtension defines the extension to use
  73707. */
  73708. CubeTexture.prototype.delayLoad = function (forcedExtension) {
  73709. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  73710. return;
  73711. }
  73712. var scene = this.getScene();
  73713. if (!scene) {
  73714. return;
  73715. }
  73716. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  73717. this._texture = this._getFromCache(this.url, this._noMipmap);
  73718. if (!this._texture) {
  73719. if (this._prefiltered) {
  73720. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, this._delayedOnLoad, undefined, this._format, undefined, this._createPolynomials);
  73721. }
  73722. else {
  73723. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, this._delayedOnLoad, undefined, this._format, forcedExtension);
  73724. }
  73725. }
  73726. };
  73727. /**
  73728. * Returns the reflection texture matrix
  73729. * @returns the reflection texture matrix
  73730. */
  73731. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  73732. return this._textureMatrix;
  73733. };
  73734. /**
  73735. * Sets the reflection texture matrix
  73736. * @param value Reflection texture matrix
  73737. */
  73738. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  73739. var _this = this;
  73740. if (value.updateFlag === this._textureMatrix.updateFlag) {
  73741. return;
  73742. }
  73743. if (value.isIdentity() !== this._textureMatrix.isIdentity()) {
  73744. this.getScene().markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) { return mat.getActiveTextures().indexOf(_this) !== -1; });
  73745. }
  73746. this._textureMatrix = value;
  73747. };
  73748. /**
  73749. * Parses text to create a cube texture
  73750. * @param parsedTexture define the serialized text to read from
  73751. * @param scene defines the hosting scene
  73752. * @param rootUrl defines the root url of the cube texture
  73753. * @returns a cube texture
  73754. */
  73755. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  73756. var texture = BABYLON.SerializationHelper.Parse(function () {
  73757. var prefiltered = false;
  73758. if (parsedTexture.prefiltered) {
  73759. prefiltered = parsedTexture.prefiltered;
  73760. }
  73761. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions, false, null, null, null, undefined, prefiltered);
  73762. }, parsedTexture, scene);
  73763. // Local Cubemaps
  73764. if (parsedTexture.boundingBoxPosition) {
  73765. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  73766. }
  73767. if (parsedTexture.boundingBoxSize) {
  73768. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  73769. }
  73770. // Animations
  73771. if (parsedTexture.animations) {
  73772. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  73773. var parsedAnimation = parsedTexture.animations[animationIndex];
  73774. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  73775. }
  73776. }
  73777. return texture;
  73778. };
  73779. /**
  73780. * Makes a clone, or deep copy, of the cube texture
  73781. * @returns a new cube texture
  73782. */
  73783. CubeTexture.prototype.clone = function () {
  73784. var _this = this;
  73785. var scene = this.getScene();
  73786. var uniqueId = 0;
  73787. var newCubeTexture = BABYLON.SerializationHelper.Clone(function () {
  73788. if (!scene) {
  73789. return _this;
  73790. }
  73791. var cubeTexture = new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  73792. uniqueId = cubeTexture.uniqueId;
  73793. return cubeTexture;
  73794. }, this);
  73795. newCubeTexture.uniqueId = uniqueId;
  73796. return newCubeTexture;
  73797. };
  73798. __decorate([
  73799. BABYLON.serialize("rotationY")
  73800. ], CubeTexture.prototype, "rotationY", null);
  73801. return CubeTexture;
  73802. }(BABYLON.BaseTexture));
  73803. BABYLON.CubeTexture = CubeTexture;
  73804. })(BABYLON || (BABYLON = {}));
  73805. //# sourceMappingURL=babylon.cubeTexture.js.map
  73806. var BABYLON;
  73807. (function (BABYLON) {
  73808. /**
  73809. * Raw cube texture where the raw buffers are passed in
  73810. */
  73811. var RawCubeTexture = /** @class */ (function (_super) {
  73812. __extends(RawCubeTexture, _super);
  73813. /**
  73814. * Creates a cube texture where the raw buffers are passed in.
  73815. * @param scene defines the scene the texture is attached to
  73816. * @param data defines the array of data to use to create each face
  73817. * @param size defines the size of the textures
  73818. * @param format defines the format of the data
  73819. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  73820. * @param generateMipMaps defines if the engine should generate the mip levels
  73821. * @param invertY defines if data must be stored with Y axis inverted
  73822. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  73823. * @param compression defines the compression used (null by default)
  73824. */
  73825. function RawCubeTexture(scene, data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  73826. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  73827. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  73828. if (generateMipMaps === void 0) { generateMipMaps = false; }
  73829. if (invertY === void 0) { invertY = false; }
  73830. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  73831. if (compression === void 0) { compression = null; }
  73832. var _this = _super.call(this, "", scene) || this;
  73833. _this._texture = scene.getEngine().createRawCubeTexture(data, size, format, type, generateMipMaps, invertY, samplingMode, compression);
  73834. return _this;
  73835. }
  73836. /**
  73837. * Updates the raw cube texture.
  73838. * @param data defines the data to store
  73839. * @param format defines the data format
  73840. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  73841. * @param invertY defines if data must be stored with Y axis inverted
  73842. * @param compression defines the compression used (null by default)
  73843. * @param level defines which level of the texture to update
  73844. */
  73845. RawCubeTexture.prototype.update = function (data, format, type, invertY, compression, level) {
  73846. if (compression === void 0) { compression = null; }
  73847. if (level === void 0) { level = 0; }
  73848. this._texture.getEngine().updateRawCubeTexture(this._texture, data, format, type, invertY, compression);
  73849. };
  73850. /**
  73851. * Updates a raw cube texture with RGBD encoded data.
  73852. * @param data defines the array of data [mipmap][face] to use to create each face
  73853. * @param sphericalPolynomial defines the spherical polynomial for irradiance
  73854. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  73855. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  73856. * @returns a promsie that resolves when the operation is complete
  73857. */
  73858. RawCubeTexture.prototype.updateRGBDAsync = function (data, sphericalPolynomial, lodScale, lodOffset) {
  73859. if (sphericalPolynomial === void 0) { sphericalPolynomial = null; }
  73860. if (lodScale === void 0) { lodScale = 0.8; }
  73861. if (lodOffset === void 0) { lodOffset = 0; }
  73862. return RawCubeTexture._UpdateRGBDAsync(this._texture, data, sphericalPolynomial, lodScale, lodOffset);
  73863. };
  73864. /**
  73865. * Clones the raw cube texture.
  73866. * @return a new cube texture
  73867. */
  73868. RawCubeTexture.prototype.clone = function () {
  73869. var _this = this;
  73870. return BABYLON.SerializationHelper.Clone(function () {
  73871. var scene = _this.getScene();
  73872. var internalTexture = _this._texture;
  73873. var texture = new RawCubeTexture(scene, internalTexture._bufferViewArray, internalTexture.width, internalTexture.format, internalTexture.type, internalTexture.generateMipMaps, internalTexture.invertY, internalTexture.samplingMode, internalTexture._compression);
  73874. if (internalTexture.dataSource === BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD) {
  73875. texture.updateRGBDAsync(internalTexture._bufferViewArrayArray, internalTexture._sphericalPolynomial, internalTexture._lodGenerationScale, internalTexture._lodGenerationOffset);
  73876. }
  73877. return texture;
  73878. }, this);
  73879. };
  73880. /** @hidden */
  73881. RawCubeTexture._UpdateRGBDAsync = function (internalTexture, data, sphericalPolynomial, lodScale, lodOffset) {
  73882. internalTexture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD;
  73883. internalTexture._bufferViewArrayArray = data;
  73884. internalTexture._lodGenerationScale = lodScale;
  73885. internalTexture._lodGenerationOffset = lodOffset;
  73886. internalTexture._sphericalPolynomial = sphericalPolynomial;
  73887. return BABYLON.EnvironmentTextureTools.UploadLevelsAsync(internalTexture, data).then(function () {
  73888. internalTexture.isReady = true;
  73889. });
  73890. };
  73891. return RawCubeTexture;
  73892. }(BABYLON.CubeTexture));
  73893. BABYLON.RawCubeTexture = RawCubeTexture;
  73894. })(BABYLON || (BABYLON = {}));
  73895. //# sourceMappingURL=babylon.rawCubeTexture.js.map
  73896. var BABYLON;
  73897. (function (BABYLON) {
  73898. /**
  73899. * This Helps creating a texture that will be created from a camera in your scene.
  73900. * It is basically a dynamic texture that could be used to create special effects for instance.
  73901. * Actually, It is the base of lot of effects in the framework like post process, shadows, effect layers and rendering pipelines...
  73902. */
  73903. var RenderTargetTexture = /** @class */ (function (_super) {
  73904. __extends(RenderTargetTexture, _super);
  73905. /**
  73906. * Instantiate a render target texture. This is mainly used to render of screen the scene to for instance apply post processse
  73907. * or used a shadow, depth texture...
  73908. * @param name The friendly name of the texture
  73909. * @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)
  73910. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  73911. * @param generateMipMaps True if mip maps need to be generated after render.
  73912. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  73913. * @param type The type of the buffer in the RTT (int, half float, float...)
  73914. * @param isCube True if a cube texture needs to be created
  73915. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  73916. * @param generateDepthBuffer True to generate a depth buffer
  73917. * @param generateStencilBuffer True to generate a stencil buffer
  73918. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  73919. * @param format The internal format of the buffer in the RTT (RED, RG, RGB, RGBA, ALPHA...)
  73920. * @param delayAllocation if the texture allocation should be delayed (default: false)
  73921. */
  73922. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti, format, delayAllocation) {
  73923. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  73924. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  73925. if (isCube === void 0) { isCube = false; }
  73926. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  73927. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  73928. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  73929. if (isMulti === void 0) { isMulti = false; }
  73930. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  73931. if (delayAllocation === void 0) { delayAllocation = false; }
  73932. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  73933. _this.isCube = isCube;
  73934. /**
  73935. * Define if particles should be rendered in your texture.
  73936. */
  73937. _this.renderParticles = true;
  73938. /**
  73939. * Define if sprites should be rendered in your texture.
  73940. */
  73941. _this.renderSprites = false;
  73942. /**
  73943. * Override the default coordinates mode to projection for RTT as it is the most common case for rendered textures.
  73944. */
  73945. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  73946. /**
  73947. * Define if the camera viewport should be respected while rendering the texture or if the render should be done to the entire texture.
  73948. */
  73949. _this.ignoreCameraViewport = false;
  73950. /**
  73951. * An event triggered when the texture is unbind.
  73952. */
  73953. _this.onBeforeBindObservable = new BABYLON.Observable();
  73954. /**
  73955. * An event triggered when the texture is unbind.
  73956. */
  73957. _this.onAfterUnbindObservable = new BABYLON.Observable();
  73958. /**
  73959. * An event triggered before rendering the texture
  73960. */
  73961. _this.onBeforeRenderObservable = new BABYLON.Observable();
  73962. /**
  73963. * An event triggered after rendering the texture
  73964. */
  73965. _this.onAfterRenderObservable = new BABYLON.Observable();
  73966. /**
  73967. * An event triggered after the texture clear
  73968. */
  73969. _this.onClearObservable = new BABYLON.Observable();
  73970. _this._currentRefreshId = -1;
  73971. _this._refreshRate = 1;
  73972. _this._samples = 1;
  73973. /**
  73974. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  73975. * It must define where the camera used to render the texture is set
  73976. */
  73977. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  73978. scene = _this.getScene();
  73979. if (!scene) {
  73980. return _this;
  73981. }
  73982. _this.renderList = new Array();
  73983. _this._engine = scene.getEngine();
  73984. _this.name = name;
  73985. _this.isRenderTarget = true;
  73986. _this._initialSizeParameter = size;
  73987. _this._processSizeParameter(size);
  73988. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  73989. });
  73990. _this._generateMipMaps = generateMipMaps ? true : false;
  73991. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  73992. // Rendering groups
  73993. _this._renderingManager = new BABYLON.RenderingManager(scene);
  73994. _this._renderingManager._useSceneAutoClearSetup = true;
  73995. if (isMulti) {
  73996. return _this;
  73997. }
  73998. _this._renderTargetOptions = {
  73999. generateMipMaps: generateMipMaps,
  74000. type: type,
  74001. format: format,
  74002. samplingMode: samplingMode,
  74003. generateDepthBuffer: generateDepthBuffer,
  74004. generateStencilBuffer: generateStencilBuffer
  74005. };
  74006. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  74007. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  74008. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  74009. }
  74010. if (!delayAllocation) {
  74011. if (isCube) {
  74012. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  74013. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  74014. _this._textureMatrix = BABYLON.Matrix.Identity();
  74015. }
  74016. else {
  74017. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  74018. }
  74019. }
  74020. return _this;
  74021. }
  74022. Object.defineProperty(RenderTargetTexture.prototype, "renderList", {
  74023. /**
  74024. * Use this list to define the list of mesh you want to render.
  74025. */
  74026. get: function () {
  74027. return this._renderList;
  74028. },
  74029. set: function (value) {
  74030. this._renderList = value;
  74031. if (this._renderList) {
  74032. this._hookArray(this._renderList);
  74033. }
  74034. },
  74035. enumerable: true,
  74036. configurable: true
  74037. });
  74038. RenderTargetTexture.prototype._hookArray = function (array) {
  74039. var _this = this;
  74040. var oldPush = array.push;
  74041. array.push = function () {
  74042. var items = [];
  74043. for (var _i = 0; _i < arguments.length; _i++) {
  74044. items[_i] = arguments[_i];
  74045. }
  74046. var wasEmpty = array.length === 0;
  74047. var result = oldPush.apply(array, items);
  74048. if (wasEmpty) {
  74049. _this.getScene().meshes.forEach(function (mesh) {
  74050. mesh._markSubMeshesAsLightDirty();
  74051. });
  74052. }
  74053. return result;
  74054. };
  74055. var oldSplice = array.splice;
  74056. array.splice = function (index, deleteCount) {
  74057. var deleted = oldSplice.apply(array, [index, deleteCount]);
  74058. if (array.length === 0) {
  74059. _this.getScene().meshes.forEach(function (mesh) {
  74060. mesh._markSubMeshesAsLightDirty();
  74061. });
  74062. }
  74063. return deleted;
  74064. };
  74065. };
  74066. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  74067. /**
  74068. * Set a after unbind callback in the texture.
  74069. * This has been kept for backward compatibility and use of onAfterUnbindObservable is recommended.
  74070. */
  74071. set: function (callback) {
  74072. if (this._onAfterUnbindObserver) {
  74073. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  74074. }
  74075. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  74076. },
  74077. enumerable: true,
  74078. configurable: true
  74079. });
  74080. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  74081. /**
  74082. * Set a before render callback in the texture.
  74083. * This has been kept for backward compatibility and use of onBeforeRenderObservable is recommended.
  74084. */
  74085. set: function (callback) {
  74086. if (this._onBeforeRenderObserver) {
  74087. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  74088. }
  74089. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  74090. },
  74091. enumerable: true,
  74092. configurable: true
  74093. });
  74094. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  74095. /**
  74096. * Set a after render callback in the texture.
  74097. * This has been kept for backward compatibility and use of onAfterRenderObservable is recommended.
  74098. */
  74099. set: function (callback) {
  74100. if (this._onAfterRenderObserver) {
  74101. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  74102. }
  74103. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  74104. },
  74105. enumerable: true,
  74106. configurable: true
  74107. });
  74108. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  74109. /**
  74110. * Set a clear callback in the texture.
  74111. * This has been kept for backward compatibility and use of onClearObservable is recommended.
  74112. */
  74113. set: function (callback) {
  74114. if (this._onClearObserver) {
  74115. this.onClearObservable.remove(this._onClearObserver);
  74116. }
  74117. this._onClearObserver = this.onClearObservable.add(callback);
  74118. },
  74119. enumerable: true,
  74120. configurable: true
  74121. });
  74122. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  74123. /**
  74124. * Gets render target creation options that were used.
  74125. */
  74126. get: function () {
  74127. return this._renderTargetOptions;
  74128. },
  74129. enumerable: true,
  74130. configurable: true
  74131. });
  74132. RenderTargetTexture.prototype._onRatioRescale = function () {
  74133. if (this._sizeRatio) {
  74134. this.resize(this._initialSizeParameter);
  74135. }
  74136. };
  74137. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  74138. get: function () {
  74139. return this._boundingBoxSize;
  74140. },
  74141. /**
  74142. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  74143. * When defined, the cubemap will switch to local mode
  74144. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  74145. * @example https://www.babylonjs-playground.com/#RNASML
  74146. */
  74147. set: function (value) {
  74148. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  74149. return;
  74150. }
  74151. this._boundingBoxSize = value;
  74152. var scene = this.getScene();
  74153. if (scene) {
  74154. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  74155. }
  74156. },
  74157. enumerable: true,
  74158. configurable: true
  74159. });
  74160. /**
  74161. * Creates a depth stencil texture.
  74162. * This is only available in WebGL 2 or with the depth texture extension available.
  74163. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  74164. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  74165. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  74166. */
  74167. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  74168. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  74169. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  74170. if (generateStencil === void 0) { generateStencil = false; }
  74171. if (!this.getScene()) {
  74172. return;
  74173. }
  74174. var engine = this.getScene().getEngine();
  74175. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  74176. bilinearFiltering: bilinearFiltering,
  74177. comparisonFunction: comparisonFunction,
  74178. generateStencil: generateStencil,
  74179. isCube: this.isCube
  74180. });
  74181. engine.setFrameBufferDepthStencilTexture(this);
  74182. };
  74183. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  74184. if (size.ratio) {
  74185. this._sizeRatio = size.ratio;
  74186. this._size = {
  74187. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  74188. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  74189. };
  74190. }
  74191. else {
  74192. this._size = size;
  74193. }
  74194. };
  74195. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  74196. /**
  74197. * Define the number of samples to use in case of MSAA.
  74198. * It defaults to one meaning no MSAA has been enabled.
  74199. */
  74200. get: function () {
  74201. return this._samples;
  74202. },
  74203. set: function (value) {
  74204. if (this._samples === value) {
  74205. return;
  74206. }
  74207. var scene = this.getScene();
  74208. if (!scene) {
  74209. return;
  74210. }
  74211. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  74212. },
  74213. enumerable: true,
  74214. configurable: true
  74215. });
  74216. /**
  74217. * Resets the refresh counter of the texture and start bak from scratch.
  74218. * Could be useful to regenerate the texture if it is setup to render only once.
  74219. */
  74220. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  74221. this._currentRefreshId = -1;
  74222. };
  74223. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  74224. /**
  74225. * Define the refresh rate of the texture or the rendering frequency.
  74226. * Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  74227. */
  74228. get: function () {
  74229. return this._refreshRate;
  74230. },
  74231. set: function (value) {
  74232. this._refreshRate = value;
  74233. this.resetRefreshCounter();
  74234. },
  74235. enumerable: true,
  74236. configurable: true
  74237. });
  74238. /**
  74239. * Adds a post process to the render target rendering passes.
  74240. * @param postProcess define the post process to add
  74241. */
  74242. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  74243. if (!this._postProcessManager) {
  74244. var scene = this.getScene();
  74245. if (!scene) {
  74246. return;
  74247. }
  74248. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  74249. this._postProcesses = new Array();
  74250. }
  74251. this._postProcesses.push(postProcess);
  74252. this._postProcesses[0].autoClear = false;
  74253. };
  74254. /**
  74255. * Clear all the post processes attached to the render target
  74256. * @param dispose define if the cleared post processesshould also be disposed (false by default)
  74257. */
  74258. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  74259. if (dispose === void 0) { dispose = false; }
  74260. if (!this._postProcesses) {
  74261. return;
  74262. }
  74263. if (dispose) {
  74264. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  74265. var postProcess = _a[_i];
  74266. postProcess.dispose();
  74267. }
  74268. }
  74269. this._postProcesses = [];
  74270. };
  74271. /**
  74272. * Remove one of the post process from the list of attached post processes to the texture
  74273. * @param postProcess define the post process to remove from the list
  74274. */
  74275. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  74276. if (!this._postProcesses) {
  74277. return;
  74278. }
  74279. var index = this._postProcesses.indexOf(postProcess);
  74280. if (index === -1) {
  74281. return;
  74282. }
  74283. this._postProcesses.splice(index, 1);
  74284. if (this._postProcesses.length > 0) {
  74285. this._postProcesses[0].autoClear = false;
  74286. }
  74287. };
  74288. /** @hidden */
  74289. RenderTargetTexture.prototype._shouldRender = function () {
  74290. if (this._currentRefreshId === -1) { // At least render once
  74291. this._currentRefreshId = 1;
  74292. return true;
  74293. }
  74294. if (this.refreshRate === this._currentRefreshId) {
  74295. this._currentRefreshId = 1;
  74296. return true;
  74297. }
  74298. this._currentRefreshId++;
  74299. return false;
  74300. };
  74301. /**
  74302. * Gets the actual render size of the texture.
  74303. * @returns the width of the render size
  74304. */
  74305. RenderTargetTexture.prototype.getRenderSize = function () {
  74306. return this.getRenderWidth();
  74307. };
  74308. /**
  74309. * Gets the actual render width of the texture.
  74310. * @returns the width of the render size
  74311. */
  74312. RenderTargetTexture.prototype.getRenderWidth = function () {
  74313. if (this._size.width) {
  74314. return this._size.width;
  74315. }
  74316. return this._size;
  74317. };
  74318. /**
  74319. * Gets the actual render height of the texture.
  74320. * @returns the height of the render size
  74321. */
  74322. RenderTargetTexture.prototype.getRenderHeight = function () {
  74323. if (this._size.width) {
  74324. return this._size.height;
  74325. }
  74326. return this._size;
  74327. };
  74328. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  74329. /**
  74330. * Get if the texture can be rescaled or not.
  74331. */
  74332. get: function () {
  74333. return true;
  74334. },
  74335. enumerable: true,
  74336. configurable: true
  74337. });
  74338. /**
  74339. * Resize the texture using a ratio.
  74340. * @param ratio the ratio to apply to the texture size in order to compute the new target size
  74341. */
  74342. RenderTargetTexture.prototype.scale = function (ratio) {
  74343. var newSize = this.getRenderSize() * ratio;
  74344. this.resize(newSize);
  74345. };
  74346. /**
  74347. * Get the texture reflection matrix used to rotate/transform the reflection.
  74348. * @returns the reflection matrix
  74349. */
  74350. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  74351. if (this.isCube) {
  74352. return this._textureMatrix;
  74353. }
  74354. return _super.prototype.getReflectionTextureMatrix.call(this);
  74355. };
  74356. /**
  74357. * Resize the texture to a new desired size.
  74358. * Be carrefull as it will recreate all the data in the new texture.
  74359. * @param size Define the new size. It can be:
  74360. * - a number for squared texture,
  74361. * - an object containing { width: number, height: number }
  74362. * - or an object containing a ratio { ratio: number }
  74363. */
  74364. RenderTargetTexture.prototype.resize = function (size) {
  74365. this.releaseInternalTexture();
  74366. var scene = this.getScene();
  74367. if (!scene) {
  74368. return;
  74369. }
  74370. this._processSizeParameter(size);
  74371. if (this.isCube) {
  74372. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  74373. }
  74374. else {
  74375. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  74376. }
  74377. };
  74378. /**
  74379. * Renders all the objects from the render list into the texture.
  74380. * @param useCameraPostProcess Define if camera post processes should be used during the rendering
  74381. * @param dumpForDebug Define if the rendering result should be dumped (copied) for debugging purpose
  74382. */
  74383. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  74384. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  74385. if (dumpForDebug === void 0) { dumpForDebug = false; }
  74386. var scene = this.getScene();
  74387. if (!scene) {
  74388. return;
  74389. }
  74390. var engine = scene.getEngine();
  74391. if (this.useCameraPostProcesses !== undefined) {
  74392. useCameraPostProcess = this.useCameraPostProcesses;
  74393. }
  74394. if (this._waitingRenderList) {
  74395. this.renderList = [];
  74396. for (var index = 0; index < this._waitingRenderList.length; index++) {
  74397. var id = this._waitingRenderList[index];
  74398. var mesh_1 = scene.getMeshByID(id);
  74399. if (mesh_1) {
  74400. this.renderList.push(mesh_1);
  74401. }
  74402. }
  74403. delete this._waitingRenderList;
  74404. }
  74405. // Is predicate defined?
  74406. if (this.renderListPredicate) {
  74407. if (this.renderList) {
  74408. this.renderList.length = 0; // Clear previous renderList
  74409. }
  74410. else {
  74411. this.renderList = [];
  74412. }
  74413. var scene = this.getScene();
  74414. if (!scene) {
  74415. return;
  74416. }
  74417. var sceneMeshes = scene.meshes;
  74418. for (var index = 0; index < sceneMeshes.length; index++) {
  74419. var mesh = sceneMeshes[index];
  74420. if (this.renderListPredicate(mesh)) {
  74421. this.renderList.push(mesh);
  74422. }
  74423. }
  74424. }
  74425. this.onBeforeBindObservable.notifyObservers(this);
  74426. // Set custom projection.
  74427. // Needs to be before binding to prevent changing the aspect ratio.
  74428. var camera;
  74429. if (this.activeCamera) {
  74430. camera = this.activeCamera;
  74431. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  74432. if (this.activeCamera !== scene.activeCamera) {
  74433. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  74434. }
  74435. }
  74436. else {
  74437. camera = scene.activeCamera;
  74438. if (camera) {
  74439. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  74440. }
  74441. }
  74442. // Prepare renderingManager
  74443. this._renderingManager.reset();
  74444. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  74445. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  74446. var sceneRenderId = scene.getRenderId();
  74447. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  74448. var mesh = currentRenderList[meshIndex];
  74449. if (mesh) {
  74450. if (!mesh.isReady(this.refreshRate === 0)) {
  74451. this.resetRefreshCounter();
  74452. continue;
  74453. }
  74454. mesh._preActivateForIntermediateRendering(sceneRenderId);
  74455. var isMasked = void 0;
  74456. if (!this.renderList && camera) {
  74457. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  74458. }
  74459. else {
  74460. isMasked = false;
  74461. }
  74462. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  74463. mesh._activate(sceneRenderId);
  74464. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  74465. var subMesh = mesh.subMeshes[subIndex];
  74466. scene._activeIndices.addCount(subMesh.indexCount, false);
  74467. this._renderingManager.dispatch(subMesh, mesh);
  74468. }
  74469. }
  74470. }
  74471. }
  74472. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  74473. var particleSystem = scene.particleSystems[particleIndex];
  74474. var emitter = particleSystem.emitter;
  74475. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  74476. continue;
  74477. }
  74478. if (currentRenderList.indexOf(emitter) >= 0) {
  74479. this._renderingManager.dispatchParticles(particleSystem);
  74480. }
  74481. }
  74482. if (this.isCube) {
  74483. for (var face = 0; face < 6; face++) {
  74484. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  74485. scene.incrementRenderId();
  74486. scene.resetCachedMaterial();
  74487. }
  74488. }
  74489. else {
  74490. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  74491. }
  74492. this.onAfterUnbindObservable.notifyObservers(this);
  74493. if (scene.activeCamera) {
  74494. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  74495. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  74496. }
  74497. engine.setViewport(scene.activeCamera.viewport);
  74498. }
  74499. scene.resetCachedMaterial();
  74500. };
  74501. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  74502. var minimum = 128;
  74503. var x = renderDimension * scale;
  74504. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  74505. // Ensure we don't exceed the render dimension (while staying POT)
  74506. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  74507. };
  74508. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  74509. var _this = this;
  74510. if (!this._texture) {
  74511. return;
  74512. }
  74513. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  74514. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  74515. });
  74516. };
  74517. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  74518. var scene = this.getScene();
  74519. if (!scene) {
  74520. return;
  74521. }
  74522. var engine = scene.getEngine();
  74523. if (!this._texture) {
  74524. return;
  74525. }
  74526. // Bind
  74527. if (this._postProcessManager) {
  74528. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  74529. }
  74530. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  74531. if (this._texture) {
  74532. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  74533. }
  74534. }
  74535. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  74536. // Clear
  74537. if (this.onClearObservable.hasObservers()) {
  74538. this.onClearObservable.notifyObservers(engine);
  74539. }
  74540. else {
  74541. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  74542. }
  74543. if (!this._doNotChangeAspectRatio) {
  74544. scene.updateTransformMatrix(true);
  74545. }
  74546. // Before Camera Draw
  74547. for (var _i = 0, _a = scene._beforeRenderTargetDrawStage; _i < _a.length; _i++) {
  74548. var step = _a[_i];
  74549. step.action(this);
  74550. }
  74551. // Render
  74552. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  74553. // After Camera Draw
  74554. for (var _b = 0, _c = scene._afterRenderTargetDrawStage; _b < _c.length; _b++) {
  74555. var step = _c[_b];
  74556. step.action(this);
  74557. }
  74558. if (this._postProcessManager) {
  74559. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  74560. }
  74561. else if (useCameraPostProcess) {
  74562. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  74563. }
  74564. if (!this._doNotChangeAspectRatio) {
  74565. scene.updateTransformMatrix(true);
  74566. }
  74567. // Dump ?
  74568. if (dumpForDebug) {
  74569. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  74570. }
  74571. // Unbind
  74572. if (!this.isCube || faceIndex === 5) {
  74573. if (this.isCube) {
  74574. if (faceIndex === 5) {
  74575. engine.generateMipMapsForCubemap(this._texture);
  74576. }
  74577. }
  74578. this.unbindFrameBuffer(engine, faceIndex);
  74579. }
  74580. else {
  74581. this.onAfterRenderObservable.notifyObservers(faceIndex);
  74582. }
  74583. };
  74584. /**
  74585. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  74586. * This allowed control for front to back rendering or reversly depending of the special needs.
  74587. *
  74588. * @param renderingGroupId The rendering group id corresponding to its index
  74589. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  74590. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  74591. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  74592. */
  74593. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  74594. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  74595. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  74596. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  74597. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  74598. };
  74599. /**
  74600. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  74601. *
  74602. * @param renderingGroupId The rendering group id corresponding to its index
  74603. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  74604. */
  74605. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  74606. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  74607. this._renderingManager._useSceneAutoClearSetup = false;
  74608. };
  74609. /**
  74610. * Clones the texture.
  74611. * @returns the cloned texture
  74612. */
  74613. RenderTargetTexture.prototype.clone = function () {
  74614. var textureSize = this.getSize();
  74615. 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);
  74616. // Base texture
  74617. newTexture.hasAlpha = this.hasAlpha;
  74618. newTexture.level = this.level;
  74619. // RenderTarget Texture
  74620. newTexture.coordinatesMode = this.coordinatesMode;
  74621. if (this.renderList) {
  74622. newTexture.renderList = this.renderList.slice(0);
  74623. }
  74624. return newTexture;
  74625. };
  74626. /**
  74627. * Serialize the texture to a JSON representation we can easily use in the resepective Parse function.
  74628. * @returns The JSON representation of the texture
  74629. */
  74630. RenderTargetTexture.prototype.serialize = function () {
  74631. if (!this.name) {
  74632. return null;
  74633. }
  74634. var serializationObject = _super.prototype.serialize.call(this);
  74635. serializationObject.renderTargetSize = this.getRenderSize();
  74636. serializationObject.renderList = [];
  74637. if (this.renderList) {
  74638. for (var index = 0; index < this.renderList.length; index++) {
  74639. serializationObject.renderList.push(this.renderList[index].id);
  74640. }
  74641. }
  74642. return serializationObject;
  74643. };
  74644. /**
  74645. * This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  74646. */
  74647. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  74648. var objBuffer = this.getInternalTexture();
  74649. var scene = this.getScene();
  74650. if (objBuffer && scene) {
  74651. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  74652. }
  74653. };
  74654. /**
  74655. * Dispose the texture and release its associated resources.
  74656. */
  74657. RenderTargetTexture.prototype.dispose = function () {
  74658. if (this._postProcessManager) {
  74659. this._postProcessManager.dispose();
  74660. this._postProcessManager = null;
  74661. }
  74662. this.clearPostProcesses(true);
  74663. if (this._resizeObserver) {
  74664. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  74665. this._resizeObserver = null;
  74666. }
  74667. this.renderList = null;
  74668. // Remove from custom render targets
  74669. var scene = this.getScene();
  74670. if (!scene) {
  74671. return;
  74672. }
  74673. var index = scene.customRenderTargets.indexOf(this);
  74674. if (index >= 0) {
  74675. scene.customRenderTargets.splice(index, 1);
  74676. }
  74677. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  74678. var camera = _a[_i];
  74679. index = camera.customRenderTargets.indexOf(this);
  74680. if (index >= 0) {
  74681. camera.customRenderTargets.splice(index, 1);
  74682. }
  74683. }
  74684. _super.prototype.dispose.call(this);
  74685. };
  74686. /** @hidden */
  74687. RenderTargetTexture.prototype._rebuild = function () {
  74688. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  74689. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  74690. }
  74691. if (this._postProcessManager) {
  74692. this._postProcessManager._rebuild();
  74693. }
  74694. };
  74695. /**
  74696. * Clear the info related to rendering groups preventing retention point in material dispose.
  74697. */
  74698. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  74699. if (this._renderingManager) {
  74700. this._renderingManager.freeRenderingGroups();
  74701. }
  74702. };
  74703. /**
  74704. * The texture will only be rendered once which can be useful to improve performance if everything in your render is static for instance.
  74705. */
  74706. RenderTargetTexture.REFRESHRATE_RENDER_ONCE = 0;
  74707. /**
  74708. * The texture will only be rendered rendered every frame and is recomended for dynamic contents.
  74709. */
  74710. RenderTargetTexture.REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  74711. /**
  74712. * The texture will be rendered every 2 frames which could be enough if your dynamic objects are not
  74713. * the central point of your effect and can save a lot of performances.
  74714. */
  74715. RenderTargetTexture.REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  74716. return RenderTargetTexture;
  74717. }(BABYLON.Texture));
  74718. BABYLON.RenderTargetTexture = RenderTargetTexture;
  74719. })(BABYLON || (BABYLON = {}));
  74720. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  74721. var BABYLON;
  74722. (function (BABYLON) {
  74723. /**
  74724. * A multi render target, like a render target provides the ability to render to a texture.
  74725. * Unlike the render target, it can render to several draw buffers in one draw.
  74726. * This is specially interesting in deferred rendering or for any effects requiring more than
  74727. * just one color from a single pass.
  74728. */
  74729. var MultiRenderTarget = /** @class */ (function (_super) {
  74730. __extends(MultiRenderTarget, _super);
  74731. /**
  74732. * Instantiate a new multi render target texture.
  74733. * A multi render target, like a render target provides the ability to render to a texture.
  74734. * Unlike the render target, it can render to several draw buffers in one draw.
  74735. * This is specially interesting in deferred rendering or for any effects requiring more than
  74736. * just one color from a single pass.
  74737. * @param name Define the name of the texture
  74738. * @param size Define the size of the buffers to render to
  74739. * @param count Define the number of target we are rendering into
  74740. * @param scene Define the scene the texture belongs to
  74741. * @param options Define the options used to create the multi render target
  74742. */
  74743. function MultiRenderTarget(name, size, count, scene, options) {
  74744. var _this = this;
  74745. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  74746. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  74747. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  74748. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  74749. _this._engine = scene.getEngine();
  74750. if (!_this.isSupported) {
  74751. _this.dispose();
  74752. return;
  74753. }
  74754. var types = [];
  74755. var samplingModes = [];
  74756. for (var i = 0; i < count; i++) {
  74757. if (options && options.types && options.types[i] !== undefined) {
  74758. types.push(options.types[i]);
  74759. }
  74760. else {
  74761. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  74762. }
  74763. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  74764. samplingModes.push(options.samplingModes[i]);
  74765. }
  74766. else {
  74767. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  74768. }
  74769. }
  74770. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  74771. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  74772. _this._size = size;
  74773. _this._multiRenderTargetOptions = {
  74774. samplingModes: samplingModes,
  74775. generateMipMaps: generateMipMaps,
  74776. generateDepthBuffer: generateDepthBuffer,
  74777. generateStencilBuffer: generateStencilBuffer,
  74778. generateDepthTexture: generateDepthTexture,
  74779. types: types,
  74780. textureCount: count
  74781. };
  74782. _this._createInternalTextures();
  74783. _this._createTextures();
  74784. return _this;
  74785. }
  74786. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  74787. /**
  74788. * Get if draw buffers are currently supported by the used hardware and browser.
  74789. */
  74790. get: function () {
  74791. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  74792. },
  74793. enumerable: true,
  74794. configurable: true
  74795. });
  74796. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  74797. /**
  74798. * Get the list of textures generated by the multi render target.
  74799. */
  74800. get: function () {
  74801. return this._textures;
  74802. },
  74803. enumerable: true,
  74804. configurable: true
  74805. });
  74806. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  74807. /**
  74808. * Get the depth texture generated by the multi render target if options.generateDepthTexture has been set
  74809. */
  74810. get: function () {
  74811. return this._textures[this._textures.length - 1];
  74812. },
  74813. enumerable: true,
  74814. configurable: true
  74815. });
  74816. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  74817. /**
  74818. * Set the wrapping mode on U of all the textures we are rendering to.
  74819. * Can be any of the Texture. (CLAMP_ADDRESSMODE, MIRROR_ADDRESSMODE or WRAP_ADDRESSMODE)
  74820. */
  74821. set: function (wrap) {
  74822. if (this._textures) {
  74823. for (var i = 0; i < this._textures.length; i++) {
  74824. this._textures[i].wrapU = wrap;
  74825. }
  74826. }
  74827. },
  74828. enumerable: true,
  74829. configurable: true
  74830. });
  74831. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  74832. /**
  74833. * Set the wrapping mode on V of all the textures we are rendering to.
  74834. * Can be any of the Texture. (CLAMP_ADDRESSMODE, MIRROR_ADDRESSMODE or WRAP_ADDRESSMODE)
  74835. */
  74836. set: function (wrap) {
  74837. if (this._textures) {
  74838. for (var i = 0; i < this._textures.length; i++) {
  74839. this._textures[i].wrapV = wrap;
  74840. }
  74841. }
  74842. },
  74843. enumerable: true,
  74844. configurable: true
  74845. });
  74846. /** @hidden */
  74847. MultiRenderTarget.prototype._rebuild = function () {
  74848. this.releaseInternalTextures();
  74849. this._createInternalTextures();
  74850. for (var i = 0; i < this._internalTextures.length; i++) {
  74851. var texture = this._textures[i];
  74852. texture._texture = this._internalTextures[i];
  74853. }
  74854. // Keeps references to frame buffer and stencil/depth buffer
  74855. this._texture = this._internalTextures[0];
  74856. };
  74857. MultiRenderTarget.prototype._createInternalTextures = function () {
  74858. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  74859. };
  74860. MultiRenderTarget.prototype._createTextures = function () {
  74861. this._textures = [];
  74862. for (var i = 0; i < this._internalTextures.length; i++) {
  74863. var texture = new BABYLON.Texture(null, this.getScene());
  74864. texture._texture = this._internalTextures[i];
  74865. this._textures.push(texture);
  74866. }
  74867. // Keeps references to frame buffer and stencil/depth buffer
  74868. this._texture = this._internalTextures[0];
  74869. };
  74870. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  74871. /**
  74872. * Define the number of samples used if MSAA is enabled.
  74873. */
  74874. get: function () {
  74875. return this._samples;
  74876. },
  74877. set: function (value) {
  74878. if (this._samples === value) {
  74879. return;
  74880. }
  74881. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  74882. },
  74883. enumerable: true,
  74884. configurable: true
  74885. });
  74886. /**
  74887. * Resize all the textures in the multi render target.
  74888. * Be carrefull as it will recreate all the data in the new texture.
  74889. * @param size Define the new size
  74890. */
  74891. MultiRenderTarget.prototype.resize = function (size) {
  74892. this.releaseInternalTextures();
  74893. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  74894. this._createInternalTextures();
  74895. };
  74896. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  74897. var _this = this;
  74898. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  74899. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  74900. });
  74901. };
  74902. /**
  74903. * Dispose the render targets and their associated resources
  74904. */
  74905. MultiRenderTarget.prototype.dispose = function () {
  74906. this.releaseInternalTextures();
  74907. _super.prototype.dispose.call(this);
  74908. };
  74909. /**
  74910. * Release all the underlying texture used as draw buffers.
  74911. */
  74912. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  74913. if (!this._internalTextures) {
  74914. return;
  74915. }
  74916. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  74917. if (this._internalTextures[i] !== undefined) {
  74918. this._internalTextures[i].dispose();
  74919. this._internalTextures.splice(i, 1);
  74920. }
  74921. }
  74922. };
  74923. return MultiRenderTarget;
  74924. }(BABYLON.RenderTargetTexture));
  74925. BABYLON.MultiRenderTarget = MultiRenderTarget;
  74926. })(BABYLON || (BABYLON = {}));
  74927. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  74928. var BABYLON;
  74929. (function (BABYLON) {
  74930. /**
  74931. * Mirror texture can be used to simulate the view from a mirror in a scene.
  74932. * It will dynamically be rendered every frame to adapt to the camera point of view.
  74933. * You can then easily use it as a reflectionTexture on a flat surface.
  74934. * In case the surface is not a plane, please consider relying on reflection probes.
  74935. * @see https://doc.babylonjs.com/how_to/reflect#mirrors
  74936. */
  74937. var MirrorTexture = /** @class */ (function (_super) {
  74938. __extends(MirrorTexture, _super);
  74939. /**
  74940. * Instantiates a Mirror Texture.
  74941. * Mirror texture can be used to simulate the view from a mirror in a scene.
  74942. * It will dynamically be rendered every frame to adapt to the camera point of view.
  74943. * You can then easily use it as a reflectionTexture on a flat surface.
  74944. * In case the surface is not a plane, please consider relying on reflection probes.
  74945. * @see https://doc.babylonjs.com/how_to/reflect#mirrors
  74946. * @param name
  74947. * @param size
  74948. * @param scene
  74949. * @param generateMipMaps
  74950. * @param type
  74951. * @param samplingMode
  74952. * @param generateDepthBuffer
  74953. */
  74954. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  74955. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74956. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  74957. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  74958. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  74959. _this.scene = scene;
  74960. /**
  74961. * Define the reflection plane we want to use. The mirrorPlane is usually set to the constructed reflector.
  74962. * 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.
  74963. * @see https://doc.babylonjs.com/how_to/reflect#mirrors
  74964. */
  74965. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  74966. _this._transformMatrix = BABYLON.Matrix.Zero();
  74967. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  74968. _this._adaptiveBlurKernel = 0;
  74969. _this._blurKernelX = 0;
  74970. _this._blurKernelY = 0;
  74971. _this._blurRatio = 1.0;
  74972. _this.ignoreCameraViewport = true;
  74973. _this._updateGammaSpace();
  74974. _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  74975. _this._updateGammaSpace;
  74976. });
  74977. _this.onBeforeRenderObservable.add(function () {
  74978. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  74979. _this._savedViewMatrix = scene.getViewMatrix();
  74980. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  74981. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  74982. scene.clipPlane = _this.mirrorPlane;
  74983. scene.getEngine().cullBackFaces = false;
  74984. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  74985. });
  74986. _this.onAfterRenderObservable.add(function () {
  74987. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  74988. scene.getEngine().cullBackFaces = true;
  74989. scene._mirroredCameraPosition = null;
  74990. delete scene.clipPlane;
  74991. });
  74992. return _this;
  74993. }
  74994. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  74995. get: function () {
  74996. return this._blurRatio;
  74997. },
  74998. /**
  74999. * Define the blur ratio used to blur the reflection if needed.
  75000. */
  75001. set: function (value) {
  75002. if (this._blurRatio === value) {
  75003. return;
  75004. }
  75005. this._blurRatio = value;
  75006. this._preparePostProcesses();
  75007. },
  75008. enumerable: true,
  75009. configurable: true
  75010. });
  75011. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  75012. /**
  75013. * Define the adaptive blur kernel used to blur the reflection if needed.
  75014. * This will autocompute the closest best match for the `blurKernel`
  75015. */
  75016. set: function (value) {
  75017. this._adaptiveBlurKernel = value;
  75018. this._autoComputeBlurKernel();
  75019. },
  75020. enumerable: true,
  75021. configurable: true
  75022. });
  75023. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  75024. /**
  75025. * Define the blur kernel used to blur the reflection if needed.
  75026. * Please consider using `adaptiveBlurKernel` as it could find the closest best value for you.
  75027. */
  75028. set: function (value) {
  75029. this.blurKernelX = value;
  75030. this.blurKernelY = value;
  75031. },
  75032. enumerable: true,
  75033. configurable: true
  75034. });
  75035. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  75036. get: function () {
  75037. return this._blurKernelX;
  75038. },
  75039. /**
  75040. * Define the blur kernel on the X Axis used to blur the reflection if needed.
  75041. * Please consider using `adaptiveBlurKernel` as it could find the closest best value for you.
  75042. */
  75043. set: function (value) {
  75044. if (this._blurKernelX === value) {
  75045. return;
  75046. }
  75047. this._blurKernelX = value;
  75048. this._preparePostProcesses();
  75049. },
  75050. enumerable: true,
  75051. configurable: true
  75052. });
  75053. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  75054. get: function () {
  75055. return this._blurKernelY;
  75056. },
  75057. /**
  75058. * Define the blur kernel on the Y Axis used to blur the reflection if needed.
  75059. * Please consider using `adaptiveBlurKernel` as it could find the closest best value for you.
  75060. */
  75061. set: function (value) {
  75062. if (this._blurKernelY === value) {
  75063. return;
  75064. }
  75065. this._blurKernelY = value;
  75066. this._preparePostProcesses();
  75067. },
  75068. enumerable: true,
  75069. configurable: true
  75070. });
  75071. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  75072. var engine = this.getScene().getEngine();
  75073. var dw = this.getRenderWidth() / engine.getRenderWidth();
  75074. var dh = this.getRenderHeight() / engine.getRenderHeight();
  75075. this.blurKernelX = this._adaptiveBlurKernel * dw;
  75076. this.blurKernelY = this._adaptiveBlurKernel * dh;
  75077. };
  75078. MirrorTexture.prototype._onRatioRescale = function () {
  75079. if (this._sizeRatio) {
  75080. this.resize(this._initialSizeParameter);
  75081. if (!this._adaptiveBlurKernel) {
  75082. this._preparePostProcesses();
  75083. }
  75084. }
  75085. if (this._adaptiveBlurKernel) {
  75086. this._autoComputeBlurKernel();
  75087. }
  75088. };
  75089. MirrorTexture.prototype._updateGammaSpace = function () {
  75090. this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;
  75091. };
  75092. MirrorTexture.prototype._preparePostProcesses = function () {
  75093. this.clearPostProcesses(true);
  75094. if (this._blurKernelX && this._blurKernelY) {
  75095. var engine = this.getScene().getEngine();
  75096. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  75097. 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);
  75098. this._blurX.autoClear = false;
  75099. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  75100. this._blurX.inputTexture = this._texture;
  75101. }
  75102. else {
  75103. this._blurX.alwaysForcePOT = true;
  75104. }
  75105. 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);
  75106. this._blurY.autoClear = false;
  75107. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  75108. this.addPostProcess(this._blurX);
  75109. this.addPostProcess(this._blurY);
  75110. }
  75111. else {
  75112. if (this._blurY) {
  75113. this.removePostProcess(this._blurY);
  75114. this._blurY.dispose();
  75115. this._blurY = null;
  75116. }
  75117. if (this._blurX) {
  75118. this.removePostProcess(this._blurX);
  75119. this._blurX.dispose();
  75120. this._blurX = null;
  75121. }
  75122. }
  75123. };
  75124. /**
  75125. * Clone the mirror texture.
  75126. * @returns the cloned texture
  75127. */
  75128. MirrorTexture.prototype.clone = function () {
  75129. var scene = this.getScene();
  75130. if (!scene) {
  75131. return this;
  75132. }
  75133. var textureSize = this.getSize();
  75134. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  75135. // Base texture
  75136. newTexture.hasAlpha = this.hasAlpha;
  75137. newTexture.level = this.level;
  75138. // Mirror Texture
  75139. newTexture.mirrorPlane = this.mirrorPlane.clone();
  75140. if (this.renderList) {
  75141. newTexture.renderList = this.renderList.slice(0);
  75142. }
  75143. return newTexture;
  75144. };
  75145. /**
  75146. * Serialize the texture to a JSON representation you could use in Parse later on
  75147. * @returns the serialized JSON representation
  75148. */
  75149. MirrorTexture.prototype.serialize = function () {
  75150. if (!this.name) {
  75151. return null;
  75152. }
  75153. var serializationObject = _super.prototype.serialize.call(this);
  75154. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  75155. return serializationObject;
  75156. };
  75157. /**
  75158. * Dispose the texture and release its associated resources.
  75159. */
  75160. MirrorTexture.prototype.dispose = function () {
  75161. _super.prototype.dispose.call(this);
  75162. this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);
  75163. };
  75164. return MirrorTexture;
  75165. }(BABYLON.RenderTargetTexture));
  75166. BABYLON.MirrorTexture = MirrorTexture;
  75167. })(BABYLON || (BABYLON = {}));
  75168. //# sourceMappingURL=babylon.mirrorTexture.js.map
  75169. var BABYLON;
  75170. (function (BABYLON) {
  75171. /**
  75172. * Creates a refraction texture used by refraction channel of the standard material.
  75173. * It is like a mirror but to see through a material.
  75174. * @see https://doc.babylonjs.com/how_to/reflect#refraction
  75175. */
  75176. var RefractionTexture = /** @class */ (function (_super) {
  75177. __extends(RefractionTexture, _super);
  75178. /**
  75179. * Creates a refraction texture used by refraction channel of the standard material.
  75180. * It is like a mirror but to see through a material.
  75181. * @see https://doc.babylonjs.com/how_to/reflect#refraction
  75182. * @param name Define the texture name
  75183. * @param size Define the size of the underlying texture
  75184. * @param scene Define the scene the refraction belongs to
  75185. * @param generateMipMaps Define if we need to generate mips level for the refraction
  75186. */
  75187. function RefractionTexture(name, size, scene, generateMipMaps) {
  75188. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  75189. /**
  75190. * Define the reflection plane we want to use. The refractionPlane is usually set to the constructed refractor.
  75191. * 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.
  75192. * @see https://doc.babylonjs.com/how_to/reflect#refraction
  75193. */
  75194. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  75195. /**
  75196. * Define how deep under the surface we should see.
  75197. */
  75198. _this.depth = 2.0;
  75199. _this.onBeforeRenderObservable.add(function () {
  75200. scene.clipPlane = _this.refractionPlane;
  75201. });
  75202. _this.onAfterRenderObservable.add(function () {
  75203. delete scene.clipPlane;
  75204. });
  75205. return _this;
  75206. }
  75207. /**
  75208. * Clone the refraction texture.
  75209. * @returns the cloned texture
  75210. */
  75211. RefractionTexture.prototype.clone = function () {
  75212. var scene = this.getScene();
  75213. if (!scene) {
  75214. return this;
  75215. }
  75216. var textureSize = this.getSize();
  75217. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  75218. // Base texture
  75219. newTexture.hasAlpha = this.hasAlpha;
  75220. newTexture.level = this.level;
  75221. // Refraction Texture
  75222. newTexture.refractionPlane = this.refractionPlane.clone();
  75223. if (this.renderList) {
  75224. newTexture.renderList = this.renderList.slice(0);
  75225. }
  75226. newTexture.depth = this.depth;
  75227. return newTexture;
  75228. };
  75229. /**
  75230. * Serialize the texture to a JSON representation you could use in Parse later on
  75231. * @returns the serialized JSON representation
  75232. */
  75233. RefractionTexture.prototype.serialize = function () {
  75234. if (!this.name) {
  75235. return null;
  75236. }
  75237. var serializationObject = _super.prototype.serialize.call(this);
  75238. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  75239. serializationObject.depth = this.depth;
  75240. return serializationObject;
  75241. };
  75242. return RefractionTexture;
  75243. }(BABYLON.RenderTargetTexture));
  75244. BABYLON.RefractionTexture = RefractionTexture;
  75245. })(BABYLON || (BABYLON = {}));
  75246. //# sourceMappingURL=babylon.refractionTexture.js.map
  75247. var BABYLON;
  75248. (function (BABYLON) {
  75249. /**
  75250. * A class extending Texture allowing drawing on a texture
  75251. * @see http://doc.babylonjs.com/how_to/dynamictexture
  75252. */
  75253. var DynamicTexture = /** @class */ (function (_super) {
  75254. __extends(DynamicTexture, _super);
  75255. /**
  75256. * Creates a DynamicTexture
  75257. * @param name defines the name of the texture
  75258. * @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
  75259. * @param scene defines the scene where you want the texture
  75260. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  75261. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  75262. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  75263. */
  75264. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  75265. if (scene === void 0) { scene = null; }
  75266. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  75267. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  75268. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  75269. _this.name = name;
  75270. _this._engine = _this.getScene().getEngine();
  75271. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  75272. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  75273. _this._generateMipMaps = generateMipMaps;
  75274. if (options.getContext) {
  75275. _this._canvas = options;
  75276. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  75277. }
  75278. else {
  75279. _this._canvas = document.createElement("canvas");
  75280. if (options.width || options.width === 0) {
  75281. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  75282. }
  75283. else {
  75284. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  75285. }
  75286. }
  75287. var textureSize = _this.getSize();
  75288. _this._canvas.width = textureSize.width;
  75289. _this._canvas.height = textureSize.height;
  75290. _this._context = _this._canvas.getContext("2d");
  75291. return _this;
  75292. }
  75293. /**
  75294. * Get the current class name of the texture useful for serialization or dynamic coding.
  75295. * @returns "DynamicTexture"
  75296. */
  75297. DynamicTexture.prototype.getClassName = function () {
  75298. return "DynamicTexture";
  75299. };
  75300. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  75301. /**
  75302. * Gets the current state of canRescale
  75303. */
  75304. get: function () {
  75305. return true;
  75306. },
  75307. enumerable: true,
  75308. configurable: true
  75309. });
  75310. DynamicTexture.prototype._recreate = function (textureSize) {
  75311. this._canvas.width = textureSize.width;
  75312. this._canvas.height = textureSize.height;
  75313. this.releaseInternalTexture();
  75314. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this.samplingMode);
  75315. };
  75316. /**
  75317. * Scales the texture
  75318. * @param ratio the scale factor to apply to both width and height
  75319. */
  75320. DynamicTexture.prototype.scale = function (ratio) {
  75321. var textureSize = this.getSize();
  75322. textureSize.width *= ratio;
  75323. textureSize.height *= ratio;
  75324. this._recreate(textureSize);
  75325. };
  75326. /**
  75327. * Resizes the texture
  75328. * @param width the new width
  75329. * @param height the new height
  75330. */
  75331. DynamicTexture.prototype.scaleTo = function (width, height) {
  75332. var textureSize = this.getSize();
  75333. textureSize.width = width;
  75334. textureSize.height = height;
  75335. this._recreate(textureSize);
  75336. };
  75337. /**
  75338. * Gets the context of the canvas used by the texture
  75339. * @returns the canvas context of the dynamic texture
  75340. */
  75341. DynamicTexture.prototype.getContext = function () {
  75342. return this._context;
  75343. };
  75344. /**
  75345. * Clears the texture
  75346. */
  75347. DynamicTexture.prototype.clear = function () {
  75348. var size = this.getSize();
  75349. this._context.fillRect(0, 0, size.width, size.height);
  75350. };
  75351. /**
  75352. * Updates the texture
  75353. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  75354. * @param premulAlpha defines if alpha is stored as premultiplied (default is false)
  75355. */
  75356. DynamicTexture.prototype.update = function (invertY, premulAlpha) {
  75357. if (premulAlpha === void 0) { premulAlpha = false; }
  75358. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, premulAlpha, this._format || undefined);
  75359. };
  75360. /**
  75361. * Draws text onto the texture
  75362. * @param text defines the text to be drawn
  75363. * @param x defines the placement of the text from the left
  75364. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  75365. * @param font defines the font to be used with font-style, font-size, font-name
  75366. * @param color defines the color used for the text
  75367. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  75368. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  75369. * @param update defines whether texture is immediately update (default is true)
  75370. */
  75371. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  75372. if (update === void 0) { update = true; }
  75373. var size = this.getSize();
  75374. if (clearColor) {
  75375. this._context.fillStyle = clearColor;
  75376. this._context.fillRect(0, 0, size.width, size.height);
  75377. }
  75378. this._context.font = font;
  75379. if (x === null || x === undefined) {
  75380. var textSize = this._context.measureText(text);
  75381. x = (size.width - textSize.width) / 2;
  75382. }
  75383. if (y === null || y === undefined) {
  75384. var fontSize = parseInt((font.replace(/\D/g, '')));
  75385. y = (size.height / 2) + (fontSize / 3.65);
  75386. }
  75387. this._context.fillStyle = color;
  75388. this._context.fillText(text, x, y);
  75389. if (update) {
  75390. this.update(invertY);
  75391. }
  75392. };
  75393. /**
  75394. * Clones the texture
  75395. * @returns the clone of the texture.
  75396. */
  75397. DynamicTexture.prototype.clone = function () {
  75398. var scene = this.getScene();
  75399. if (!scene) {
  75400. return this;
  75401. }
  75402. var textureSize = this.getSize();
  75403. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  75404. // Base texture
  75405. newTexture.hasAlpha = this.hasAlpha;
  75406. newTexture.level = this.level;
  75407. // Dynamic Texture
  75408. newTexture.wrapU = this.wrapU;
  75409. newTexture.wrapV = this.wrapV;
  75410. return newTexture;
  75411. };
  75412. /**
  75413. * Serializes the dynamic texture. The scene should be ready before the dynamic texture is serialized
  75414. * @returns a serialized dynamic texture object
  75415. */
  75416. DynamicTexture.prototype.serialize = function () {
  75417. var scene = this.getScene();
  75418. if (scene && !scene.isReady()) {
  75419. BABYLON.Tools.Warn("The scene must be ready before serializing the dynamic texture");
  75420. }
  75421. var serializationObject = _super.prototype.serialize.call(this);
  75422. serializationObject.base64String = this._canvas.toDataURL();
  75423. serializationObject.invertY = this._invertY;
  75424. serializationObject.samplingMode = this.samplingMode;
  75425. return serializationObject;
  75426. };
  75427. /** @hidden */
  75428. DynamicTexture.prototype._rebuild = function () {
  75429. this.update();
  75430. };
  75431. return DynamicTexture;
  75432. }(BABYLON.Texture));
  75433. BABYLON.DynamicTexture = DynamicTexture;
  75434. })(BABYLON || (BABYLON = {}));
  75435. //# sourceMappingURL=babylon.dynamicTexture.js.map
  75436. var BABYLON;
  75437. (function (BABYLON) {
  75438. /**
  75439. * If you want to display a video in your scene, this is the special texture for that.
  75440. * This special texture works similar to other textures, with the exception of a few parameters.
  75441. * @see https://doc.babylonjs.com/how_to/video_texture
  75442. */
  75443. var VideoTexture = /** @class */ (function (_super) {
  75444. __extends(VideoTexture, _super);
  75445. /**
  75446. * Creates a video texture.
  75447. * If you want to display a video in your scene, this is the special texture for that.
  75448. * This special texture works similar to other textures, with the exception of a few parameters.
  75449. * @see https://doc.babylonjs.com/how_to/video_texture
  75450. * @param name optional name, will detect from video source, if not defined
  75451. * @param src can be used to provide an url, array of urls or an already setup HTML video element.
  75452. * @param scene is obviously the current scene.
  75453. * @param generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  75454. * @param invertY is false by default but can be used to invert video on Y axis
  75455. * @param samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  75456. * @param settings allows finer control over video usage
  75457. */
  75458. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  75459. if (generateMipMaps === void 0) { generateMipMaps = false; }
  75460. if (invertY === void 0) { invertY = false; }
  75461. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  75462. if (settings === void 0) { settings = {
  75463. autoPlay: true,
  75464. loop: true,
  75465. autoUpdateTexture: true,
  75466. }; }
  75467. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  75468. _this._onUserActionRequestedObservable = null;
  75469. _this._stillImageCaptured = false;
  75470. _this._displayingPosterTexture = false;
  75471. _this._createInternalTexture = function () {
  75472. if (_this._texture != null) {
  75473. if (_this._displayingPosterTexture) {
  75474. _this._texture.dispose();
  75475. _this._displayingPosterTexture = false;
  75476. }
  75477. else {
  75478. return;
  75479. }
  75480. }
  75481. if (!_this._engine.needPOTTextures ||
  75482. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  75483. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  75484. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  75485. }
  75486. else {
  75487. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  75488. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  75489. _this._generateMipMaps = false;
  75490. }
  75491. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this.samplingMode);
  75492. if (!_this.video.autoplay && !_this._settings.poster) {
  75493. var oldHandler_1 = _this.video.onplaying;
  75494. var error_1 = false;
  75495. _this.video.onplaying = function () {
  75496. _this.video.onplaying = oldHandler_1;
  75497. _this._texture.isReady = true;
  75498. _this._updateInternalTexture();
  75499. if (!error_1) {
  75500. _this.video.pause();
  75501. }
  75502. if (_this.onLoadObservable.hasObservers()) {
  75503. _this.onLoadObservable.notifyObservers(_this);
  75504. }
  75505. };
  75506. var playing = _this.video.play();
  75507. if (playing) {
  75508. playing.then(function () {
  75509. // Everything is good.
  75510. })
  75511. .catch(function () {
  75512. error_1 = true;
  75513. // On Chrome for instance, new policies might prevent playing without user interaction.
  75514. if (_this._onUserActionRequestedObservable && _this._onUserActionRequestedObservable.hasObservers()) {
  75515. _this._onUserActionRequestedObservable.notifyObservers(_this);
  75516. }
  75517. });
  75518. }
  75519. else {
  75520. _this.video.onplaying = oldHandler_1;
  75521. _this._texture.isReady = true;
  75522. _this._updateInternalTexture();
  75523. if (_this.onLoadObservable.hasObservers()) {
  75524. _this.onLoadObservable.notifyObservers(_this);
  75525. }
  75526. }
  75527. }
  75528. else {
  75529. _this._texture.isReady = true;
  75530. _this._updateInternalTexture();
  75531. if (_this.onLoadObservable.hasObservers()) {
  75532. _this.onLoadObservable.notifyObservers(_this);
  75533. }
  75534. }
  75535. };
  75536. _this.reset = function () {
  75537. if (_this._texture == null) {
  75538. return;
  75539. }
  75540. if (!_this._displayingPosterTexture) {
  75541. _this._texture.dispose();
  75542. _this._texture = null;
  75543. }
  75544. };
  75545. _this._updateInternalTexture = function (e) {
  75546. if (_this._texture == null || !_this._texture.isReady) {
  75547. return;
  75548. }
  75549. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  75550. return;
  75551. }
  75552. if (_this._displayingPosterTexture) {
  75553. return;
  75554. }
  75555. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  75556. };
  75557. _this._engine = _this.getScene().getEngine();
  75558. _this._generateMipMaps = generateMipMaps;
  75559. _this._initialSamplingMode = samplingMode;
  75560. _this.autoUpdateTexture = settings.autoUpdateTexture;
  75561. _this.name = name || _this._getName(src);
  75562. _this.video = _this._getVideo(src);
  75563. _this._settings = settings;
  75564. if (settings.poster) {
  75565. _this.video.poster = settings.poster;
  75566. }
  75567. if (settings.autoPlay !== undefined) {
  75568. _this.video.autoplay = settings.autoPlay;
  75569. }
  75570. if (settings.loop !== undefined) {
  75571. _this.video.loop = settings.loop;
  75572. }
  75573. _this.video.setAttribute("playsinline", "");
  75574. _this.video.addEventListener("paused", _this._updateInternalTexture);
  75575. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  75576. _this.video.addEventListener("emptied", _this.reset);
  75577. _this._createInternalTextureOnEvent = (settings.poster && !settings.autoPlay) ? "play" : "canplay";
  75578. _this.video.addEventListener(_this._createInternalTextureOnEvent, _this._createInternalTexture);
  75579. var videoHasEnoughData = (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA);
  75580. if (settings.poster &&
  75581. (!settings.autoPlay || !videoHasEnoughData)) {
  75582. _this._texture = _this._engine.createTexture(settings.poster, false, true, scene);
  75583. _this._displayingPosterTexture = true;
  75584. }
  75585. else if (videoHasEnoughData) {
  75586. _this._createInternalTexture();
  75587. }
  75588. return _this;
  75589. }
  75590. Object.defineProperty(VideoTexture.prototype, "onUserActionRequestedObservable", {
  75591. /**
  75592. * Event triggerd when a dom action is required by the user to play the video.
  75593. * This happens due to recent changes in browser policies preventing video to auto start.
  75594. */
  75595. get: function () {
  75596. if (!this._onUserActionRequestedObservable) {
  75597. this._onUserActionRequestedObservable = new BABYLON.Observable();
  75598. }
  75599. return this._onUserActionRequestedObservable;
  75600. },
  75601. enumerable: true,
  75602. configurable: true
  75603. });
  75604. VideoTexture.prototype._getName = function (src) {
  75605. if (src instanceof HTMLVideoElement) {
  75606. return src.currentSrc;
  75607. }
  75608. if (typeof src === "object") {
  75609. return src.toString();
  75610. }
  75611. return src;
  75612. };
  75613. VideoTexture.prototype._getVideo = function (src) {
  75614. if (src instanceof HTMLVideoElement) {
  75615. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  75616. return src;
  75617. }
  75618. var video = document.createElement("video");
  75619. if (typeof src === "string") {
  75620. BABYLON.Tools.SetCorsBehavior(src, video);
  75621. video.src = src;
  75622. }
  75623. else {
  75624. BABYLON.Tools.SetCorsBehavior(src[0], video);
  75625. src.forEach(function (url) {
  75626. var source = document.createElement("source");
  75627. source.src = url;
  75628. video.appendChild(source);
  75629. });
  75630. }
  75631. return video;
  75632. };
  75633. /**
  75634. * @hidden Internal method to initiate `update`.
  75635. */
  75636. VideoTexture.prototype._rebuild = function () {
  75637. this.update();
  75638. };
  75639. /**
  75640. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  75641. */
  75642. VideoTexture.prototype.update = function () {
  75643. if (!this.autoUpdateTexture) {
  75644. // Expecting user to call `updateTexture` manually
  75645. return;
  75646. }
  75647. this.updateTexture(true);
  75648. };
  75649. /**
  75650. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  75651. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  75652. */
  75653. VideoTexture.prototype.updateTexture = function (isVisible) {
  75654. if (!isVisible) {
  75655. return;
  75656. }
  75657. if (this.video.paused && this._stillImageCaptured) {
  75658. return;
  75659. }
  75660. this._stillImageCaptured = true;
  75661. this._updateInternalTexture();
  75662. };
  75663. /**
  75664. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  75665. * @param url New url.
  75666. */
  75667. VideoTexture.prototype.updateURL = function (url) {
  75668. this.video.src = url;
  75669. };
  75670. /**
  75671. * Dispose the texture and release its associated resources.
  75672. */
  75673. VideoTexture.prototype.dispose = function () {
  75674. _super.prototype.dispose.call(this);
  75675. if (this._onUserActionRequestedObservable) {
  75676. this._onUserActionRequestedObservable.clear();
  75677. this._onUserActionRequestedObservable = null;
  75678. }
  75679. this.video.removeEventListener(this._createInternalTextureOnEvent, this._createInternalTexture);
  75680. this.video.removeEventListener("paused", this._updateInternalTexture);
  75681. this.video.removeEventListener("seeked", this._updateInternalTexture);
  75682. this.video.removeEventListener("emptied", this.reset);
  75683. this.video.pause();
  75684. };
  75685. /**
  75686. * Creates a video texture straight from your WebCam video feed.
  75687. * @param scene Define the scene the texture should be created in
  75688. * @param onReady Define a callback to triggered once the texture will be ready
  75689. * @param constraints Define the constraints to use to create the web cam feed from WebRTC
  75690. */
  75691. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  75692. var video = document.createElement("video");
  75693. video.setAttribute('autoplay', '');
  75694. video.setAttribute('muted', '');
  75695. video.setAttribute('playsinline', '');
  75696. var constraintsDeviceId;
  75697. if (constraints && constraints.deviceId) {
  75698. constraintsDeviceId = {
  75699. exact: constraints.deviceId,
  75700. };
  75701. }
  75702. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  75703. if (navigator.mediaDevices) {
  75704. navigator.mediaDevices.getUserMedia({ video: constraints })
  75705. .then(function (stream) {
  75706. if (video.mozSrcObject !== undefined) {
  75707. // hack for Firefox < 19
  75708. video.mozSrcObject = stream;
  75709. }
  75710. else {
  75711. video.srcObject = stream;
  75712. }
  75713. var onPlaying = function () {
  75714. if (onReady) {
  75715. onReady(new VideoTexture("video", video, scene, true, true));
  75716. }
  75717. video.removeEventListener("playing", onPlaying);
  75718. };
  75719. video.addEventListener("playing", onPlaying);
  75720. video.play();
  75721. })
  75722. .catch(function (err) {
  75723. BABYLON.Tools.Error(err.name);
  75724. });
  75725. }
  75726. else {
  75727. navigator.getUserMedia =
  75728. navigator.getUserMedia ||
  75729. navigator.webkitGetUserMedia ||
  75730. navigator.mozGetUserMedia ||
  75731. navigator.msGetUserMedia;
  75732. if (navigator.getUserMedia) {
  75733. navigator.getUserMedia({
  75734. video: {
  75735. deviceId: constraintsDeviceId,
  75736. width: {
  75737. min: (constraints && constraints.minWidth) || 256,
  75738. max: (constraints && constraints.maxWidth) || 640,
  75739. },
  75740. height: {
  75741. min: (constraints && constraints.minHeight) || 256,
  75742. max: (constraints && constraints.maxHeight) || 480,
  75743. },
  75744. },
  75745. }, function (stream) {
  75746. if (video.mozSrcObject !== undefined) {
  75747. // hack for Firefox < 19
  75748. video.mozSrcObject = stream;
  75749. }
  75750. else {
  75751. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  75752. }
  75753. video.play();
  75754. if (onReady) {
  75755. onReady(new VideoTexture("video", video, scene, true, true));
  75756. }
  75757. }, function (e) {
  75758. BABYLON.Tools.Error(e.name);
  75759. });
  75760. }
  75761. }
  75762. };
  75763. return VideoTexture;
  75764. }(BABYLON.Texture));
  75765. BABYLON.VideoTexture = VideoTexture;
  75766. })(BABYLON || (BABYLON = {}));
  75767. //# sourceMappingURL=babylon.videoTexture.js.map
  75768. var BABYLON;
  75769. (function (BABYLON) {
  75770. /**
  75771. * Raw texture can help creating a texture directly from an array of data.
  75772. * This can be super useful if you either get the data from an uncompressed source or
  75773. * if you wish to create your texture pixel by pixel.
  75774. */
  75775. var RawTexture = /** @class */ (function (_super) {
  75776. __extends(RawTexture, _super);
  75777. /**
  75778. * Instantiates a new RawTexture.
  75779. * Raw texture can help creating a texture directly from an array of data.
  75780. * This can be super useful if you either get the data from an uncompressed source or
  75781. * if you wish to create your texture pixel by pixel.
  75782. * @param data define the array of data to use to create the texture
  75783. * @param width define the width of the texture
  75784. * @param height define the height of the texture
  75785. * @param format define the format of the data (RGB, RGBA... Engine.TEXTUREFORMAT_xxx)
  75786. * @param scene define the scene the texture belongs to
  75787. * @param generateMipMaps define whether mip maps should be generated or not
  75788. * @param invertY define if the data should be flipped on Y when uploaded to the GPU
  75789. * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
  75790. * @param type define the format of the data (int, float... Engine.TEXTURETYPE_xxx)
  75791. */
  75792. function RawTexture(data, width, height,
  75793. /**
  75794. * Define the format of the data (RGB, RGBA... Engine.TEXTUREFORMAT_xxx)
  75795. */
  75796. format, scene, generateMipMaps, invertY, samplingMode, type) {
  75797. if (generateMipMaps === void 0) { generateMipMaps = true; }
  75798. if (invertY === void 0) { invertY = false; }
  75799. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  75800. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75801. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  75802. _this.format = format;
  75803. _this._engine = scene.getEngine();
  75804. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  75805. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  75806. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  75807. return _this;
  75808. }
  75809. /**
  75810. * Updates the texture underlying data.
  75811. * @param data Define the new data of the texture
  75812. */
  75813. RawTexture.prototype.update = function (data) {
  75814. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  75815. };
  75816. /**
  75817. * Creates a luminance texture from some data.
  75818. * @param data Define the texture data
  75819. * @param width Define the width of the texture
  75820. * @param height Define the height of the texture
  75821. * @param scene Define the scene the texture belongs to
  75822. * @param generateMipMaps Define whether or not to create mip maps for the texture
  75823. * @param invertY define if the data should be flipped on Y when uploaded to the GPU
  75824. * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
  75825. * @returns the luminance texture
  75826. */
  75827. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  75828. if (generateMipMaps === void 0) { generateMipMaps = true; }
  75829. if (invertY === void 0) { invertY = false; }
  75830. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  75831. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  75832. };
  75833. /**
  75834. * Creates a luminance alpha texture from some data.
  75835. * @param data Define the texture data
  75836. * @param width Define the width of the texture
  75837. * @param height Define the height of the texture
  75838. * @param scene Define the scene the texture belongs to
  75839. * @param generateMipMaps Define whether or not to create mip maps for the texture
  75840. * @param invertY define if the data should be flipped on Y when uploaded to the GPU
  75841. * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
  75842. * @returns the luminance alpha texture
  75843. */
  75844. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  75845. if (generateMipMaps === void 0) { generateMipMaps = true; }
  75846. if (invertY === void 0) { invertY = false; }
  75847. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  75848. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  75849. };
  75850. /**
  75851. * Creates an alpha texture from some data.
  75852. * @param data Define the texture data
  75853. * @param width Define the width of the texture
  75854. * @param height Define the height of the texture
  75855. * @param scene Define the scene the texture belongs to
  75856. * @param generateMipMaps Define whether or not to create mip maps for the texture
  75857. * @param invertY define if the data should be flipped on Y when uploaded to the GPU
  75858. * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
  75859. * @returns the alpha texture
  75860. */
  75861. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  75862. if (generateMipMaps === void 0) { generateMipMaps = true; }
  75863. if (invertY === void 0) { invertY = false; }
  75864. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  75865. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  75866. };
  75867. /**
  75868. * Creates a RGB texture from some data.
  75869. * @param data Define the texture data
  75870. * @param width Define the width of the texture
  75871. * @param height Define the height of the texture
  75872. * @param scene Define the scene the texture belongs to
  75873. * @param generateMipMaps Define whether or not to create mip maps for the texture
  75874. * @param invertY define if the data should be flipped on Y when uploaded to the GPU
  75875. * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
  75876. * @param type define the format of the data (int, float... Engine.TEXTURETYPE_xxx)
  75877. * @returns the RGB alpha texture
  75878. */
  75879. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  75880. if (generateMipMaps === void 0) { generateMipMaps = true; }
  75881. if (invertY === void 0) { invertY = false; }
  75882. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  75883. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75884. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  75885. };
  75886. /**
  75887. * Creates a RGBA texture from some data.
  75888. * @param data Define the texture data
  75889. * @param width Define the width of the texture
  75890. * @param height Define the height of the texture
  75891. * @param scene Define the scene the texture belongs to
  75892. * @param generateMipMaps Define whether or not to create mip maps for the texture
  75893. * @param invertY define if the data should be flipped on Y when uploaded to the GPU
  75894. * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
  75895. * @param type define the format of the data (int, float... Engine.TEXTURETYPE_xxx)
  75896. * @returns the RGBA texture
  75897. */
  75898. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  75899. if (generateMipMaps === void 0) { generateMipMaps = true; }
  75900. if (invertY === void 0) { invertY = false; }
  75901. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  75902. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75903. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  75904. };
  75905. /**
  75906. * Creates a R texture from some data.
  75907. * @param data Define the texture data
  75908. * @param width Define the width of the texture
  75909. * @param height Define the height of the texture
  75910. * @param scene Define the scene the texture belongs to
  75911. * @param generateMipMaps Define whether or not to create mip maps for the texture
  75912. * @param invertY define if the data should be flipped on Y when uploaded to the GPU
  75913. * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
  75914. * @param type define the format of the data (int, float... Engine.TEXTURETYPE_xxx)
  75915. * @returns the R texture
  75916. */
  75917. RawTexture.CreateRTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  75918. if (generateMipMaps === void 0) { generateMipMaps = true; }
  75919. if (invertY === void 0) { invertY = false; }
  75920. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  75921. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  75922. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_R, scene, generateMipMaps, invertY, samplingMode, type);
  75923. };
  75924. return RawTexture;
  75925. }(BABYLON.Texture));
  75926. BABYLON.RawTexture = RawTexture;
  75927. })(BABYLON || (BABYLON = {}));
  75928. //# sourceMappingURL=babylon.rawTexture.js.map
  75929. var BABYLON;
  75930. (function (BABYLON) {
  75931. /**
  75932. * Class used to store 3D textures containing user data
  75933. */
  75934. var RawTexture3D = /** @class */ (function (_super) {
  75935. __extends(RawTexture3D, _super);
  75936. /**
  75937. * Create a new RawTexture3D
  75938. * @param data defines the data of the texture
  75939. * @param width defines the width of the texture
  75940. * @param height defines the height of the texture
  75941. * @param depth defines the depth of the texture
  75942. * @param format defines the texture format to use
  75943. * @param scene defines the hosting scene
  75944. * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
  75945. * @param invertY defines if texture must be stored with Y axis inverted
  75946. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  75947. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  75948. */
  75949. function RawTexture3D(data, width, height, depth,
  75950. /** Gets or sets the texture format to use */
  75951. format, scene, generateMipMaps, invertY, samplingMode, textureType) {
  75952. if (generateMipMaps === void 0) { generateMipMaps = true; }
  75953. if (invertY === void 0) { invertY = false; }
  75954. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  75955. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75956. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  75957. _this.format = format;
  75958. _this._engine = scene.getEngine();
  75959. _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode, undefined, textureType);
  75960. _this.is3D = true;
  75961. return _this;
  75962. }
  75963. /**
  75964. * Update the texture with new data
  75965. * @param data defines the data to store in the texture
  75966. */
  75967. RawTexture3D.prototype.update = function (data) {
  75968. if (!this._texture) {
  75969. return;
  75970. }
  75971. this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  75972. };
  75973. return RawTexture3D;
  75974. }(BABYLON.Texture));
  75975. BABYLON.RawTexture3D = RawTexture3D;
  75976. })(BABYLON || (BABYLON = {}));
  75977. //# sourceMappingURL=babylon.rawTexture3D.js.map
  75978. var BABYLON;
  75979. (function (BABYLON) {
  75980. /**
  75981. * PostProcessManager is used to manage one or more post processes or post process pipelines
  75982. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  75983. */
  75984. var PostProcessManager = /** @class */ (function () {
  75985. /**
  75986. * Creates a new instance PostProcess
  75987. * @param scene The scene that the post process is associated with.
  75988. */
  75989. function PostProcessManager(scene) {
  75990. this._vertexBuffers = {};
  75991. this._scene = scene;
  75992. }
  75993. PostProcessManager.prototype._prepareBuffers = function () {
  75994. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  75995. return;
  75996. }
  75997. // VBO
  75998. var vertices = [];
  75999. vertices.push(1, 1);
  76000. vertices.push(-1, 1);
  76001. vertices.push(-1, -1);
  76002. vertices.push(1, -1);
  76003. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  76004. this._buildIndexBuffer();
  76005. };
  76006. PostProcessManager.prototype._buildIndexBuffer = function () {
  76007. // Indices
  76008. var indices = [];
  76009. indices.push(0);
  76010. indices.push(1);
  76011. indices.push(2);
  76012. indices.push(0);
  76013. indices.push(2);
  76014. indices.push(3);
  76015. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  76016. };
  76017. /**
  76018. * Rebuilds the vertex buffers of the manager.
  76019. * @hidden
  76020. */
  76021. PostProcessManager.prototype._rebuild = function () {
  76022. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  76023. if (!vb) {
  76024. return;
  76025. }
  76026. vb._rebuild();
  76027. this._buildIndexBuffer();
  76028. };
  76029. // Methods
  76030. /**
  76031. * Prepares a frame to be run through a post process.
  76032. * @param sourceTexture The input texture to the post procesess. (default: null)
  76033. * @param postProcesses An array of post processes to be run. (default: null)
  76034. * @returns True if the post processes were able to be run.
  76035. * @hidden
  76036. */
  76037. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  76038. if (sourceTexture === void 0) { sourceTexture = null; }
  76039. if (postProcesses === void 0) { postProcesses = null; }
  76040. var camera = this._scene.activeCamera;
  76041. if (!camera) {
  76042. return false;
  76043. }
  76044. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  76045. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  76046. return false;
  76047. }
  76048. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  76049. return true;
  76050. };
  76051. /**
  76052. * Manually render a set of post processes to a texture.
  76053. * @param postProcesses An array of post processes to be run.
  76054. * @param targetTexture The target texture to render to.
  76055. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  76056. * @param faceIndex defines the face to render to if a cubemap is defined as the target
  76057. * @param lodLevel defines which lod of the texture to render to
  76058. */
  76059. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport, faceIndex, lodLevel) {
  76060. if (targetTexture === void 0) { targetTexture = null; }
  76061. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  76062. if (faceIndex === void 0) { faceIndex = 0; }
  76063. if (lodLevel === void 0) { lodLevel = 0; }
  76064. var engine = this._scene.getEngine();
  76065. for (var index = 0; index < postProcesses.length; index++) {
  76066. if (index < postProcesses.length - 1) {
  76067. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  76068. }
  76069. else {
  76070. if (targetTexture) {
  76071. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport, undefined, lodLevel);
  76072. }
  76073. else {
  76074. engine.restoreDefaultFramebuffer();
  76075. }
  76076. }
  76077. var pp = postProcesses[index];
  76078. var effect = pp.apply();
  76079. if (effect) {
  76080. pp.onBeforeRenderObservable.notifyObservers(effect);
  76081. // VBOs
  76082. this._prepareBuffers();
  76083. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  76084. // Draw order
  76085. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  76086. pp.onAfterRenderObservable.notifyObservers(effect);
  76087. }
  76088. }
  76089. // Restore depth buffer
  76090. engine.setDepthBuffer(true);
  76091. engine.setDepthWrite(true);
  76092. };
  76093. /**
  76094. * Finalize the result of the output of the postprocesses.
  76095. * @param doNotPresent If true the result will not be displayed to the screen.
  76096. * @param targetTexture The target texture to render to.
  76097. * @param faceIndex The index of the face to bind the target texture to.
  76098. * @param postProcesses The array of post processes to render.
  76099. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  76100. * @hidden
  76101. */
  76102. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  76103. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  76104. var camera = this._scene.activeCamera;
  76105. if (!camera) {
  76106. return;
  76107. }
  76108. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  76109. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  76110. return;
  76111. }
  76112. var engine = this._scene.getEngine();
  76113. for (var index = 0, len = postProcesses.length; index < len; index++) {
  76114. var pp = postProcesses[index];
  76115. if (index < len - 1) {
  76116. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  76117. }
  76118. else {
  76119. if (targetTexture) {
  76120. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  76121. pp._outputTexture = targetTexture;
  76122. }
  76123. else {
  76124. engine.restoreDefaultFramebuffer();
  76125. pp._outputTexture = null;
  76126. }
  76127. }
  76128. if (doNotPresent) {
  76129. break;
  76130. }
  76131. var effect = pp.apply();
  76132. if (effect) {
  76133. pp.onBeforeRenderObservable.notifyObservers(effect);
  76134. // VBOs
  76135. this._prepareBuffers();
  76136. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  76137. // Draw order
  76138. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  76139. pp.onAfterRenderObservable.notifyObservers(effect);
  76140. }
  76141. }
  76142. // Restore states
  76143. engine.setDepthBuffer(true);
  76144. engine.setDepthWrite(true);
  76145. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  76146. };
  76147. /**
  76148. * Disposes of the post process manager.
  76149. */
  76150. PostProcessManager.prototype.dispose = function () {
  76151. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  76152. if (buffer) {
  76153. buffer.dispose();
  76154. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  76155. }
  76156. if (this._indexBuffer) {
  76157. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  76158. this._indexBuffer = null;
  76159. }
  76160. };
  76161. return PostProcessManager;
  76162. }());
  76163. BABYLON.PostProcessManager = PostProcessManager;
  76164. })(BABYLON || (BABYLON = {}));
  76165. //# sourceMappingURL=babylon.postProcessManager.js.map
  76166. var BABYLON;
  76167. (function (BABYLON) {
  76168. /**
  76169. * PostProcess can be used to apply a shader to a texture after it has been rendered
  76170. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  76171. */
  76172. var PostProcess = /** @class */ (function () {
  76173. /**
  76174. * Creates a new instance PostProcess
  76175. * @param name The name of the PostProcess.
  76176. * @param fragmentUrl The url of the fragment shader to be used.
  76177. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  76178. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  76179. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  76180. * @param camera The camera to apply the render pass to.
  76181. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  76182. * @param engine The engine which the post process will be applied. (default: current engine)
  76183. * @param reusable If the post process can be reused on the same frame. (default: false)
  76184. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  76185. * @param textureType Type of textures used when performing the post process. (default: 0)
  76186. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  76187. * @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
  76188. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  76189. */
  76190. function PostProcess(
  76191. /** Name of the PostProcess. */
  76192. name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  76193. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  76194. if (defines === void 0) { defines = null; }
  76195. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76196. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  76197. if (blockCompilation === void 0) { blockCompilation = false; }
  76198. this.name = name;
  76199. /**
  76200. * Width of the texture to apply the post process on
  76201. */
  76202. this.width = -1;
  76203. /**
  76204. * Height of the texture to apply the post process on
  76205. */
  76206. this.height = -1;
  76207. /**
  76208. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  76209. * @hidden
  76210. */
  76211. this._outputTexture = null;
  76212. /**
  76213. * If the buffer needs to be cleared before applying the post process. (default: true)
  76214. * Should be set to false if shader will overwrite all previous pixels.
  76215. */
  76216. this.autoClear = true;
  76217. /**
  76218. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  76219. */
  76220. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  76221. /**
  76222. * Animations to be used for the post processing
  76223. */
  76224. this.animations = new Array();
  76225. /**
  76226. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  76227. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  76228. */
  76229. this.enablePixelPerfectMode = false;
  76230. /**
  76231. * Force the postprocess to be applied without taking in account viewport
  76232. */
  76233. this.forceFullscreenViewport = true;
  76234. /**
  76235. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  76236. *
  76237. * | Value | Type | Description |
  76238. * | ----- | ----------------------------------- | ----------- |
  76239. * | 1 | SCALEMODE_FLOOR | [engine.scalemode_floor](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_floor) |
  76240. * | 2 | SCALEMODE_NEAREST | [engine.scalemode_nearest](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_nearest) |
  76241. * | 3 | SCALEMODE_CEILING | [engine.scalemode_ceiling](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_ceiling) |
  76242. *
  76243. */
  76244. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  76245. /**
  76246. * Force textures to be a power of two (default: false)
  76247. */
  76248. this.alwaysForcePOT = false;
  76249. this._samples = 1;
  76250. /**
  76251. * Modify the scale of the post process to be the same as the viewport (default: false)
  76252. */
  76253. this.adaptScaleToCurrentViewport = false;
  76254. this._reusable = false;
  76255. /**
  76256. * Smart array of input and output textures for the post process.
  76257. * @hidden
  76258. */
  76259. this._textures = new BABYLON.SmartArray(2);
  76260. /**
  76261. * The index in _textures that corresponds to the output texture.
  76262. * @hidden
  76263. */
  76264. this._currentRenderTextureInd = 0;
  76265. this._scaleRatio = new BABYLON.Vector2(1, 1);
  76266. this._texelSize = BABYLON.Vector2.Zero();
  76267. // Events
  76268. /**
  76269. * An event triggered when the postprocess is activated.
  76270. */
  76271. this.onActivateObservable = new BABYLON.Observable();
  76272. /**
  76273. * An event triggered when the postprocess changes its size.
  76274. */
  76275. this.onSizeChangedObservable = new BABYLON.Observable();
  76276. /**
  76277. * An event triggered when the postprocess applies its effect.
  76278. */
  76279. this.onApplyObservable = new BABYLON.Observable();
  76280. /**
  76281. * An event triggered before rendering the postprocess
  76282. */
  76283. this.onBeforeRenderObservable = new BABYLON.Observable();
  76284. /**
  76285. * An event triggered after rendering the postprocess
  76286. */
  76287. this.onAfterRenderObservable = new BABYLON.Observable();
  76288. if (camera != null) {
  76289. this._camera = camera;
  76290. this._scene = camera.getScene();
  76291. camera.attachPostProcess(this);
  76292. this._engine = this._scene.getEngine();
  76293. this._scene.postProcesses.push(this);
  76294. }
  76295. else if (engine) {
  76296. this._engine = engine;
  76297. this._engine.postProcesses.push(this);
  76298. }
  76299. this._options = options;
  76300. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  76301. this._reusable = reusable || false;
  76302. this._textureType = textureType;
  76303. this._samplers = samplers || [];
  76304. this._samplers.push("textureSampler");
  76305. this._fragmentUrl = fragmentUrl;
  76306. this._vertexUrl = vertexUrl;
  76307. this._parameters = parameters || [];
  76308. this._parameters.push("scale");
  76309. this._indexParameters = indexParameters;
  76310. if (!blockCompilation) {
  76311. this.updateEffect(defines);
  76312. }
  76313. }
  76314. Object.defineProperty(PostProcess.prototype, "samples", {
  76315. /**
  76316. * Number of sample textures (default: 1)
  76317. */
  76318. get: function () {
  76319. return this._samples;
  76320. },
  76321. set: function (n) {
  76322. var _this = this;
  76323. this._samples = n;
  76324. this._textures.forEach(function (texture) {
  76325. if (texture.samples !== _this._samples) {
  76326. _this._engine.updateRenderTargetTextureSampleCount(texture, _this._samples);
  76327. }
  76328. });
  76329. },
  76330. enumerable: true,
  76331. configurable: true
  76332. });
  76333. Object.defineProperty(PostProcess.prototype, "onActivate", {
  76334. /**
  76335. * A function that is added to the onActivateObservable
  76336. */
  76337. set: function (callback) {
  76338. if (this._onActivateObserver) {
  76339. this.onActivateObservable.remove(this._onActivateObserver);
  76340. }
  76341. if (callback) {
  76342. this._onActivateObserver = this.onActivateObservable.add(callback);
  76343. }
  76344. },
  76345. enumerable: true,
  76346. configurable: true
  76347. });
  76348. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  76349. /**
  76350. * A function that is added to the onSizeChangedObservable
  76351. */
  76352. set: function (callback) {
  76353. if (this._onSizeChangedObserver) {
  76354. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  76355. }
  76356. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  76357. },
  76358. enumerable: true,
  76359. configurable: true
  76360. });
  76361. Object.defineProperty(PostProcess.prototype, "onApply", {
  76362. /**
  76363. * A function that is added to the onApplyObservable
  76364. */
  76365. set: function (callback) {
  76366. if (this._onApplyObserver) {
  76367. this.onApplyObservable.remove(this._onApplyObserver);
  76368. }
  76369. this._onApplyObserver = this.onApplyObservable.add(callback);
  76370. },
  76371. enumerable: true,
  76372. configurable: true
  76373. });
  76374. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  76375. /**
  76376. * A function that is added to the onBeforeRenderObservable
  76377. */
  76378. set: function (callback) {
  76379. if (this._onBeforeRenderObserver) {
  76380. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  76381. }
  76382. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  76383. },
  76384. enumerable: true,
  76385. configurable: true
  76386. });
  76387. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  76388. /**
  76389. * A function that is added to the onAfterRenderObservable
  76390. */
  76391. set: function (callback) {
  76392. if (this._onAfterRenderObserver) {
  76393. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  76394. }
  76395. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  76396. },
  76397. enumerable: true,
  76398. configurable: true
  76399. });
  76400. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  76401. /**
  76402. * 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
  76403. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  76404. */
  76405. get: function () {
  76406. return this._textures.data[this._currentRenderTextureInd];
  76407. },
  76408. set: function (value) {
  76409. this._forcedOutputTexture = value;
  76410. },
  76411. enumerable: true,
  76412. configurable: true
  76413. });
  76414. /**
  76415. * Gets the camera which post process is applied to.
  76416. * @returns The camera the post process is applied to.
  76417. */
  76418. PostProcess.prototype.getCamera = function () {
  76419. return this._camera;
  76420. };
  76421. Object.defineProperty(PostProcess.prototype, "texelSize", {
  76422. /**
  76423. * Gets the texel size of the postprocess.
  76424. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  76425. */
  76426. get: function () {
  76427. if (this._shareOutputWithPostProcess) {
  76428. return this._shareOutputWithPostProcess.texelSize;
  76429. }
  76430. if (this._forcedOutputTexture) {
  76431. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  76432. }
  76433. return this._texelSize;
  76434. },
  76435. enumerable: true,
  76436. configurable: true
  76437. });
  76438. /**
  76439. * Gets the engine which this post process belongs to.
  76440. * @returns The engine the post process was enabled with.
  76441. */
  76442. PostProcess.prototype.getEngine = function () {
  76443. return this._engine;
  76444. };
  76445. /**
  76446. * The effect that is created when initializing the post process.
  76447. * @returns The created effect corrisponding the the postprocess.
  76448. */
  76449. PostProcess.prototype.getEffect = function () {
  76450. return this._effect;
  76451. };
  76452. /**
  76453. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  76454. * @param postProcess The post process to share the output with.
  76455. * @returns This post process.
  76456. */
  76457. PostProcess.prototype.shareOutputWith = function (postProcess) {
  76458. this._disposeTextures();
  76459. this._shareOutputWithPostProcess = postProcess;
  76460. return this;
  76461. };
  76462. /**
  76463. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  76464. * This should be called if the post process that shares output with this post process is disabled/disposed.
  76465. */
  76466. PostProcess.prototype.useOwnOutput = function () {
  76467. if (this._textures.length == 0) {
  76468. this._textures = new BABYLON.SmartArray(2);
  76469. }
  76470. this._shareOutputWithPostProcess = null;
  76471. };
  76472. /**
  76473. * Updates the effect with the current post process compile time values and recompiles the shader.
  76474. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  76475. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  76476. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  76477. * @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
  76478. * @param onCompiled Called when the shader has been compiled.
  76479. * @param onError Called if there is an error when compiling a shader.
  76480. */
  76481. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  76482. if (defines === void 0) { defines = null; }
  76483. if (uniforms === void 0) { uniforms = null; }
  76484. if (samplers === void 0) { samplers = null; }
  76485. 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);
  76486. };
  76487. /**
  76488. * The post process is reusable if it can be used multiple times within one frame.
  76489. * @returns If the post process is reusable
  76490. */
  76491. PostProcess.prototype.isReusable = function () {
  76492. return this._reusable;
  76493. };
  76494. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  76495. PostProcess.prototype.markTextureDirty = function () {
  76496. this.width = -1;
  76497. };
  76498. /**
  76499. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  76500. * 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.
  76501. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  76502. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  76503. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  76504. * @returns The target texture that was bound to be written to.
  76505. */
  76506. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  76507. var _this = this;
  76508. if (sourceTexture === void 0) { sourceTexture = null; }
  76509. camera = camera || this._camera;
  76510. var scene = camera.getScene();
  76511. var engine = scene.getEngine();
  76512. var maxSize = engine.getCaps().maxTextureSize;
  76513. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  76514. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  76515. // 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
  76516. var webVRCamera = camera.parent;
  76517. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  76518. requiredWidth /= 2;
  76519. }
  76520. var desiredWidth = (this._options.width || requiredWidth);
  76521. var desiredHeight = this._options.height || requiredHeight;
  76522. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  76523. if (this.adaptScaleToCurrentViewport) {
  76524. var currentViewport = engine.currentViewport;
  76525. if (currentViewport) {
  76526. desiredWidth *= currentViewport.width;
  76527. desiredHeight *= currentViewport.height;
  76528. }
  76529. }
  76530. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  76531. if (!this._options.width) {
  76532. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  76533. }
  76534. if (!this._options.height) {
  76535. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  76536. }
  76537. }
  76538. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  76539. if (this._textures.length > 0) {
  76540. for (var i = 0; i < this._textures.length; i++) {
  76541. this._engine._releaseTexture(this._textures.data[i]);
  76542. }
  76543. this._textures.reset();
  76544. }
  76545. this.width = desiredWidth;
  76546. this.height = desiredHeight;
  76547. var textureSize = { width: this.width, height: this.height };
  76548. var textureOptions = {
  76549. generateMipMaps: false,
  76550. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  76551. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  76552. samplingMode: this.renderTargetSamplingMode,
  76553. type: this._textureType
  76554. };
  76555. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  76556. if (this._reusable) {
  76557. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  76558. }
  76559. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  76560. this.onSizeChangedObservable.notifyObservers(this);
  76561. }
  76562. this._textures.forEach(function (texture) {
  76563. if (texture.samples !== _this.samples) {
  76564. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  76565. }
  76566. });
  76567. }
  76568. var target;
  76569. if (this._shareOutputWithPostProcess) {
  76570. target = this._shareOutputWithPostProcess.inputTexture;
  76571. }
  76572. else if (this._forcedOutputTexture) {
  76573. target = this._forcedOutputTexture;
  76574. this.width = this._forcedOutputTexture.width;
  76575. this.height = this._forcedOutputTexture.height;
  76576. }
  76577. else {
  76578. target = this.inputTexture;
  76579. }
  76580. // Bind the input of this post process to be used as the output of the previous post process.
  76581. if (this.enablePixelPerfectMode) {
  76582. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  76583. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, this.forceFullscreenViewport);
  76584. }
  76585. else {
  76586. this._scaleRatio.copyFromFloats(1, 1);
  76587. this._engine.bindFramebuffer(target, 0, undefined, undefined, this.forceFullscreenViewport);
  76588. }
  76589. this.onActivateObservable.notifyObservers(camera);
  76590. // Clear
  76591. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  76592. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, scene._allowPostProcessClearColor, true, true);
  76593. }
  76594. if (this._reusable) {
  76595. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  76596. }
  76597. return target;
  76598. };
  76599. Object.defineProperty(PostProcess.prototype, "isSupported", {
  76600. /**
  76601. * If the post process is supported.
  76602. */
  76603. get: function () {
  76604. return this._effect.isSupported;
  76605. },
  76606. enumerable: true,
  76607. configurable: true
  76608. });
  76609. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  76610. /**
  76611. * The aspect ratio of the output texture.
  76612. */
  76613. get: function () {
  76614. if (this._shareOutputWithPostProcess) {
  76615. return this._shareOutputWithPostProcess.aspectRatio;
  76616. }
  76617. if (this._forcedOutputTexture) {
  76618. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  76619. }
  76620. return this.width / this.height;
  76621. },
  76622. enumerable: true,
  76623. configurable: true
  76624. });
  76625. /**
  76626. * Get a value indicating if the post-process is ready to be used
  76627. * @returns true if the post-process is ready (shader is compiled)
  76628. */
  76629. PostProcess.prototype.isReady = function () {
  76630. return this._effect && this._effect.isReady();
  76631. };
  76632. /**
  76633. * Binds all textures and uniforms to the shader, this will be run on every pass.
  76634. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  76635. */
  76636. PostProcess.prototype.apply = function () {
  76637. // Check
  76638. if (!this._effect || !this._effect.isReady()) {
  76639. return null;
  76640. }
  76641. // States
  76642. this._engine.enableEffect(this._effect);
  76643. this._engine.setState(false);
  76644. this._engine.setDepthBuffer(false);
  76645. this._engine.setDepthWrite(false);
  76646. // Alpha
  76647. this._engine.setAlphaMode(this.alphaMode);
  76648. if (this.alphaConstants) {
  76649. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  76650. }
  76651. // Bind the output texture of the preivous post process as the input to this post process.
  76652. var source;
  76653. if (this._shareOutputWithPostProcess) {
  76654. source = this._shareOutputWithPostProcess.inputTexture;
  76655. }
  76656. else if (this._forcedOutputTexture) {
  76657. source = this._forcedOutputTexture;
  76658. }
  76659. else {
  76660. source = this.inputTexture;
  76661. }
  76662. this._effect._bindTexture("textureSampler", source);
  76663. // Parameters
  76664. this._effect.setVector2("scale", this._scaleRatio);
  76665. this.onApplyObservable.notifyObservers(this._effect);
  76666. return this._effect;
  76667. };
  76668. PostProcess.prototype._disposeTextures = function () {
  76669. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  76670. return;
  76671. }
  76672. if (this._textures.length > 0) {
  76673. for (var i = 0; i < this._textures.length; i++) {
  76674. this._engine._releaseTexture(this._textures.data[i]);
  76675. }
  76676. }
  76677. this._textures.dispose();
  76678. };
  76679. /**
  76680. * Disposes the post process.
  76681. * @param camera The camera to dispose the post process on.
  76682. */
  76683. PostProcess.prototype.dispose = function (camera) {
  76684. camera = camera || this._camera;
  76685. this._disposeTextures();
  76686. if (this._scene) {
  76687. var index_1 = this._scene.postProcesses.indexOf(this);
  76688. if (index_1 !== -1) {
  76689. this._scene.postProcesses.splice(index_1, 1);
  76690. }
  76691. }
  76692. else {
  76693. var index_2 = this._engine.postProcesses.indexOf(this);
  76694. if (index_2 !== -1) {
  76695. this._engine.postProcesses.splice(index_2, 1);
  76696. }
  76697. }
  76698. if (!camera) {
  76699. return;
  76700. }
  76701. camera.detachPostProcess(this);
  76702. var index = camera._postProcesses.indexOf(this);
  76703. if (index === 0 && camera._postProcesses.length > 0) {
  76704. var firstPostProcess = this._camera._getFirstPostProcess();
  76705. if (firstPostProcess) {
  76706. firstPostProcess.markTextureDirty();
  76707. }
  76708. }
  76709. this.onActivateObservable.clear();
  76710. this.onAfterRenderObservable.clear();
  76711. this.onApplyObservable.clear();
  76712. this.onBeforeRenderObservable.clear();
  76713. this.onSizeChangedObservable.clear();
  76714. };
  76715. return PostProcess;
  76716. }());
  76717. BABYLON.PostProcess = PostProcess;
  76718. })(BABYLON || (BABYLON = {}));
  76719. //# sourceMappingURL=babylon.postProcess.js.map
  76720. var BABYLON;
  76721. (function (BABYLON) {
  76722. /**
  76723. * PassPostProcess which produces an output the same as it's input
  76724. */
  76725. var PassPostProcess = /** @class */ (function (_super) {
  76726. __extends(PassPostProcess, _super);
  76727. /**
  76728. * Creates the PassPostProcess
  76729. * @param name The name of the effect.
  76730. * @param options The required width/height ratio to downsize to before computing the render pass.
  76731. * @param camera The camera to apply the render pass to.
  76732. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  76733. * @param engine The engine which the post process will be applied. (default: current engine)
  76734. * @param reusable If the post process can be reused on the same frame. (default: false)
  76735. * @param textureType The type of texture to be used when performing the post processing.
  76736. * @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)
  76737. */
  76738. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  76739. if (camera === void 0) { camera = null; }
  76740. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76741. if (blockCompilation === void 0) { blockCompilation = false; }
  76742. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  76743. }
  76744. return PassPostProcess;
  76745. }(BABYLON.PostProcess));
  76746. BABYLON.PassPostProcess = PassPostProcess;
  76747. /**
  76748. * PassCubePostProcess which produces an output the same as it's input (which must be a cube texture)
  76749. */
  76750. var PassCubePostProcess = /** @class */ (function (_super) {
  76751. __extends(PassCubePostProcess, _super);
  76752. /**
  76753. * Creates the PassCubePostProcess
  76754. * @param name The name of the effect.
  76755. * @param options The required width/height ratio to downsize to before computing the render pass.
  76756. * @param camera The camera to apply the render pass to.
  76757. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  76758. * @param engine The engine which the post process will be applied. (default: current engine)
  76759. * @param reusable If the post process can be reused on the same frame. (default: false)
  76760. * @param textureType The type of texture to be used when performing the post processing.
  76761. * @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)
  76762. */
  76763. function PassCubePostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  76764. if (camera === void 0) { camera = null; }
  76765. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76766. if (blockCompilation === void 0) { blockCompilation = false; }
  76767. var _this = _super.call(this, name, "passCube", null, null, options, camera, samplingMode, engine, reusable, "#define POSITIVEX", textureType, undefined, null, blockCompilation) || this;
  76768. _this._face = 0;
  76769. return _this;
  76770. }
  76771. Object.defineProperty(PassCubePostProcess.prototype, "face", {
  76772. /**
  76773. * Gets or sets the cube face to display.
  76774. * * 0 is +X
  76775. * * 1 is -X
  76776. * * 2 is +Y
  76777. * * 3 is -Y
  76778. * * 4 is +Z
  76779. * * 5 is -Z
  76780. */
  76781. get: function () {
  76782. return this._face;
  76783. },
  76784. set: function (value) {
  76785. if (value < 0 || value > 5) {
  76786. return;
  76787. }
  76788. this._face = value;
  76789. switch (this._face) {
  76790. case 0:
  76791. this.updateEffect("#define POSITIVEX");
  76792. break;
  76793. case 1:
  76794. this.updateEffect("#define NEGATIVEX");
  76795. break;
  76796. case 2:
  76797. this.updateEffect("#define POSITIVEY");
  76798. break;
  76799. case 3:
  76800. this.updateEffect("#define NEGATIVEY");
  76801. break;
  76802. case 4:
  76803. this.updateEffect("#define POSITIVEZ");
  76804. break;
  76805. case 5:
  76806. this.updateEffect("#define NEGATIVEZ");
  76807. break;
  76808. }
  76809. },
  76810. enumerable: true,
  76811. configurable: true
  76812. });
  76813. return PassCubePostProcess;
  76814. }(BABYLON.PostProcess));
  76815. BABYLON.PassCubePostProcess = PassCubePostProcess;
  76816. })(BABYLON || (BABYLON = {}));
  76817. //# sourceMappingURL=babylon.passPostProcess.js.map
  76818. var __assign = (this && this.__assign) || function () {
  76819. __assign = Object.assign || function(t) {
  76820. for (var s, i = 1, n = arguments.length; i < n; i++) {
  76821. s = arguments[i];
  76822. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  76823. t[p] = s[p];
  76824. }
  76825. return t;
  76826. };
  76827. return __assign.apply(this, arguments);
  76828. };
  76829. var BABYLON;
  76830. (function (BABYLON) {
  76831. /**
  76832. * Default implementation IShadowGenerator.
  76833. * This is the main object responsible of generating shadows in the framework.
  76834. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  76835. */
  76836. var ShadowGenerator = /** @class */ (function () {
  76837. /**
  76838. * Creates a ShadowGenerator object.
  76839. * A ShadowGenerator is the required tool to use the shadows.
  76840. * Each light casting shadows needs to use its own ShadowGenerator.
  76841. * Documentation : https://doc.babylonjs.com/babylon101/shadows
  76842. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  76843. * @param light The light object generating the shadows.
  76844. * @param usefulFloatFirst 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.
  76845. */
  76846. function ShadowGenerator(mapSize, light, usefulFloatFirst) {
  76847. this._bias = 0.00005;
  76848. this._normalBias = 0;
  76849. this._blurBoxOffset = 1;
  76850. this._blurScale = 2;
  76851. this._blurKernel = 1;
  76852. this._useKernelBlur = false;
  76853. this._filter = ShadowGenerator.FILTER_NONE;
  76854. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  76855. this._contactHardeningLightSizeUVRatio = 0.1;
  76856. this._darkness = 0;
  76857. this._transparencyShadow = false;
  76858. /**
  76859. * Controls the extent to which the shadows fade out at the edge of the frustum
  76860. * Used only by directionals and spots
  76861. */
  76862. this.frustumEdgeFalloff = 0;
  76863. /**
  76864. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  76865. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  76866. * It might on the other hand introduce peter panning.
  76867. */
  76868. this.forceBackFacesOnly = false;
  76869. this._lightDirection = BABYLON.Vector3.Zero();
  76870. this._viewMatrix = BABYLON.Matrix.Zero();
  76871. this._projectionMatrix = BABYLON.Matrix.Zero();
  76872. this._transformMatrix = BABYLON.Matrix.Zero();
  76873. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  76874. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  76875. this._currentFaceIndex = 0;
  76876. this._currentFaceIndexCache = 0;
  76877. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  76878. this._mapSize = mapSize;
  76879. this._light = light;
  76880. this._scene = light.getScene();
  76881. light._shadowGenerator = this;
  76882. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_SHADOWGENERATOR);
  76883. if (!component) {
  76884. component = new BABYLON.ShadowGeneratorSceneComponent(this._scene);
  76885. this._scene._addComponent(component);
  76886. }
  76887. // Texture type fallback from float to int if not supported.
  76888. var caps = this._scene.getEngine().getCaps();
  76889. if (!usefulFloatFirst) {
  76890. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  76891. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  76892. }
  76893. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  76894. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  76895. }
  76896. else {
  76897. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  76898. }
  76899. }
  76900. else {
  76901. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  76902. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  76903. }
  76904. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  76905. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  76906. }
  76907. else {
  76908. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  76909. }
  76910. }
  76911. this._initializeGenerator();
  76912. this._applyFilterValues();
  76913. }
  76914. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  76915. /**
  76916. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  76917. */
  76918. get: function () {
  76919. return this._bias;
  76920. },
  76921. /**
  76922. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  76923. */
  76924. set: function (bias) {
  76925. this._bias = bias;
  76926. },
  76927. enumerable: true,
  76928. configurable: true
  76929. });
  76930. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  76931. /**
  76932. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  76933. */
  76934. get: function () {
  76935. return this._normalBias;
  76936. },
  76937. /**
  76938. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  76939. */
  76940. set: function (normalBias) {
  76941. this._normalBias = normalBias;
  76942. },
  76943. enumerable: true,
  76944. configurable: true
  76945. });
  76946. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  76947. /**
  76948. * Gets the blur box offset: offset applied during the blur pass.
  76949. * Only useful if useKernelBlur = false
  76950. */
  76951. get: function () {
  76952. return this._blurBoxOffset;
  76953. },
  76954. /**
  76955. * Sets the blur box offset: offset applied during the blur pass.
  76956. * Only useful if useKernelBlur = false
  76957. */
  76958. set: function (value) {
  76959. if (this._blurBoxOffset === value) {
  76960. return;
  76961. }
  76962. this._blurBoxOffset = value;
  76963. this._disposeBlurPostProcesses();
  76964. },
  76965. enumerable: true,
  76966. configurable: true
  76967. });
  76968. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  76969. /**
  76970. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  76971. * 2 means half of the size.
  76972. */
  76973. get: function () {
  76974. return this._blurScale;
  76975. },
  76976. /**
  76977. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  76978. * 2 means half of the size.
  76979. */
  76980. set: function (value) {
  76981. if (this._blurScale === value) {
  76982. return;
  76983. }
  76984. this._blurScale = value;
  76985. this._disposeBlurPostProcesses();
  76986. },
  76987. enumerable: true,
  76988. configurable: true
  76989. });
  76990. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  76991. /**
  76992. * Gets the blur kernel: kernel size of the blur pass.
  76993. * Only useful if useKernelBlur = true
  76994. */
  76995. get: function () {
  76996. return this._blurKernel;
  76997. },
  76998. /**
  76999. * Sets the blur kernel: kernel size of the blur pass.
  77000. * Only useful if useKernelBlur = true
  77001. */
  77002. set: function (value) {
  77003. if (this._blurKernel === value) {
  77004. return;
  77005. }
  77006. this._blurKernel = value;
  77007. this._disposeBlurPostProcesses();
  77008. },
  77009. enumerable: true,
  77010. configurable: true
  77011. });
  77012. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  77013. /**
  77014. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  77015. * Only useful in filtered mode (useBlurExponentialShadowMap...)
  77016. */
  77017. get: function () {
  77018. return this._useKernelBlur;
  77019. },
  77020. /**
  77021. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  77022. * Only useful in filtered mode (useBlurExponentialShadowMap...)
  77023. */
  77024. set: function (value) {
  77025. if (this._useKernelBlur === value) {
  77026. return;
  77027. }
  77028. this._useKernelBlur = value;
  77029. this._disposeBlurPostProcesses();
  77030. },
  77031. enumerable: true,
  77032. configurable: true
  77033. });
  77034. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  77035. /**
  77036. * Gets the depth scale used in ESM mode.
  77037. */
  77038. get: function () {
  77039. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  77040. },
  77041. /**
  77042. * Sets the depth scale used in ESM mode.
  77043. * This can override the scale stored on the light.
  77044. */
  77045. set: function (value) {
  77046. this._depthScale = value;
  77047. },
  77048. enumerable: true,
  77049. configurable: true
  77050. });
  77051. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  77052. /**
  77053. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  77054. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  77055. */
  77056. get: function () {
  77057. return this._filter;
  77058. },
  77059. /**
  77060. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  77061. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  77062. */
  77063. set: function (value) {
  77064. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  77065. if (this._light.needCube()) {
  77066. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  77067. this.useExponentialShadowMap = true;
  77068. return;
  77069. }
  77070. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  77071. this.useCloseExponentialShadowMap = true;
  77072. return;
  77073. }
  77074. // PCF on cubemap would also be expensive
  77075. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  77076. this.usePoissonSampling = true;
  77077. return;
  77078. }
  77079. }
  77080. // Weblg1 fallback for PCF.
  77081. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  77082. if (this._scene.getEngine().webGLVersion === 1) {
  77083. this.usePoissonSampling = true;
  77084. return;
  77085. }
  77086. }
  77087. if (this._filter === value) {
  77088. return;
  77089. }
  77090. this._filter = value;
  77091. this._disposeBlurPostProcesses();
  77092. this._applyFilterValues();
  77093. this._light._markMeshesAsLightDirty();
  77094. },
  77095. enumerable: true,
  77096. configurable: true
  77097. });
  77098. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  77099. /**
  77100. * Gets if the current filter is set to Poisson Sampling.
  77101. */
  77102. get: function () {
  77103. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  77104. },
  77105. /**
  77106. * Sets the current filter to Poisson Sampling.
  77107. */
  77108. set: function (value) {
  77109. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  77110. return;
  77111. }
  77112. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  77113. },
  77114. enumerable: true,
  77115. configurable: true
  77116. });
  77117. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  77118. /**
  77119. * Gets if the current filter is set to ESM.
  77120. */
  77121. get: function () {
  77122. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  77123. },
  77124. /**
  77125. * Sets the current filter is to ESM.
  77126. */
  77127. set: function (value) {
  77128. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  77129. return;
  77130. }
  77131. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  77132. },
  77133. enumerable: true,
  77134. configurable: true
  77135. });
  77136. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  77137. /**
  77138. * Gets if the current filter is set to filtered ESM.
  77139. */
  77140. get: function () {
  77141. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  77142. },
  77143. /**
  77144. * Gets if the current filter is set to filtered ESM.
  77145. */
  77146. set: function (value) {
  77147. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  77148. return;
  77149. }
  77150. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  77151. },
  77152. enumerable: true,
  77153. configurable: true
  77154. });
  77155. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  77156. /**
  77157. * Gets if the current filter is set to "close ESM" (using the inverse of the
  77158. * exponential to prevent steep falloff artifacts).
  77159. */
  77160. get: function () {
  77161. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  77162. },
  77163. /**
  77164. * Sets the current filter to "close ESM" (using the inverse of the
  77165. * exponential to prevent steep falloff artifacts).
  77166. */
  77167. set: function (value) {
  77168. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  77169. return;
  77170. }
  77171. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  77172. },
  77173. enumerable: true,
  77174. configurable: true
  77175. });
  77176. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  77177. /**
  77178. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  77179. * exponential to prevent steep falloff artifacts).
  77180. */
  77181. get: function () {
  77182. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  77183. },
  77184. /**
  77185. * Sets the current filter to filtered "close ESM" (using the inverse of the
  77186. * exponential to prevent steep falloff artifacts).
  77187. */
  77188. set: function (value) {
  77189. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  77190. return;
  77191. }
  77192. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  77193. },
  77194. enumerable: true,
  77195. configurable: true
  77196. });
  77197. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  77198. /**
  77199. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  77200. */
  77201. get: function () {
  77202. return this.filter === ShadowGenerator.FILTER_PCF;
  77203. },
  77204. /**
  77205. * Sets the current filter to "PCF" (percentage closer filtering).
  77206. */
  77207. set: function (value) {
  77208. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  77209. return;
  77210. }
  77211. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  77212. },
  77213. enumerable: true,
  77214. configurable: true
  77215. });
  77216. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  77217. /**
  77218. * Gets the PCF or PCSS Quality.
  77219. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  77220. */
  77221. get: function () {
  77222. return this._filteringQuality;
  77223. },
  77224. /**
  77225. * Sets the PCF or PCSS Quality.
  77226. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  77227. */
  77228. set: function (filteringQuality) {
  77229. this._filteringQuality = filteringQuality;
  77230. },
  77231. enumerable: true,
  77232. configurable: true
  77233. });
  77234. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  77235. /**
  77236. * Gets if the current filter is set to "PCSS" (contact hardening).
  77237. */
  77238. get: function () {
  77239. return this.filter === ShadowGenerator.FILTER_PCSS;
  77240. },
  77241. /**
  77242. * Sets the current filter to "PCSS" (contact hardening).
  77243. */
  77244. set: function (value) {
  77245. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  77246. return;
  77247. }
  77248. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  77249. },
  77250. enumerable: true,
  77251. configurable: true
  77252. });
  77253. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  77254. /**
  77255. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  77256. * Using a ratio helps keeping shape stability independently of the map size.
  77257. *
  77258. * It does not account for the light projection as it was having too much
  77259. * instability during the light setup or during light position changes.
  77260. *
  77261. * Only valid if useContactHardeningShadow is true.
  77262. */
  77263. get: function () {
  77264. return this._contactHardeningLightSizeUVRatio;
  77265. },
  77266. /**
  77267. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  77268. * Using a ratio helps keeping shape stability independently of the map size.
  77269. *
  77270. * It does not account for the light projection as it was having too much
  77271. * instability during the light setup or during light position changes.
  77272. *
  77273. * Only valid if useContactHardeningShadow is true.
  77274. */
  77275. set: function (contactHardeningLightSizeUVRatio) {
  77276. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  77277. },
  77278. enumerable: true,
  77279. configurable: true
  77280. });
  77281. /**
  77282. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  77283. * 0 means strongest and 1 would means no shadow.
  77284. * @returns the darkness.
  77285. */
  77286. ShadowGenerator.prototype.getDarkness = function () {
  77287. return this._darkness;
  77288. };
  77289. /**
  77290. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  77291. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  77292. * @returns the shadow generator allowing fluent coding.
  77293. */
  77294. ShadowGenerator.prototype.setDarkness = function (darkness) {
  77295. if (darkness >= 1.0) {
  77296. this._darkness = 1.0;
  77297. }
  77298. else if (darkness <= 0.0) {
  77299. this._darkness = 0.0;
  77300. }
  77301. else {
  77302. this._darkness = darkness;
  77303. }
  77304. return this;
  77305. };
  77306. /**
  77307. * Sets the ability to have transparent shadow (boolean).
  77308. * @param transparent True if transparent else False
  77309. * @returns the shadow generator allowing fluent coding
  77310. */
  77311. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  77312. this._transparencyShadow = transparent;
  77313. return this;
  77314. };
  77315. /**
  77316. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  77317. * @returns The render target texture if present otherwise, null
  77318. */
  77319. ShadowGenerator.prototype.getShadowMap = function () {
  77320. return this._shadowMap;
  77321. };
  77322. /**
  77323. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  77324. * @returns The render target texture if the shadow map is present otherwise, null
  77325. */
  77326. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  77327. if (this._shadowMap2) {
  77328. return this._shadowMap2;
  77329. }
  77330. return this._shadowMap;
  77331. };
  77332. /**
  77333. * Helper function to add a mesh and its descendants to the list of shadow casters.
  77334. * @param mesh Mesh to add
  77335. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  77336. * @returns the Shadow Generator itself
  77337. */
  77338. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  77339. if (includeDescendants === void 0) { includeDescendants = true; }
  77340. var _a;
  77341. if (!this._shadowMap) {
  77342. return this;
  77343. }
  77344. if (!this._shadowMap.renderList) {
  77345. this._shadowMap.renderList = [];
  77346. }
  77347. this._shadowMap.renderList.push(mesh);
  77348. if (includeDescendants) {
  77349. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  77350. }
  77351. return this;
  77352. };
  77353. /**
  77354. * Helper function to remove a mesh and its descendants from the list of shadow casters
  77355. * @param mesh Mesh to remove
  77356. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  77357. * @returns the Shadow Generator itself
  77358. */
  77359. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  77360. if (includeDescendants === void 0) { includeDescendants = true; }
  77361. if (!this._shadowMap || !this._shadowMap.renderList) {
  77362. return this;
  77363. }
  77364. var index = this._shadowMap.renderList.indexOf(mesh);
  77365. if (index !== -1) {
  77366. this._shadowMap.renderList.splice(index, 1);
  77367. }
  77368. if (includeDescendants) {
  77369. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  77370. var child = _a[_i];
  77371. this.removeShadowCaster(child);
  77372. }
  77373. }
  77374. return this;
  77375. };
  77376. /**
  77377. * Returns the associated light object.
  77378. * @returns the light generating the shadow
  77379. */
  77380. ShadowGenerator.prototype.getLight = function () {
  77381. return this._light;
  77382. };
  77383. ShadowGenerator.prototype._initializeGenerator = function () {
  77384. this._light._markMeshesAsLightDirty();
  77385. this._initializeShadowMap();
  77386. };
  77387. ShadowGenerator.prototype._initializeShadowMap = function () {
  77388. var _this = this;
  77389. // Render target
  77390. var engine = this._scene.getEngine();
  77391. if (engine.webGLVersion > 1) {
  77392. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  77393. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  77394. }
  77395. else {
  77396. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  77397. }
  77398. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77399. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77400. this._shadowMap.anisotropicFilteringLevel = 1;
  77401. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  77402. this._shadowMap.renderParticles = false;
  77403. this._shadowMap.ignoreCameraViewport = true;
  77404. // Record Face Index before render.
  77405. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  77406. _this._currentFaceIndex = faceIndex;
  77407. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  77408. engine.setColorWrite(false);
  77409. }
  77410. });
  77411. // Custom render function.
  77412. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  77413. // Blur if required afer render.
  77414. this._shadowMap.onAfterUnbindObservable.add(function () {
  77415. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  77416. engine.setColorWrite(true);
  77417. }
  77418. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  77419. return;
  77420. }
  77421. var shadowMap = _this.getShadowMapForRendering();
  77422. if (shadowMap) {
  77423. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  77424. }
  77425. });
  77426. // Clear according to the chosen filter.
  77427. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  77428. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  77429. this._shadowMap.onClearObservable.add(function (engine) {
  77430. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  77431. engine.clear(clearOne, false, true, false);
  77432. }
  77433. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  77434. engine.clear(clearZero, true, true, false);
  77435. }
  77436. else {
  77437. engine.clear(clearOne, true, true, false);
  77438. }
  77439. });
  77440. };
  77441. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  77442. var _this = this;
  77443. var engine = this._scene.getEngine();
  77444. var targetSize = this._mapSize / this.blurScale;
  77445. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  77446. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  77447. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77448. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77449. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  77450. }
  77451. if (this.useKernelBlur) {
  77452. 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);
  77453. this._kernelBlurXPostprocess.width = targetSize;
  77454. this._kernelBlurXPostprocess.height = targetSize;
  77455. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  77456. effect.setTexture("textureSampler", _this._shadowMap);
  77457. });
  77458. 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);
  77459. this._kernelBlurXPostprocess.autoClear = false;
  77460. this._kernelBlurYPostprocess.autoClear = false;
  77461. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  77462. this._kernelBlurXPostprocess.packedFloat = true;
  77463. this._kernelBlurYPostprocess.packedFloat = true;
  77464. }
  77465. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  77466. }
  77467. else {
  77468. 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);
  77469. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  77470. effect.setFloat2("screenSize", targetSize, targetSize);
  77471. effect.setTexture("textureSampler", _this._shadowMap);
  77472. });
  77473. this._boxBlurPostprocess.autoClear = false;
  77474. this._blurPostProcesses = [this._boxBlurPostprocess];
  77475. }
  77476. };
  77477. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  77478. var index;
  77479. var engine = this._scene.getEngine();
  77480. if (depthOnlySubMeshes.length) {
  77481. engine.setColorWrite(false);
  77482. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  77483. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  77484. }
  77485. engine.setColorWrite(true);
  77486. }
  77487. for (index = 0; index < opaqueSubMeshes.length; index++) {
  77488. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  77489. }
  77490. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  77491. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  77492. }
  77493. if (this._transparencyShadow) {
  77494. for (index = 0; index < transparentSubMeshes.length; index++) {
  77495. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  77496. }
  77497. }
  77498. };
  77499. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  77500. var _this = this;
  77501. var mesh = subMesh.getRenderingMesh();
  77502. var scene = this._scene;
  77503. var engine = scene.getEngine();
  77504. var material = subMesh.getMaterial();
  77505. if (!material || subMesh.verticesCount === 0) {
  77506. return;
  77507. }
  77508. // Culling
  77509. engine.setState(material.backFaceCulling);
  77510. // Managing instances
  77511. var batch = mesh._getInstancesRenderList(subMesh._id);
  77512. if (batch.mustReturn) {
  77513. return;
  77514. }
  77515. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  77516. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  77517. engine.enableEffect(this._effect);
  77518. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  77519. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  77520. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  77521. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  77522. this._effect.setVector3("lightData", this._cachedDirection);
  77523. }
  77524. else {
  77525. this._effect.setVector3("lightData", this._cachedPosition);
  77526. }
  77527. if (scene.activeCamera) {
  77528. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  77529. }
  77530. // Alpha test
  77531. if (material && material.needAlphaTesting()) {
  77532. var alphaTexture = material.getAlphaTestTexture();
  77533. if (alphaTexture) {
  77534. this._effect.setTexture("diffuseSampler", alphaTexture);
  77535. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  77536. }
  77537. }
  77538. // Bones
  77539. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  77540. var skeleton = mesh.skeleton;
  77541. if (skeleton.isUsingTextureForMatrices) {
  77542. var boneTexture = skeleton.getTransformMatrixTexture();
  77543. if (!boneTexture) {
  77544. return;
  77545. }
  77546. this._effect.setTexture("boneSampler", boneTexture);
  77547. this._effect.setFloat("boneTextureWidth", 4.0 * (skeleton.bones.length + 1));
  77548. }
  77549. else {
  77550. this._effect.setMatrices("mBones", skeleton.getTransformMatrices((mesh)));
  77551. }
  77552. }
  77553. // Morph targets
  77554. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  77555. if (this.forceBackFacesOnly) {
  77556. engine.setState(true, 0, false, true);
  77557. }
  77558. // Draw
  77559. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  77560. if (this.forceBackFacesOnly) {
  77561. engine.setState(true, 0, false, false);
  77562. }
  77563. }
  77564. else {
  77565. // Need to reset refresh rate of the shadowMap
  77566. if (this._shadowMap) {
  77567. this._shadowMap.resetRefreshCounter();
  77568. }
  77569. }
  77570. };
  77571. ShadowGenerator.prototype._applyFilterValues = function () {
  77572. if (!this._shadowMap) {
  77573. return;
  77574. }
  77575. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  77576. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  77577. }
  77578. else {
  77579. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  77580. }
  77581. };
  77582. /**
  77583. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  77584. * @param onCompiled Callback triggered at the and of the effects compilation
  77585. * @param options Sets of optional options forcing the compilation with different modes
  77586. */
  77587. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  77588. var _this = this;
  77589. var localOptions = __assign({ useInstances: false }, options);
  77590. var shadowMap = this.getShadowMap();
  77591. if (!shadowMap) {
  77592. if (onCompiled) {
  77593. onCompiled(this);
  77594. }
  77595. return;
  77596. }
  77597. var renderList = shadowMap.renderList;
  77598. if (!renderList) {
  77599. if (onCompiled) {
  77600. onCompiled(this);
  77601. }
  77602. return;
  77603. }
  77604. var subMeshes = new Array();
  77605. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  77606. var mesh = renderList_1[_i];
  77607. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  77608. }
  77609. if (subMeshes.length === 0) {
  77610. if (onCompiled) {
  77611. onCompiled(this);
  77612. }
  77613. return;
  77614. }
  77615. var currentIndex = 0;
  77616. var checkReady = function () {
  77617. if (!_this._scene || !_this._scene.getEngine()) {
  77618. return;
  77619. }
  77620. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  77621. currentIndex++;
  77622. if (currentIndex >= subMeshes.length) {
  77623. if (onCompiled) {
  77624. onCompiled(_this);
  77625. }
  77626. return;
  77627. }
  77628. }
  77629. setTimeout(checkReady, 16);
  77630. };
  77631. checkReady();
  77632. };
  77633. /**
  77634. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  77635. * @param options Sets of optional options forcing the compilation with different modes
  77636. * @returns A promise that resolves when the compilation completes
  77637. */
  77638. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  77639. var _this = this;
  77640. return new Promise(function (resolve) {
  77641. _this.forceCompilation(function () {
  77642. resolve();
  77643. }, options);
  77644. });
  77645. };
  77646. /**
  77647. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  77648. * @param subMesh The submesh we want to render in the shadow map
  77649. * @param useInstances Defines wether will draw in the map using instances
  77650. * @returns true if ready otherwise, false
  77651. */
  77652. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  77653. var defines = [];
  77654. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  77655. defines.push("#define FLOAT");
  77656. }
  77657. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  77658. defines.push("#define ESM");
  77659. }
  77660. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  77661. defines.push("#define DEPTHTEXTURE");
  77662. }
  77663. var attribs = [BABYLON.VertexBuffer.PositionKind];
  77664. var mesh = subMesh.getMesh();
  77665. var material = subMesh.getMaterial();
  77666. // Normal bias.
  77667. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  77668. attribs.push(BABYLON.VertexBuffer.NormalKind);
  77669. defines.push("#define NORMAL");
  77670. if (mesh.nonUniformScaling) {
  77671. defines.push("#define NONUNIFORMSCALING");
  77672. }
  77673. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  77674. defines.push("#define DIRECTIONINLIGHTDATA");
  77675. }
  77676. }
  77677. // Alpha test
  77678. if (material && material.needAlphaTesting()) {
  77679. var alphaTexture = material.getAlphaTestTexture();
  77680. if (alphaTexture) {
  77681. defines.push("#define ALPHATEST");
  77682. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  77683. attribs.push(BABYLON.VertexBuffer.UVKind);
  77684. defines.push("#define UV1");
  77685. }
  77686. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  77687. if (alphaTexture.coordinatesIndex === 1) {
  77688. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  77689. defines.push("#define UV2");
  77690. }
  77691. }
  77692. }
  77693. }
  77694. // Bones
  77695. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  77696. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  77697. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  77698. if (mesh.numBoneInfluencers > 4) {
  77699. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  77700. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  77701. }
  77702. var skeleton = mesh.skeleton;
  77703. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  77704. if (skeleton.isUsingTextureForMatrices) {
  77705. defines.push("#define BONETEXTURE");
  77706. }
  77707. else {
  77708. defines.push("#define BonesPerMesh " + (skeleton.bones.length + 1));
  77709. }
  77710. }
  77711. else {
  77712. defines.push("#define NUM_BONE_INFLUENCERS 0");
  77713. }
  77714. // Morph targets
  77715. var manager = mesh.morphTargetManager;
  77716. var morphInfluencers = 0;
  77717. if (manager) {
  77718. if (manager.numInfluencers > 0) {
  77719. defines.push("#define MORPHTARGETS");
  77720. morphInfluencers = manager.numInfluencers;
  77721. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  77722. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  77723. }
  77724. }
  77725. // Instances
  77726. if (useInstances) {
  77727. defines.push("#define INSTANCES");
  77728. attribs.push("world0");
  77729. attribs.push("world1");
  77730. attribs.push("world2");
  77731. attribs.push("world3");
  77732. }
  77733. // Get correct effect
  77734. var join = defines.join("\n");
  77735. if (this._cachedDefines !== join) {
  77736. this._cachedDefines = join;
  77737. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences", "boneTextureWidth"], ["diffuseSampler", "boneSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  77738. }
  77739. if (!this._effect.isReady()) {
  77740. return false;
  77741. }
  77742. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  77743. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  77744. this._initializeBlurRTTAndPostProcesses();
  77745. }
  77746. }
  77747. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  77748. return false;
  77749. }
  77750. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  77751. return false;
  77752. }
  77753. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  77754. return false;
  77755. }
  77756. return true;
  77757. };
  77758. /**
  77759. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  77760. * @param defines Defines of the material we want to update
  77761. * @param lightIndex Index of the light in the enabled light list of the material
  77762. */
  77763. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  77764. var scene = this._scene;
  77765. var light = this._light;
  77766. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  77767. return;
  77768. }
  77769. defines["SHADOW" + lightIndex] = true;
  77770. if (this.useContactHardeningShadow) {
  77771. defines["SHADOWPCSS" + lightIndex] = true;
  77772. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  77773. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  77774. }
  77775. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  77776. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  77777. }
  77778. // else default to high.
  77779. }
  77780. if (this.usePercentageCloserFiltering) {
  77781. defines["SHADOWPCF" + lightIndex] = true;
  77782. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  77783. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  77784. }
  77785. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  77786. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  77787. }
  77788. // else default to high.
  77789. }
  77790. else if (this.usePoissonSampling) {
  77791. defines["SHADOWPOISSON" + lightIndex] = true;
  77792. }
  77793. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  77794. defines["SHADOWESM" + lightIndex] = true;
  77795. }
  77796. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  77797. defines["SHADOWCLOSEESM" + lightIndex] = true;
  77798. }
  77799. if (light.needCube()) {
  77800. defines["SHADOWCUBE" + lightIndex] = true;
  77801. }
  77802. };
  77803. /**
  77804. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  77805. * defined in the generator but impacting the effect).
  77806. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  77807. * @param effect The effect we are binfing the information for
  77808. */
  77809. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  77810. var light = this._light;
  77811. var scene = this._scene;
  77812. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  77813. return;
  77814. }
  77815. var camera = scene.activeCamera;
  77816. if (!camera) {
  77817. return;
  77818. }
  77819. var shadowMap = this.getShadowMap();
  77820. if (!shadowMap) {
  77821. return;
  77822. }
  77823. if (!light.needCube()) {
  77824. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  77825. }
  77826. // Only PCF uses depth stencil texture.
  77827. if (this._filter === ShadowGenerator.FILTER_PCF) {
  77828. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  77829. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  77830. }
  77831. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  77832. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  77833. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  77834. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  77835. }
  77836. else {
  77837. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  77838. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  77839. }
  77840. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  77841. };
  77842. /**
  77843. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  77844. * (eq to shadow prjection matrix * light transform matrix)
  77845. * @returns The transform matrix used to create the shadow map
  77846. */
  77847. ShadowGenerator.prototype.getTransformMatrix = function () {
  77848. var scene = this._scene;
  77849. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  77850. return this._transformMatrix;
  77851. }
  77852. this._currentRenderID = scene.getRenderId();
  77853. this._currentFaceIndexCache = this._currentFaceIndex;
  77854. var lightPosition = this._light.position;
  77855. if (this._light.computeTransformedInformation()) {
  77856. lightPosition = this._light.transformedPosition;
  77857. }
  77858. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  77859. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  77860. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  77861. }
  77862. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  77863. this._cachedPosition.copyFrom(lightPosition);
  77864. this._cachedDirection.copyFrom(this._lightDirection);
  77865. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  77866. var shadowMap = this.getShadowMap();
  77867. if (shadowMap) {
  77868. var renderList = shadowMap.renderList;
  77869. if (renderList) {
  77870. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  77871. }
  77872. }
  77873. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  77874. }
  77875. return this._transformMatrix;
  77876. };
  77877. /**
  77878. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  77879. * Cube and 2D textures for instance.
  77880. */
  77881. ShadowGenerator.prototype.recreateShadowMap = function () {
  77882. var shadowMap = this._shadowMap;
  77883. if (!shadowMap) {
  77884. return;
  77885. }
  77886. // Track render list.
  77887. var renderList = shadowMap.renderList;
  77888. // Clean up existing data.
  77889. this._disposeRTTandPostProcesses();
  77890. // Reinitializes.
  77891. this._initializeGenerator();
  77892. // Reaffect the filter to ensure a correct fallback if necessary.
  77893. this.filter = this.filter;
  77894. // Reaffect the filter.
  77895. this._applyFilterValues();
  77896. // Reaffect Render List.
  77897. this._shadowMap.renderList = renderList;
  77898. };
  77899. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  77900. if (this._shadowMap2) {
  77901. this._shadowMap2.dispose();
  77902. this._shadowMap2 = null;
  77903. }
  77904. if (this._boxBlurPostprocess) {
  77905. this._boxBlurPostprocess.dispose();
  77906. this._boxBlurPostprocess = null;
  77907. }
  77908. if (this._kernelBlurXPostprocess) {
  77909. this._kernelBlurXPostprocess.dispose();
  77910. this._kernelBlurXPostprocess = null;
  77911. }
  77912. if (this._kernelBlurYPostprocess) {
  77913. this._kernelBlurYPostprocess.dispose();
  77914. this._kernelBlurYPostprocess = null;
  77915. }
  77916. this._blurPostProcesses = [];
  77917. };
  77918. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  77919. if (this._shadowMap) {
  77920. this._shadowMap.dispose();
  77921. this._shadowMap = null;
  77922. }
  77923. this._disposeBlurPostProcesses();
  77924. };
  77925. /**
  77926. * Disposes the ShadowGenerator.
  77927. * Returns nothing.
  77928. */
  77929. ShadowGenerator.prototype.dispose = function () {
  77930. this._disposeRTTandPostProcesses();
  77931. if (this._light) {
  77932. this._light._shadowGenerator = null;
  77933. this._light._markMeshesAsLightDirty();
  77934. }
  77935. };
  77936. /**
  77937. * Serializes the shadow generator setup to a json object.
  77938. * @returns The serialized JSON object
  77939. */
  77940. ShadowGenerator.prototype.serialize = function () {
  77941. var serializationObject = {};
  77942. var shadowMap = this.getShadowMap();
  77943. if (!shadowMap) {
  77944. return serializationObject;
  77945. }
  77946. serializationObject.lightId = this._light.id;
  77947. serializationObject.mapSize = shadowMap.getRenderSize();
  77948. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  77949. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  77950. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  77951. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  77952. serializationObject.usePoissonSampling = this.usePoissonSampling;
  77953. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  77954. serializationObject.depthScale = this.depthScale;
  77955. serializationObject.darkness = this.getDarkness();
  77956. serializationObject.blurBoxOffset = this.blurBoxOffset;
  77957. serializationObject.blurKernel = this.blurKernel;
  77958. serializationObject.blurScale = this.blurScale;
  77959. serializationObject.useKernelBlur = this.useKernelBlur;
  77960. serializationObject.transparencyShadow = this._transparencyShadow;
  77961. serializationObject.frustumEdgeFalloff = this.frustumEdgeFalloff;
  77962. serializationObject.bias = this.bias;
  77963. serializationObject.normalBias = this.normalBias;
  77964. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  77965. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  77966. serializationObject.filteringQuality = this.filteringQuality;
  77967. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  77968. serializationObject.renderList = [];
  77969. if (shadowMap.renderList) {
  77970. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  77971. var mesh = shadowMap.renderList[meshIndex];
  77972. serializationObject.renderList.push(mesh.id);
  77973. }
  77974. }
  77975. return serializationObject;
  77976. };
  77977. /**
  77978. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  77979. * @param parsedShadowGenerator The JSON object to parse
  77980. * @param scene The scene to create the shadow map for
  77981. * @returns The parsed shadow generator
  77982. */
  77983. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  77984. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  77985. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  77986. var shadowMap = shadowGenerator.getShadowMap();
  77987. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  77988. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  77989. meshes.forEach(function (mesh) {
  77990. if (!shadowMap) {
  77991. return;
  77992. }
  77993. if (!shadowMap.renderList) {
  77994. shadowMap.renderList = [];
  77995. }
  77996. shadowMap.renderList.push(mesh);
  77997. });
  77998. }
  77999. if (parsedShadowGenerator.usePoissonSampling) {
  78000. shadowGenerator.usePoissonSampling = true;
  78001. }
  78002. else if (parsedShadowGenerator.useExponentialShadowMap) {
  78003. shadowGenerator.useExponentialShadowMap = true;
  78004. }
  78005. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  78006. shadowGenerator.useBlurExponentialShadowMap = true;
  78007. }
  78008. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  78009. shadowGenerator.useCloseExponentialShadowMap = true;
  78010. }
  78011. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  78012. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  78013. }
  78014. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  78015. shadowGenerator.usePercentageCloserFiltering = true;
  78016. }
  78017. else if (parsedShadowGenerator.useContactHardeningShadow) {
  78018. shadowGenerator.useContactHardeningShadow = true;
  78019. }
  78020. if (parsedShadowGenerator.filteringQuality) {
  78021. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  78022. }
  78023. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  78024. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  78025. }
  78026. // Backward compat
  78027. else if (parsedShadowGenerator.useVarianceShadowMap) {
  78028. shadowGenerator.useExponentialShadowMap = true;
  78029. }
  78030. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  78031. shadowGenerator.useBlurExponentialShadowMap = true;
  78032. }
  78033. if (parsedShadowGenerator.depthScale) {
  78034. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  78035. }
  78036. if (parsedShadowGenerator.blurScale) {
  78037. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  78038. }
  78039. if (parsedShadowGenerator.blurBoxOffset) {
  78040. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  78041. }
  78042. if (parsedShadowGenerator.useKernelBlur) {
  78043. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  78044. }
  78045. if (parsedShadowGenerator.blurKernel) {
  78046. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  78047. }
  78048. if (parsedShadowGenerator.bias !== undefined) {
  78049. shadowGenerator.bias = parsedShadowGenerator.bias;
  78050. }
  78051. if (parsedShadowGenerator.normalBias !== undefined) {
  78052. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  78053. }
  78054. if (parsedShadowGenerator.frustumEdgeFalloff !== undefined) {
  78055. shadowGenerator.frustumEdgeFalloff = parsedShadowGenerator.frustumEdgeFalloff;
  78056. }
  78057. if (parsedShadowGenerator.darkness) {
  78058. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  78059. }
  78060. if (parsedShadowGenerator.transparencyShadow) {
  78061. shadowGenerator.setTransparencyShadow(true);
  78062. }
  78063. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  78064. return shadowGenerator;
  78065. };
  78066. /**
  78067. * Shadow generator mode None: no filtering applied.
  78068. */
  78069. ShadowGenerator.FILTER_NONE = 0;
  78070. /**
  78071. * Shadow generator mode ESM: Exponential Shadow Mapping.
  78072. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  78073. */
  78074. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  78075. /**
  78076. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  78077. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  78078. */
  78079. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  78080. /**
  78081. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  78082. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  78083. */
  78084. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  78085. /**
  78086. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  78087. * edge artifacts on steep falloff.
  78088. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  78089. */
  78090. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  78091. /**
  78092. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  78093. * edge artifacts on steep falloff.
  78094. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  78095. */
  78096. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  78097. /**
  78098. * Shadow generator mode PCF: Percentage Closer Filtering
  78099. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  78100. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  78101. */
  78102. ShadowGenerator.FILTER_PCF = 6;
  78103. /**
  78104. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  78105. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  78106. * Contact Hardening
  78107. */
  78108. ShadowGenerator.FILTER_PCSS = 7;
  78109. /**
  78110. * Reserved for PCF and PCSS
  78111. * Highest Quality.
  78112. *
  78113. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  78114. *
  78115. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  78116. */
  78117. ShadowGenerator.QUALITY_HIGH = 0;
  78118. /**
  78119. * Reserved for PCF and PCSS
  78120. * Good tradeoff for quality/perf cross devices
  78121. *
  78122. * Execute PCF on a 3*3 kernel.
  78123. *
  78124. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  78125. */
  78126. ShadowGenerator.QUALITY_MEDIUM = 1;
  78127. /**
  78128. * Reserved for PCF and PCSS
  78129. * The lowest quality but the fastest.
  78130. *
  78131. * Execute PCF on a 1*1 kernel.
  78132. *
  78133. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  78134. */
  78135. ShadowGenerator.QUALITY_LOW = 2;
  78136. return ShadowGenerator;
  78137. }());
  78138. BABYLON.ShadowGenerator = ShadowGenerator;
  78139. })(BABYLON || (BABYLON = {}));
  78140. //# sourceMappingURL=babylon.shadowGenerator.js.map
  78141. var BABYLON;
  78142. (function (BABYLON) {
  78143. // Adds the parser to the scene parsers.
  78144. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_SHADOWGENERATOR, function (parsedData, scene, container, rootUrl) {
  78145. // Shadows
  78146. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  78147. for (var index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  78148. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  78149. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  78150. // SG would be available on their associated lights
  78151. }
  78152. }
  78153. });
  78154. /**
  78155. * Defines the shadow generator component responsible to manage any shadow generators
  78156. * in a given scene.
  78157. */
  78158. var ShadowGeneratorSceneComponent = /** @class */ (function () {
  78159. /**
  78160. * Creates a new instance of the component for the given scene
  78161. * @param scene Defines the scene to register the component in
  78162. */
  78163. function ShadowGeneratorSceneComponent(scene) {
  78164. /**
  78165. * The component name helpfull to identify the component in the list of scene components.
  78166. */
  78167. this.name = BABYLON.SceneComponentConstants.NAME_SHADOWGENERATOR;
  78168. this.scene = scene;
  78169. }
  78170. /**
  78171. * Registers the component in a given scene
  78172. */
  78173. ShadowGeneratorSceneComponent.prototype.register = function () {
  78174. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR, this, this._gatherRenderTargets);
  78175. };
  78176. /**
  78177. * Rebuilds the elements related to this component in case of
  78178. * context lost for instance.
  78179. */
  78180. ShadowGeneratorSceneComponent.prototype.rebuild = function () {
  78181. // Nothing To Do Here.
  78182. };
  78183. /**
  78184. * Serializes the component data to the specified json object
  78185. * @param serializationObject The object to serialize to
  78186. */
  78187. ShadowGeneratorSceneComponent.prototype.serialize = function (serializationObject) {
  78188. // Shadows
  78189. serializationObject.shadowGenerators = [];
  78190. var lights = this.scene.lights;
  78191. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  78192. var light = lights_1[_i];
  78193. var shadowGenerator = light.getShadowGenerator();
  78194. if (shadowGenerator) {
  78195. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  78196. }
  78197. }
  78198. };
  78199. /**
  78200. * Adds all the element from the container to the scene
  78201. * @param container the container holding the elements
  78202. */
  78203. ShadowGeneratorSceneComponent.prototype.addFromContainer = function (container) {
  78204. // Nothing To Do Here. (directly attached to a light)
  78205. };
  78206. /**
  78207. * Removes all the elements in the container from the scene
  78208. * @param container contains the elements to remove
  78209. */
  78210. ShadowGeneratorSceneComponent.prototype.removeFromContainer = function (container) {
  78211. // Nothing To Do Here. (directly attached to a light)
  78212. };
  78213. /**
  78214. * Rebuilds the elements related to this component in case of
  78215. * context lost for instance.
  78216. */
  78217. ShadowGeneratorSceneComponent.prototype.dispose = function () {
  78218. // Nothing To Do Here.
  78219. };
  78220. ShadowGeneratorSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  78221. // Shadows
  78222. var scene = this.scene;
  78223. if (this.scene.shadowsEnabled) {
  78224. for (var lightIndex = 0; lightIndex < scene.lights.length; lightIndex++) {
  78225. var light = scene.lights[lightIndex];
  78226. var shadowGenerator = light.getShadowGenerator();
  78227. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  78228. var shadowMap = (shadowGenerator.getShadowMap());
  78229. if (scene.textures.indexOf(shadowMap) !== -1) {
  78230. renderTargets.push(shadowMap);
  78231. }
  78232. }
  78233. }
  78234. }
  78235. };
  78236. return ShadowGeneratorSceneComponent;
  78237. }());
  78238. BABYLON.ShadowGeneratorSceneComponent = ShadowGeneratorSceneComponent;
  78239. })(BABYLON || (BABYLON = {}));
  78240. //# sourceMappingURL=babylon.shadowGeneratorSceneComponent.js.map
  78241. var BABYLON;
  78242. (function (BABYLON) {
  78243. /**
  78244. * Class used for the default loading screen
  78245. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  78246. */
  78247. var DefaultLoadingScreen = /** @class */ (function () {
  78248. /**
  78249. * Creates a new default loading screen
  78250. * @param _renderingCanvas defines the canvas used to render the scene
  78251. * @param _loadingText defines the default text to display
  78252. * @param _loadingDivBackgroundColor defines the default background color
  78253. */
  78254. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  78255. if (_loadingText === void 0) { _loadingText = ""; }
  78256. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  78257. var _this = this;
  78258. this._renderingCanvas = _renderingCanvas;
  78259. this._loadingText = _loadingText;
  78260. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  78261. // Resize
  78262. this._resizeLoadingUI = function () {
  78263. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  78264. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  78265. if (!_this._loadingDiv) {
  78266. return;
  78267. }
  78268. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  78269. _this._loadingDiv.style.left = canvasRect.left + "px";
  78270. _this._loadingDiv.style.top = canvasRect.top + "px";
  78271. _this._loadingDiv.style.width = canvasRect.width + "px";
  78272. _this._loadingDiv.style.height = canvasRect.height + "px";
  78273. };
  78274. }
  78275. /**
  78276. * Function called to display the loading screen
  78277. */
  78278. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  78279. if (this._loadingDiv) {
  78280. // Do not add a loading screen if there is already one
  78281. return;
  78282. }
  78283. this._loadingDiv = document.createElement("div");
  78284. this._loadingDiv.id = "babylonjsLoadingDiv";
  78285. this._loadingDiv.style.opacity = "0";
  78286. this._loadingDiv.style.transition = "opacity 1.5s ease";
  78287. this._loadingDiv.style.pointerEvents = "none";
  78288. // Loading text
  78289. this._loadingTextDiv = document.createElement("div");
  78290. this._loadingTextDiv.style.position = "absolute";
  78291. this._loadingTextDiv.style.left = "0";
  78292. this._loadingTextDiv.style.top = "50%";
  78293. this._loadingTextDiv.style.marginTop = "80px";
  78294. this._loadingTextDiv.style.width = "100%";
  78295. this._loadingTextDiv.style.height = "20px";
  78296. this._loadingTextDiv.style.fontFamily = "Arial";
  78297. this._loadingTextDiv.style.fontSize = "14px";
  78298. this._loadingTextDiv.style.color = "white";
  78299. this._loadingTextDiv.style.textAlign = "center";
  78300. this._loadingTextDiv.innerHTML = "Loading";
  78301. this._loadingDiv.appendChild(this._loadingTextDiv);
  78302. //set the predefined text
  78303. this._loadingTextDiv.innerHTML = this._loadingText;
  78304. // Generating keyframes
  78305. var style = document.createElement('style');
  78306. style.type = 'text/css';
  78307. 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 }";
  78308. style.innerHTML = keyFrames;
  78309. document.getElementsByTagName('head')[0].appendChild(style);
  78310. // Loading img
  78311. var imgBack = new Image();
  78312. 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";
  78313. imgBack.style.position = "absolute";
  78314. imgBack.style.left = "50%";
  78315. imgBack.style.top = "50%";
  78316. imgBack.style.marginLeft = "-60px";
  78317. imgBack.style.marginTop = "-60px";
  78318. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  78319. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  78320. imgBack.style.transformOrigin = "50% 50%";
  78321. imgBack.style.webkitTransformOrigin = "50% 50%";
  78322. this._loadingDiv.appendChild(imgBack);
  78323. this._resizeLoadingUI();
  78324. window.addEventListener("resize", this._resizeLoadingUI);
  78325. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  78326. document.body.appendChild(this._loadingDiv);
  78327. this._loadingDiv.style.opacity = "1";
  78328. };
  78329. /**
  78330. * Function called to hide the loading screen
  78331. */
  78332. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  78333. var _this = this;
  78334. if (!this._loadingDiv) {
  78335. return;
  78336. }
  78337. var onTransitionEnd = function () {
  78338. if (!_this._loadingDiv) {
  78339. return;
  78340. }
  78341. if (_this._loadingDiv.parentElement) {
  78342. _this._loadingDiv.parentElement.removeChild(_this._loadingDiv);
  78343. }
  78344. window.removeEventListener("resize", _this._resizeLoadingUI);
  78345. _this._loadingDiv = null;
  78346. };
  78347. this._loadingDiv.style.opacity = "0";
  78348. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  78349. };
  78350. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  78351. get: function () {
  78352. return this._loadingText;
  78353. },
  78354. /**
  78355. * Gets or sets the text to display while loading
  78356. */
  78357. set: function (text) {
  78358. this._loadingText = text;
  78359. if (this._loadingTextDiv) {
  78360. this._loadingTextDiv.innerHTML = this._loadingText;
  78361. }
  78362. },
  78363. enumerable: true,
  78364. configurable: true
  78365. });
  78366. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  78367. /**
  78368. * Gets or sets the color to use for the background
  78369. */
  78370. get: function () {
  78371. return this._loadingDivBackgroundColor;
  78372. },
  78373. set: function (color) {
  78374. this._loadingDivBackgroundColor = color;
  78375. if (!this._loadingDiv) {
  78376. return;
  78377. }
  78378. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  78379. },
  78380. enumerable: true,
  78381. configurable: true
  78382. });
  78383. return DefaultLoadingScreen;
  78384. }());
  78385. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  78386. })(BABYLON || (BABYLON = {}));
  78387. //# sourceMappingURL=babylon.loadingScreen.js.map
  78388. var BABYLON;
  78389. (function (BABYLON) {
  78390. /**
  78391. * Class used to represent data loading progression
  78392. */
  78393. var SceneLoaderProgressEvent = /** @class */ (function () {
  78394. /**
  78395. * Create a new progress event
  78396. * @param lengthComputable defines if data length to load can be evaluated
  78397. * @param loaded defines the loaded data length
  78398. * @param total defines the data length to load
  78399. */
  78400. function SceneLoaderProgressEvent(
  78401. /** defines if data length to load can be evaluated */
  78402. lengthComputable,
  78403. /** defines the loaded data length */
  78404. loaded,
  78405. /** defines the data length to load */
  78406. total) {
  78407. this.lengthComputable = lengthComputable;
  78408. this.loaded = loaded;
  78409. this.total = total;
  78410. }
  78411. /**
  78412. * Creates a new SceneLoaderProgressEvent from a ProgressEvent
  78413. * @param event defines the source event
  78414. * @returns a new SceneLoaderProgressEvent
  78415. */
  78416. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  78417. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  78418. };
  78419. return SceneLoaderProgressEvent;
  78420. }());
  78421. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  78422. /**
  78423. * Class used to load scene from various file formats using registered plugins
  78424. * @see http://doc.babylonjs.com/how_to/load_from_any_file_type
  78425. */
  78426. var SceneLoader = /** @class */ (function () {
  78427. function SceneLoader() {
  78428. }
  78429. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  78430. /**
  78431. * Gets or sets a boolean indicating if entire scene must be loaded even if scene contains incremental data
  78432. */
  78433. get: function () {
  78434. return SceneLoader._ForceFullSceneLoadingForIncremental;
  78435. },
  78436. set: function (value) {
  78437. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  78438. },
  78439. enumerable: true,
  78440. configurable: true
  78441. });
  78442. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  78443. /**
  78444. * Gets or sets a boolean indicating if loading screen must be displayed while loading a scene
  78445. */
  78446. get: function () {
  78447. return SceneLoader._ShowLoadingScreen;
  78448. },
  78449. set: function (value) {
  78450. SceneLoader._ShowLoadingScreen = value;
  78451. },
  78452. enumerable: true,
  78453. configurable: true
  78454. });
  78455. Object.defineProperty(SceneLoader, "loggingLevel", {
  78456. /**
  78457. * Defines the current logging level (while loading the scene)
  78458. * @ignorenaming
  78459. */
  78460. get: function () {
  78461. return SceneLoader._loggingLevel;
  78462. },
  78463. set: function (value) {
  78464. SceneLoader._loggingLevel = value;
  78465. },
  78466. enumerable: true,
  78467. configurable: true
  78468. });
  78469. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  78470. /**
  78471. * Gets or set a boolean indicating if matrix weights must be cleaned upon loading
  78472. */
  78473. get: function () {
  78474. return SceneLoader._CleanBoneMatrixWeights;
  78475. },
  78476. set: function (value) {
  78477. SceneLoader._CleanBoneMatrixWeights = value;
  78478. },
  78479. enumerable: true,
  78480. configurable: true
  78481. });
  78482. SceneLoader._getDefaultPlugin = function () {
  78483. return SceneLoader._registeredPlugins[".babylon"];
  78484. };
  78485. SceneLoader._getPluginForExtension = function (extension) {
  78486. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  78487. if (registeredPlugin) {
  78488. return registeredPlugin;
  78489. }
  78490. 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");
  78491. return SceneLoader._getDefaultPlugin();
  78492. };
  78493. SceneLoader._getPluginForDirectLoad = function (data) {
  78494. for (var extension in SceneLoader._registeredPlugins) {
  78495. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  78496. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  78497. return SceneLoader._registeredPlugins[extension];
  78498. }
  78499. }
  78500. return SceneLoader._getDefaultPlugin();
  78501. };
  78502. SceneLoader._getPluginForFilename = function (sceneFilename) {
  78503. var queryStringPosition = sceneFilename.indexOf("?");
  78504. if (queryStringPosition !== -1) {
  78505. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  78506. }
  78507. var dotPosition = sceneFilename.lastIndexOf(".");
  78508. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  78509. return SceneLoader._getPluginForExtension(extension);
  78510. };
  78511. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  78512. SceneLoader._getDirectLoad = function (sceneFilename) {
  78513. if (sceneFilename.substr(0, 5) === "data:") {
  78514. return sceneFilename.substr(5);
  78515. }
  78516. return null;
  78517. };
  78518. SceneLoader._loadData = function (fileInfo, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  78519. var directLoad = SceneLoader._getDirectLoad(fileInfo.name);
  78520. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(fileInfo.name) : SceneLoader._getPluginForFilename(fileInfo.name));
  78521. var plugin;
  78522. if (registeredPlugin.plugin.createPlugin) {
  78523. plugin = registeredPlugin.plugin.createPlugin();
  78524. }
  78525. else {
  78526. plugin = registeredPlugin.plugin;
  78527. }
  78528. var useArrayBuffer = registeredPlugin.isBinary;
  78529. var offlineProvider;
  78530. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  78531. var dataCallback = function (data, responseURL) {
  78532. if (scene.isDisposed) {
  78533. onError("Scene has been disposed");
  78534. return;
  78535. }
  78536. scene.offlineProvider = offlineProvider;
  78537. onSuccess(plugin, data, responseURL);
  78538. };
  78539. var request = null;
  78540. var pluginDisposed = false;
  78541. var onDisposeObservable = plugin.onDisposeObservable;
  78542. if (onDisposeObservable) {
  78543. onDisposeObservable.add(function () {
  78544. pluginDisposed = true;
  78545. if (request) {
  78546. request.abort();
  78547. request = null;
  78548. }
  78549. onDispose();
  78550. });
  78551. }
  78552. var manifestChecked = function () {
  78553. if (pluginDisposed) {
  78554. return;
  78555. }
  78556. request = BABYLON.Tools.LoadFile(fileInfo.url, dataCallback, onProgress ? function (event) {
  78557. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  78558. } : undefined, offlineProvider, useArrayBuffer, function (request, exception) {
  78559. onError("Failed to load scene." + (exception ? " " + exception.message : ""), exception);
  78560. });
  78561. };
  78562. if (directLoad) {
  78563. dataCallback(directLoad);
  78564. return plugin;
  78565. }
  78566. var file = fileInfo.file || BABYLON.FilesInput.FilesToLoad[fileInfo.name.toLowerCase()];
  78567. if (fileInfo.rootUrl.indexOf("file:") === -1 || (fileInfo.rootUrl.indexOf("file:") !== -1 && !file)) {
  78568. var engine = scene.getEngine();
  78569. var canUseOfflineSupport = engine.enableOfflineSupport;
  78570. if (canUseOfflineSupport) {
  78571. // Also check for exceptions
  78572. var exceptionFound = false;
  78573. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  78574. var regex = _a[_i];
  78575. if (regex.test(fileInfo.url)) {
  78576. exceptionFound = true;
  78577. break;
  78578. }
  78579. }
  78580. canUseOfflineSupport = !exceptionFound;
  78581. }
  78582. if (canUseOfflineSupport && BABYLON.Engine.OfflineProviderFactory) {
  78583. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  78584. offlineProvider = BABYLON.Engine.OfflineProviderFactory(fileInfo.url, manifestChecked, engine.disableManifestCheck);
  78585. }
  78586. else {
  78587. manifestChecked();
  78588. }
  78589. }
  78590. // Loading file from disk via input file or drag'n'drop
  78591. else {
  78592. if (file) {
  78593. request = BABYLON.Tools.ReadFile(file, dataCallback, onProgress, useArrayBuffer);
  78594. }
  78595. else {
  78596. onError("Unable to find file named " + fileInfo.name);
  78597. }
  78598. }
  78599. return plugin;
  78600. };
  78601. SceneLoader._getFileInfo = function (rootUrl, sceneFilename) {
  78602. var url;
  78603. var name;
  78604. var file = null;
  78605. if (!sceneFilename) {
  78606. url = rootUrl;
  78607. name = BABYLON.Tools.GetFilename(rootUrl);
  78608. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  78609. }
  78610. else if (sceneFilename.lastModified) {
  78611. var sceneFile = sceneFilename;
  78612. url = rootUrl + sceneFile.name;
  78613. name = sceneFile.name;
  78614. file = sceneFile;
  78615. }
  78616. else {
  78617. var filename = sceneFilename;
  78618. if (filename.substr(0, 1) === "/") {
  78619. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  78620. return null;
  78621. }
  78622. url = rootUrl + filename;
  78623. name = filename;
  78624. }
  78625. return {
  78626. url: url,
  78627. rootUrl: rootUrl,
  78628. name: name,
  78629. file: file
  78630. };
  78631. };
  78632. // Public functions
  78633. /**
  78634. * Gets a plugin that can load the given extension
  78635. * @param extension defines the extension to load
  78636. * @returns a plugin or null if none works
  78637. */
  78638. SceneLoader.GetPluginForExtension = function (extension) {
  78639. return SceneLoader._getPluginForExtension(extension).plugin;
  78640. };
  78641. /**
  78642. * Gets a boolean indicating that the given extension can be loaded
  78643. * @param extension defines the extension to load
  78644. * @returns true if the extension is supported
  78645. */
  78646. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  78647. return !!SceneLoader._registeredPlugins[extension];
  78648. };
  78649. /**
  78650. * Adds a new plugin to the list of registered plugins
  78651. * @param plugin defines the plugin to add
  78652. */
  78653. SceneLoader.RegisterPlugin = function (plugin) {
  78654. if (typeof plugin.extensions === "string") {
  78655. var extension = plugin.extensions;
  78656. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  78657. plugin: plugin,
  78658. isBinary: false
  78659. };
  78660. }
  78661. else {
  78662. var extensions = plugin.extensions;
  78663. Object.keys(extensions).forEach(function (extension) {
  78664. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  78665. plugin: plugin,
  78666. isBinary: extensions[extension].isBinary
  78667. };
  78668. });
  78669. }
  78670. };
  78671. /**
  78672. * Import meshes into a scene
  78673. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  78674. * @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)
  78675. * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene or a File object (default: empty string)
  78676. * @param scene the instance of BABYLON.Scene to append to
  78677. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  78678. * @param onProgress a callback with a progress event for each file being loaded
  78679. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  78680. * @param pluginExtension the extension used to determine the plugin
  78681. * @returns The loaded plugin
  78682. */
  78683. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  78684. if (sceneFilename === void 0) { sceneFilename = ""; }
  78685. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  78686. if (onSuccess === void 0) { onSuccess = null; }
  78687. if (onProgress === void 0) { onProgress = null; }
  78688. if (onError === void 0) { onError = null; }
  78689. if (pluginExtension === void 0) { pluginExtension = null; }
  78690. if (!scene) {
  78691. BABYLON.Tools.Error("No scene available to import mesh to");
  78692. return null;
  78693. }
  78694. var fileInfo = SceneLoader._getFileInfo(rootUrl, sceneFilename);
  78695. if (!fileInfo) {
  78696. return null;
  78697. }
  78698. var loadingToken = {};
  78699. scene._addPendingData(loadingToken);
  78700. var disposeHandler = function () {
  78701. scene._removePendingData(loadingToken);
  78702. };
  78703. var errorHandler = function (message, exception) {
  78704. var errorMessage = "Unable to import meshes from " + fileInfo.url + ": " + message;
  78705. if (onError) {
  78706. onError(scene, errorMessage, exception);
  78707. }
  78708. else {
  78709. BABYLON.Tools.Error(errorMessage);
  78710. // should the exception be thrown?
  78711. }
  78712. disposeHandler();
  78713. };
  78714. var progressHandler = onProgress ? function (event) {
  78715. try {
  78716. onProgress(event);
  78717. }
  78718. catch (e) {
  78719. errorHandler("Error in onProgress callback", e);
  78720. }
  78721. } : undefined;
  78722. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  78723. scene.importedMeshesFiles.push(fileInfo.url);
  78724. if (onSuccess) {
  78725. try {
  78726. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  78727. }
  78728. catch (e) {
  78729. errorHandler("Error in onSuccess callback", e);
  78730. }
  78731. }
  78732. scene._removePendingData(loadingToken);
  78733. };
  78734. return SceneLoader._loadData(fileInfo, scene, function (plugin, data, responseURL) {
  78735. if (plugin.rewriteRootURL) {
  78736. fileInfo.rootUrl = plugin.rewriteRootURL(fileInfo.rootUrl, responseURL);
  78737. }
  78738. if (plugin.importMesh) {
  78739. var syncedPlugin = plugin;
  78740. var meshes = new Array();
  78741. var particleSystems = new Array();
  78742. var skeletons = new Array();
  78743. if (!syncedPlugin.importMesh(meshNames, scene, data, fileInfo.rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  78744. return;
  78745. }
  78746. scene.loadingPluginName = plugin.name;
  78747. successHandler(meshes, particleSystems, skeletons, []);
  78748. }
  78749. else {
  78750. var asyncedPlugin = plugin;
  78751. asyncedPlugin.importMeshAsync(meshNames, scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name).then(function (result) {
  78752. scene.loadingPluginName = plugin.name;
  78753. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  78754. }).catch(function (error) {
  78755. errorHandler(error.message, error);
  78756. });
  78757. }
  78758. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  78759. };
  78760. /**
  78761. * Import meshes into a scene
  78762. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  78763. * @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)
  78764. * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene or a File object (default: empty string)
  78765. * @param scene the instance of BABYLON.Scene to append to
  78766. * @param onProgress a callback with a progress event for each file being loaded
  78767. * @param pluginExtension the extension used to determine the plugin
  78768. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  78769. */
  78770. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  78771. if (sceneFilename === void 0) { sceneFilename = ""; }
  78772. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  78773. if (onProgress === void 0) { onProgress = null; }
  78774. if (pluginExtension === void 0) { pluginExtension = null; }
  78775. return new Promise(function (resolve, reject) {
  78776. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  78777. resolve({
  78778. meshes: meshes,
  78779. particleSystems: particleSystems,
  78780. skeletons: skeletons,
  78781. animationGroups: animationGroups
  78782. });
  78783. }, onProgress, function (scene, message, exception) {
  78784. reject(exception || new Error(message));
  78785. }, pluginExtension);
  78786. });
  78787. };
  78788. /**
  78789. * Load a scene
  78790. * @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)
  78791. * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene or a File object (default: empty string)
  78792. * @param engine is the instance of BABYLON.Engine to use to create the scene
  78793. * @param onSuccess a callback with the scene when import succeeds
  78794. * @param onProgress a callback with a progress event for each file being loaded
  78795. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  78796. * @param pluginExtension the extension used to determine the plugin
  78797. * @returns The loaded plugin
  78798. */
  78799. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  78800. if (sceneFilename === void 0) { sceneFilename = ""; }
  78801. if (engine === void 0) { engine = BABYLON.Engine.LastCreatedEngine; }
  78802. if (onSuccess === void 0) { onSuccess = null; }
  78803. if (onProgress === void 0) { onProgress = null; }
  78804. if (onError === void 0) { onError = null; }
  78805. if (pluginExtension === void 0) { pluginExtension = null; }
  78806. if (!engine) {
  78807. BABYLON.Tools.Error("No engine available");
  78808. return null;
  78809. }
  78810. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  78811. };
  78812. /**
  78813. * Load a scene
  78814. * @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)
  78815. * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene or a File object (default: empty string)
  78816. * @param engine is the instance of BABYLON.Engine to use to create the scene
  78817. * @param onProgress a callback with a progress event for each file being loaded
  78818. * @param pluginExtension the extension used to determine the plugin
  78819. * @returns The loaded scene
  78820. */
  78821. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  78822. if (sceneFilename === void 0) { sceneFilename = ""; }
  78823. if (engine === void 0) { engine = BABYLON.Engine.LastCreatedEngine; }
  78824. if (onProgress === void 0) { onProgress = null; }
  78825. if (pluginExtension === void 0) { pluginExtension = null; }
  78826. return new Promise(function (resolve, reject) {
  78827. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  78828. resolve(scene);
  78829. }, onProgress, function (scene, message, exception) {
  78830. reject(exception || new Error(message));
  78831. }, pluginExtension);
  78832. });
  78833. };
  78834. /**
  78835. * Append a scene
  78836. * @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)
  78837. * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene or a File object (default: empty string)
  78838. * @param scene is the instance of BABYLON.Scene to append to
  78839. * @param onSuccess a callback with the scene when import succeeds
  78840. * @param onProgress a callback with a progress event for each file being loaded
  78841. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  78842. * @param pluginExtension the extension used to determine the plugin
  78843. * @returns The loaded plugin
  78844. */
  78845. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  78846. if (sceneFilename === void 0) { sceneFilename = ""; }
  78847. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  78848. if (onSuccess === void 0) { onSuccess = null; }
  78849. if (onProgress === void 0) { onProgress = null; }
  78850. if (onError === void 0) { onError = null; }
  78851. if (pluginExtension === void 0) { pluginExtension = null; }
  78852. if (!scene) {
  78853. BABYLON.Tools.Error("No scene available to append to");
  78854. return null;
  78855. }
  78856. var fileInfo = SceneLoader._getFileInfo(rootUrl, sceneFilename);
  78857. if (!fileInfo) {
  78858. return null;
  78859. }
  78860. if (SceneLoader.ShowLoadingScreen) {
  78861. scene.getEngine().displayLoadingUI();
  78862. }
  78863. var loadingToken = {};
  78864. scene._addPendingData(loadingToken);
  78865. var disposeHandler = function () {
  78866. scene._removePendingData(loadingToken);
  78867. scene.getEngine().hideLoadingUI();
  78868. };
  78869. var errorHandler = function (message, exception) {
  78870. var errorMessage = "Unable to load from " + fileInfo.url + (message ? ": " + message : "");
  78871. if (onError) {
  78872. onError(scene, errorMessage, exception);
  78873. }
  78874. else {
  78875. BABYLON.Tools.Error(errorMessage);
  78876. // should the exception be thrown?
  78877. }
  78878. disposeHandler();
  78879. };
  78880. var progressHandler = onProgress ? function (event) {
  78881. try {
  78882. onProgress(event);
  78883. }
  78884. catch (e) {
  78885. errorHandler("Error in onProgress callback", e);
  78886. }
  78887. } : undefined;
  78888. var successHandler = function () {
  78889. if (onSuccess) {
  78890. try {
  78891. onSuccess(scene);
  78892. }
  78893. catch (e) {
  78894. errorHandler("Error in onSuccess callback", e);
  78895. }
  78896. }
  78897. scene._removePendingData(loadingToken);
  78898. };
  78899. return SceneLoader._loadData(fileInfo, scene, function (plugin, data, responseURL) {
  78900. if (plugin.load) {
  78901. var syncedPlugin = plugin;
  78902. if (!syncedPlugin.load(scene, data, fileInfo.rootUrl, errorHandler)) {
  78903. return;
  78904. }
  78905. scene.loadingPluginName = plugin.name;
  78906. successHandler();
  78907. }
  78908. else {
  78909. var asyncedPlugin = plugin;
  78910. asyncedPlugin.loadAsync(scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name).then(function () {
  78911. scene.loadingPluginName = plugin.name;
  78912. successHandler();
  78913. }).catch(function (error) {
  78914. errorHandler(error.message, error);
  78915. });
  78916. }
  78917. if (SceneLoader.ShowLoadingScreen) {
  78918. scene.executeWhenReady(function () {
  78919. scene.getEngine().hideLoadingUI();
  78920. });
  78921. }
  78922. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  78923. };
  78924. /**
  78925. * Append a scene
  78926. * @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)
  78927. * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene or a File object (default: empty string)
  78928. * @param scene is the instance of BABYLON.Scene to append to
  78929. * @param onProgress a callback with a progress event for each file being loaded
  78930. * @param pluginExtension the extension used to determine the plugin
  78931. * @returns The given scene
  78932. */
  78933. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  78934. if (sceneFilename === void 0) { sceneFilename = ""; }
  78935. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  78936. if (onProgress === void 0) { onProgress = null; }
  78937. if (pluginExtension === void 0) { pluginExtension = null; }
  78938. return new Promise(function (resolve, reject) {
  78939. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  78940. resolve(scene);
  78941. }, onProgress, function (scene, message, exception) {
  78942. reject(exception || new Error(message));
  78943. }, pluginExtension);
  78944. });
  78945. };
  78946. /**
  78947. * Load a scene into an asset container
  78948. * @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)
  78949. * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene or a File object (default: empty string)
  78950. * @param scene is the instance of BABYLON.Scene to append to (default: last created scene)
  78951. * @param onSuccess a callback with the scene when import succeeds
  78952. * @param onProgress a callback with a progress event for each file being loaded
  78953. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  78954. * @param pluginExtension the extension used to determine the plugin
  78955. * @returns The loaded plugin
  78956. */
  78957. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  78958. if (sceneFilename === void 0) { sceneFilename = ""; }
  78959. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  78960. if (onSuccess === void 0) { onSuccess = null; }
  78961. if (onProgress === void 0) { onProgress = null; }
  78962. if (onError === void 0) { onError = null; }
  78963. if (pluginExtension === void 0) { pluginExtension = null; }
  78964. if (!scene) {
  78965. BABYLON.Tools.Error("No scene available to load asset container to");
  78966. return null;
  78967. }
  78968. var fileInfo = SceneLoader._getFileInfo(rootUrl, sceneFilename);
  78969. if (!fileInfo) {
  78970. return null;
  78971. }
  78972. var loadingToken = {};
  78973. scene._addPendingData(loadingToken);
  78974. var disposeHandler = function () {
  78975. scene._removePendingData(loadingToken);
  78976. };
  78977. var errorHandler = function (message, exception) {
  78978. var errorMessage = "Unable to load assets from " + fileInfo.url + (message ? ": " + message : "");
  78979. if (onError) {
  78980. onError(scene, errorMessage, exception);
  78981. }
  78982. else {
  78983. BABYLON.Tools.Error(errorMessage);
  78984. // should the exception be thrown?
  78985. }
  78986. disposeHandler();
  78987. };
  78988. var progressHandler = onProgress ? function (event) {
  78989. try {
  78990. onProgress(event);
  78991. }
  78992. catch (e) {
  78993. errorHandler("Error in onProgress callback", e);
  78994. }
  78995. } : undefined;
  78996. var successHandler = function (assets) {
  78997. if (onSuccess) {
  78998. try {
  78999. onSuccess(assets);
  79000. }
  79001. catch (e) {
  79002. errorHandler("Error in onSuccess callback", e);
  79003. }
  79004. }
  79005. scene._removePendingData(loadingToken);
  79006. };
  79007. return SceneLoader._loadData(fileInfo, scene, function (plugin, data, responseURL) {
  79008. if (plugin.loadAssetContainer) {
  79009. var syncedPlugin = plugin;
  79010. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, fileInfo.rootUrl, errorHandler);
  79011. if (!assetContainer) {
  79012. return;
  79013. }
  79014. scene.loadingPluginName = plugin.name;
  79015. successHandler(assetContainer);
  79016. }
  79017. else if (plugin.loadAssetContainerAsync) {
  79018. var asyncedPlugin = plugin;
  79019. asyncedPlugin.loadAssetContainerAsync(scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name).then(function (assetContainer) {
  79020. scene.loadingPluginName = plugin.name;
  79021. successHandler(assetContainer);
  79022. }).catch(function (error) {
  79023. errorHandler(error.message, error);
  79024. });
  79025. }
  79026. else {
  79027. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  79028. }
  79029. if (SceneLoader.ShowLoadingScreen) {
  79030. scene.executeWhenReady(function () {
  79031. scene.getEngine().hideLoadingUI();
  79032. });
  79033. }
  79034. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  79035. };
  79036. /**
  79037. * Load a scene into an asset container
  79038. * @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)
  79039. * @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)
  79040. * @param scene is the instance of BABYLON.Scene to append to
  79041. * @param onProgress a callback with a progress event for each file being loaded
  79042. * @param pluginExtension the extension used to determine the plugin
  79043. * @returns The loaded asset container
  79044. */
  79045. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  79046. if (sceneFilename === void 0) { sceneFilename = ""; }
  79047. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  79048. if (onProgress === void 0) { onProgress = null; }
  79049. if (pluginExtension === void 0) { pluginExtension = null; }
  79050. return new Promise(function (resolve, reject) {
  79051. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  79052. resolve(assetContainer);
  79053. }, onProgress, function (scene, message, exception) {
  79054. reject(exception || new Error(message));
  79055. }, pluginExtension);
  79056. });
  79057. };
  79058. // Flags
  79059. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  79060. SceneLoader._ShowLoadingScreen = true;
  79061. SceneLoader._CleanBoneMatrixWeights = false;
  79062. /**
  79063. * No logging while loading
  79064. */
  79065. SceneLoader.NO_LOGGING = 0;
  79066. /**
  79067. * Minimal logging while loading
  79068. */
  79069. SceneLoader.MINIMAL_LOGGING = 1;
  79070. /**
  79071. * Summary logging while loading
  79072. */
  79073. SceneLoader.SUMMARY_LOGGING = 2;
  79074. /**
  79075. * Detailled logging while loading
  79076. */
  79077. SceneLoader.DETAILED_LOGGING = 3;
  79078. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  79079. // Members
  79080. /**
  79081. * Event raised when a plugin is used to load a scene
  79082. */
  79083. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  79084. SceneLoader._registeredPlugins = {};
  79085. return SceneLoader;
  79086. }());
  79087. BABYLON.SceneLoader = SceneLoader;
  79088. })(BABYLON || (BABYLON = {}));
  79089. //# sourceMappingURL=babylon.sceneLoader.js.map
  79090. var BABYLON;
  79091. (function (BABYLON) {
  79092. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  79093. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  79094. var parsedMaterial = parsedData.materials[index];
  79095. if (parsedMaterial.id === id) {
  79096. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  79097. }
  79098. }
  79099. return null;
  79100. };
  79101. var isDescendantOf = function (mesh, names, hierarchyIds) {
  79102. for (var i in names) {
  79103. if (mesh.name === names[i]) {
  79104. hierarchyIds.push(mesh.id);
  79105. return true;
  79106. }
  79107. }
  79108. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  79109. hierarchyIds.push(mesh.id);
  79110. return true;
  79111. }
  79112. return false;
  79113. };
  79114. var logOperation = function (operation, producer) {
  79115. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  79116. };
  79117. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  79118. if (addToScene === void 0) { addToScene = false; }
  79119. var container = new BABYLON.AssetContainer(scene);
  79120. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  79121. // when SceneLoader.debugLogging = true (default), or exception encountered.
  79122. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  79123. // and avoid problems with multiple concurrent .babylon loads.
  79124. var log = "importScene has failed JSON parse";
  79125. try {
  79126. var parsedData = JSON.parse(data);
  79127. log = "";
  79128. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  79129. var index;
  79130. var cache;
  79131. // Lights
  79132. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  79133. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  79134. var parsedLight = parsedData.lights[index];
  79135. var light = BABYLON.Light.Parse(parsedLight, scene);
  79136. if (light) {
  79137. container.lights.push(light);
  79138. log += (index === 0 ? "\n\tLights:" : "");
  79139. log += "\n\t\t" + light.toString(fullDetails);
  79140. }
  79141. }
  79142. }
  79143. // Reflection probes
  79144. if (parsedData.reflectionProbes !== undefined && parsedData.reflectionProbes !== null) {
  79145. for (index = 0, cache = parsedData.reflectionProbes.length; index < cache; index++) {
  79146. var parsedReflectionProbe = parsedData.reflectionProbes[index];
  79147. var reflectionProbe = BABYLON.ReflectionProbe.Parse(parsedReflectionProbe, scene, rootUrl);
  79148. if (reflectionProbe) {
  79149. container.reflectionProbes.push(reflectionProbe);
  79150. log += (index === 0 ? "\n\tReflection Probes:" : "");
  79151. log += "\n\t\t" + reflectionProbe.toString(fullDetails);
  79152. }
  79153. }
  79154. }
  79155. // Animations
  79156. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  79157. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  79158. var parsedAnimation = parsedData.animations[index];
  79159. var animation = BABYLON.Animation.Parse(parsedAnimation);
  79160. scene.animations.push(animation);
  79161. container.animations.push(animation);
  79162. log += (index === 0 ? "\n\tAnimations:" : "");
  79163. log += "\n\t\t" + animation.toString(fullDetails);
  79164. }
  79165. }
  79166. // Materials
  79167. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  79168. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  79169. var parsedMaterial = parsedData.materials[index];
  79170. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  79171. container.materials.push(mat);
  79172. log += (index === 0 ? "\n\tMaterials:" : "");
  79173. log += "\n\t\t" + mat.toString(fullDetails);
  79174. }
  79175. }
  79176. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  79177. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  79178. var parsedMultiMaterial = parsedData.multiMaterials[index];
  79179. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  79180. container.multiMaterials.push(mmat);
  79181. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  79182. log += "\n\t\t" + mmat.toString(fullDetails);
  79183. }
  79184. }
  79185. // Morph targets
  79186. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  79187. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  79188. var managerData = _a[_i];
  79189. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  79190. }
  79191. }
  79192. // Skeletons
  79193. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  79194. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  79195. var parsedSkeleton = parsedData.skeletons[index];
  79196. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  79197. container.skeletons.push(skeleton);
  79198. log += (index === 0 ? "\n\tSkeletons:" : "");
  79199. log += "\n\t\t" + skeleton.toString(fullDetails);
  79200. }
  79201. }
  79202. // Geometries
  79203. var geometries = parsedData.geometries;
  79204. if (geometries !== undefined && geometries !== null) {
  79205. var addedGeometry = new Array();
  79206. // Boxes
  79207. var boxes = geometries.boxes;
  79208. if (boxes !== undefined && boxes !== null) {
  79209. for (index = 0, cache = boxes.length; index < cache; index++) {
  79210. var parsedBox = boxes[index];
  79211. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  79212. }
  79213. }
  79214. // Spheres
  79215. var spheres = geometries.spheres;
  79216. if (spheres !== undefined && spheres !== null) {
  79217. for (index = 0, cache = spheres.length; index < cache; index++) {
  79218. var parsedSphere = spheres[index];
  79219. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  79220. }
  79221. }
  79222. // Cylinders
  79223. var cylinders = geometries.cylinders;
  79224. if (cylinders !== undefined && cylinders !== null) {
  79225. for (index = 0, cache = cylinders.length; index < cache; index++) {
  79226. var parsedCylinder = cylinders[index];
  79227. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  79228. }
  79229. }
  79230. // Toruses
  79231. var toruses = geometries.toruses;
  79232. if (toruses !== undefined && toruses !== null) {
  79233. for (index = 0, cache = toruses.length; index < cache; index++) {
  79234. var parsedTorus = toruses[index];
  79235. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  79236. }
  79237. }
  79238. // Grounds
  79239. var grounds = geometries.grounds;
  79240. if (grounds !== undefined && grounds !== null) {
  79241. for (index = 0, cache = grounds.length; index < cache; index++) {
  79242. var parsedGround = grounds[index];
  79243. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  79244. }
  79245. }
  79246. // Planes
  79247. var planes = geometries.planes;
  79248. if (planes !== undefined && planes !== null) {
  79249. for (index = 0, cache = planes.length; index < cache; index++) {
  79250. var parsedPlane = planes[index];
  79251. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  79252. }
  79253. }
  79254. // TorusKnots
  79255. var torusKnots = geometries.torusKnots;
  79256. if (torusKnots !== undefined && torusKnots !== null) {
  79257. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  79258. var parsedTorusKnot = torusKnots[index];
  79259. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  79260. }
  79261. }
  79262. // VertexData
  79263. var vertexData = geometries.vertexData;
  79264. if (vertexData !== undefined && vertexData !== null) {
  79265. for (index = 0, cache = vertexData.length; index < cache; index++) {
  79266. var parsedVertexData = vertexData[index];
  79267. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  79268. }
  79269. }
  79270. addedGeometry.forEach(function (g) {
  79271. if (g) {
  79272. container.geometries.push(g);
  79273. }
  79274. });
  79275. }
  79276. // Transform nodes
  79277. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  79278. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  79279. var parsedTransformNode = parsedData.transformNodes[index];
  79280. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  79281. container.transformNodes.push(node);
  79282. }
  79283. }
  79284. // Meshes
  79285. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  79286. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  79287. var parsedMesh = parsedData.meshes[index];
  79288. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  79289. container.meshes.push(mesh);
  79290. log += (index === 0 ? "\n\tMeshes:" : "");
  79291. log += "\n\t\t" + mesh.toString(fullDetails);
  79292. }
  79293. }
  79294. // Cameras
  79295. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  79296. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  79297. var parsedCamera = parsedData.cameras[index];
  79298. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  79299. container.cameras.push(camera);
  79300. log += (index === 0 ? "\n\tCameras:" : "");
  79301. log += "\n\t\t" + camera.toString(fullDetails);
  79302. }
  79303. }
  79304. // Animation Groups
  79305. if (parsedData.animationGroups !== undefined && parsedData.animationGroups !== null) {
  79306. for (index = 0, cache = parsedData.animationGroups.length; index < cache; index++) {
  79307. var parsedAnimationGroup = parsedData.animationGroups[index];
  79308. var animationGroup = BABYLON.AnimationGroup.Parse(parsedAnimationGroup, scene);
  79309. container.animationGroups.push(animationGroup);
  79310. log += (index === 0 ? "\n\tAnimationGroups:" : "");
  79311. log += "\n\t\t" + animationGroup.toString(fullDetails);
  79312. }
  79313. }
  79314. // Browsing all the graph to connect the dots
  79315. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  79316. var camera = scene.cameras[index];
  79317. if (camera._waitingParentId) {
  79318. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  79319. camera._waitingParentId = null;
  79320. }
  79321. }
  79322. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  79323. var light_1 = scene.lights[index];
  79324. if (light_1 && light_1._waitingParentId) {
  79325. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  79326. light_1._waitingParentId = null;
  79327. }
  79328. }
  79329. // Connect parents & children and parse actions
  79330. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  79331. var transformNode = scene.transformNodes[index];
  79332. if (transformNode._waitingParentId) {
  79333. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  79334. transformNode._waitingParentId = null;
  79335. }
  79336. }
  79337. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  79338. var mesh = scene.meshes[index];
  79339. if (mesh._waitingParentId) {
  79340. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  79341. mesh._waitingParentId = null;
  79342. }
  79343. }
  79344. // freeze world matrix application
  79345. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  79346. var currentMesh = scene.meshes[index];
  79347. if (currentMesh._waitingFreezeWorldMatrix) {
  79348. currentMesh.freezeWorldMatrix();
  79349. currentMesh._waitingFreezeWorldMatrix = null;
  79350. }
  79351. else {
  79352. currentMesh.computeWorldMatrix(true);
  79353. }
  79354. }
  79355. // Lights exclusions / inclusions
  79356. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  79357. var light_2 = scene.lights[index];
  79358. // Excluded check
  79359. if (light_2._excludedMeshesIds.length > 0) {
  79360. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  79361. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  79362. if (excludedMesh) {
  79363. light_2.excludedMeshes.push(excludedMesh);
  79364. }
  79365. }
  79366. light_2._excludedMeshesIds = [];
  79367. }
  79368. // Included check
  79369. if (light_2._includedOnlyMeshesIds.length > 0) {
  79370. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  79371. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  79372. if (includedOnlyMesh) {
  79373. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  79374. }
  79375. }
  79376. light_2._includedOnlyMeshesIds = [];
  79377. }
  79378. }
  79379. BABYLON.AbstractScene.Parse(parsedData, scene, container, rootUrl);
  79380. // Actions (scene) Done last as it can access other objects.
  79381. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  79382. var mesh = scene.meshes[index];
  79383. if (mesh._waitingActions) {
  79384. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  79385. mesh._waitingActions = null;
  79386. }
  79387. }
  79388. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  79389. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  79390. }
  79391. if (!addToScene) {
  79392. container.removeAllFromScene();
  79393. }
  79394. }
  79395. catch (err) {
  79396. var msg = logOperation("loadAssets", parsedData ? parsedData.producer : "Unknown") + log;
  79397. if (onError) {
  79398. onError(msg, err);
  79399. }
  79400. else {
  79401. BABYLON.Tools.Log(msg);
  79402. throw err;
  79403. }
  79404. }
  79405. finally {
  79406. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  79407. BABYLON.Tools.Log(logOperation("loadAssets", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  79408. }
  79409. }
  79410. return container;
  79411. };
  79412. BABYLON.SceneLoader.RegisterPlugin({
  79413. name: "babylon.js",
  79414. extensions: ".babylon",
  79415. canDirectLoad: function (data) {
  79416. if (data.indexOf("babylon") !== -1) { // We consider that the producer string is filled
  79417. return true;
  79418. }
  79419. return false;
  79420. },
  79421. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  79422. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  79423. // when SceneLoader.debugLogging = true (default), or exception encountered.
  79424. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  79425. // and avoid problems with multiple concurrent .babylon loads.
  79426. var log = "importMesh has failed JSON parse";
  79427. try {
  79428. var parsedData = JSON.parse(data);
  79429. log = "";
  79430. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  79431. if (!meshesNames) {
  79432. meshesNames = null;
  79433. }
  79434. else if (!Array.isArray(meshesNames)) {
  79435. meshesNames = [meshesNames];
  79436. }
  79437. var hierarchyIds = new Array();
  79438. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  79439. var loadedSkeletonsIds = [];
  79440. var loadedMaterialsIds = [];
  79441. var index;
  79442. var cache;
  79443. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  79444. var parsedMesh = parsedData.meshes[index];
  79445. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  79446. if (meshesNames !== null) {
  79447. // Remove found mesh name from list.
  79448. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  79449. }
  79450. //Geometry?
  79451. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  79452. //does the file contain geometries?
  79453. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  79454. //find the correct geometry and add it to the scene
  79455. var found = false;
  79456. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  79457. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  79458. return;
  79459. }
  79460. else {
  79461. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  79462. if (parsedGeometryData.id === parsedMesh.geometryId) {
  79463. switch (geometryType) {
  79464. case "boxes":
  79465. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  79466. break;
  79467. case "spheres":
  79468. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  79469. break;
  79470. case "cylinders":
  79471. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  79472. break;
  79473. case "toruses":
  79474. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  79475. break;
  79476. case "grounds":
  79477. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  79478. break;
  79479. case "planes":
  79480. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  79481. break;
  79482. case "torusKnots":
  79483. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  79484. break;
  79485. case "vertexData":
  79486. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  79487. break;
  79488. }
  79489. found = true;
  79490. }
  79491. });
  79492. }
  79493. });
  79494. if (found === false) {
  79495. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  79496. }
  79497. }
  79498. }
  79499. // Material ?
  79500. if (parsedMesh.materialId) {
  79501. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  79502. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  79503. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  79504. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  79505. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  79506. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  79507. var subMatId = parsedMultiMaterial.materials[matIndex];
  79508. loadedMaterialsIds.push(subMatId);
  79509. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  79510. if (mat) {
  79511. log += "\n\tMaterial " + mat.toString(fullDetails);
  79512. }
  79513. }
  79514. loadedMaterialsIds.push(parsedMultiMaterial.id);
  79515. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  79516. if (mmat) {
  79517. materialFound = true;
  79518. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  79519. }
  79520. break;
  79521. }
  79522. }
  79523. }
  79524. if (materialFound === false) {
  79525. loadedMaterialsIds.push(parsedMesh.materialId);
  79526. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  79527. if (!mat) {
  79528. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  79529. }
  79530. else {
  79531. log += "\n\tMaterial " + mat.toString(fullDetails);
  79532. }
  79533. }
  79534. }
  79535. // Skeleton ?
  79536. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  79537. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  79538. if (skeletonAlreadyLoaded === false) {
  79539. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  79540. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  79541. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  79542. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  79543. skeletons.push(skeleton);
  79544. loadedSkeletonsIds.push(parsedSkeleton.id);
  79545. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  79546. }
  79547. }
  79548. }
  79549. }
  79550. // Morph targets ?
  79551. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  79552. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  79553. var managerData = _a[_i];
  79554. BABYLON.MorphTargetManager.Parse(managerData, scene);
  79555. }
  79556. }
  79557. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  79558. meshes.push(mesh);
  79559. log += "\n\tMesh " + mesh.toString(fullDetails);
  79560. }
  79561. }
  79562. // Connecting parents
  79563. var currentMesh;
  79564. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  79565. currentMesh = scene.meshes[index];
  79566. if (currentMesh._waitingParentId) {
  79567. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  79568. currentMesh._waitingParentId = null;
  79569. }
  79570. }
  79571. // freeze and compute world matrix application
  79572. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  79573. currentMesh = scene.meshes[index];
  79574. if (currentMesh._waitingFreezeWorldMatrix) {
  79575. currentMesh.freezeWorldMatrix();
  79576. currentMesh._waitingFreezeWorldMatrix = null;
  79577. }
  79578. else {
  79579. currentMesh.computeWorldMatrix(true);
  79580. }
  79581. }
  79582. }
  79583. // Particles
  79584. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  79585. var parser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);
  79586. if (parser) {
  79587. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  79588. var parsedParticleSystem = parsedData.particleSystems[index];
  79589. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  79590. particleSystems.push(parser(parsedParticleSystem, scene, rootUrl));
  79591. }
  79592. }
  79593. }
  79594. }
  79595. return true;
  79596. }
  79597. catch (err) {
  79598. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  79599. if (onError) {
  79600. onError(msg, err);
  79601. }
  79602. else {
  79603. BABYLON.Tools.Log(msg);
  79604. throw err;
  79605. }
  79606. }
  79607. finally {
  79608. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  79609. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  79610. }
  79611. }
  79612. return false;
  79613. },
  79614. load: function (scene, data, rootUrl, onError) {
  79615. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  79616. // when SceneLoader.debugLogging = true (default), or exception encountered.
  79617. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  79618. // and avoid problems with multiple concurrent .babylon loads.
  79619. var log = "importScene has failed JSON parse";
  79620. try {
  79621. var parsedData = JSON.parse(data);
  79622. log = "";
  79623. // Scene
  79624. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  79625. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  79626. }
  79627. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  79628. scene.autoClear = parsedData.autoClear;
  79629. }
  79630. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  79631. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  79632. }
  79633. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  79634. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  79635. }
  79636. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  79637. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  79638. }
  79639. // Fog
  79640. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  79641. scene.fogMode = parsedData.fogMode;
  79642. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  79643. scene.fogStart = parsedData.fogStart;
  79644. scene.fogEnd = parsedData.fogEnd;
  79645. scene.fogDensity = parsedData.fogDensity;
  79646. log += "\tFog mode for scene: ";
  79647. switch (scene.fogMode) {
  79648. // getters not compiling, so using hardcoded
  79649. case 1:
  79650. log += "exp\n";
  79651. break;
  79652. case 2:
  79653. log += "exp2\n";
  79654. break;
  79655. case 3:
  79656. log += "linear\n";
  79657. break;
  79658. }
  79659. }
  79660. //Physics
  79661. if (parsedData.physicsEnabled) {
  79662. var physicsPlugin;
  79663. if (parsedData.physicsEngine === "cannon") {
  79664. physicsPlugin = new BABYLON.CannonJSPlugin();
  79665. }
  79666. else if (parsedData.physicsEngine === "oimo") {
  79667. physicsPlugin = new BABYLON.OimoJSPlugin();
  79668. }
  79669. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  79670. //else - default engine, which is currently oimo
  79671. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  79672. scene.enablePhysics(physicsGravity, physicsPlugin);
  79673. }
  79674. // Metadata
  79675. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  79676. scene.metadata = parsedData.metadata;
  79677. }
  79678. //collisions, if defined. otherwise, default is true
  79679. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  79680. scene.collisionsEnabled = parsedData.collisionsEnabled;
  79681. }
  79682. scene.workerCollisions = !!parsedData.workerCollisions;
  79683. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  79684. if (!container) {
  79685. return false;
  79686. }
  79687. if (parsedData.autoAnimate) {
  79688. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  79689. }
  79690. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  79691. scene.setActiveCameraByID(parsedData.activeCameraID);
  79692. }
  79693. // Environment texture
  79694. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  79695. // PBR needed for both HDR texture (gamma space) & a sky box
  79696. var isPBR = parsedData.isPBR !== undefined ? parsedData.isPBR : true;
  79697. if (parsedData.environmentTextureType && parsedData.environmentTextureType === "BABYLON.HDRCubeTexture") {
  79698. var hdrSize = (parsedData.environmentTextureSize) ? parsedData.environmentTextureSize : 128;
  79699. var hdrTexture = new BABYLON.HDRCubeTexture(rootUrl + parsedData.environmentTexture, scene, hdrSize, true, !isPBR);
  79700. if (parsedData.environmentTextureRotationY) {
  79701. hdrTexture.rotationY = parsedData.environmentTextureRotationY;
  79702. }
  79703. scene.environmentTexture = hdrTexture;
  79704. }
  79705. else {
  79706. var cubeTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  79707. if (parsedData.environmentTextureRotationY) {
  79708. cubeTexture.rotationY = parsedData.environmentTextureRotationY;
  79709. }
  79710. scene.environmentTexture = cubeTexture;
  79711. }
  79712. if (parsedData.createDefaultSkybox === true) {
  79713. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  79714. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  79715. scene.createDefaultSkybox(scene.environmentTexture, isPBR, skyboxScale, skyboxBlurLevel);
  79716. }
  79717. }
  79718. // Finish
  79719. return true;
  79720. }
  79721. catch (err) {
  79722. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  79723. if (onError) {
  79724. onError(msg, err);
  79725. }
  79726. else {
  79727. BABYLON.Tools.Log(msg);
  79728. throw err;
  79729. }
  79730. }
  79731. finally {
  79732. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  79733. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  79734. }
  79735. }
  79736. return false;
  79737. },
  79738. loadAssetContainer: function (scene, data, rootUrl, onError) {
  79739. var container = loadAssetContainer(scene, data, rootUrl, onError);
  79740. return container;
  79741. }
  79742. });
  79743. })(BABYLON || (BABYLON = {}));
  79744. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  79745. var BABYLON;
  79746. (function (BABYLON) {
  79747. /**
  79748. * Class used to help managing file picking and drag'n'drop
  79749. */
  79750. var FilesInput = /** @class */ (function () {
  79751. /**
  79752. * Creates a new FilesInput
  79753. * @param engine defines the rendering engine
  79754. * @param scene defines the hosting scene
  79755. * @param sceneLoadedCallback callback called when scene is loaded
  79756. * @param progressCallback callback called to track progress
  79757. * @param additionalRenderLoopLogicCallback callback called to add user logic to the rendering loop
  79758. * @param textureLoadingCallback callback called when a texture is loading
  79759. * @param startingProcessingFilesCallback callback called when the system is about to process all files
  79760. * @param onReloadCallback callback called when a reload is requested
  79761. * @param errorCallback callback call if an error occurs
  79762. */
  79763. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  79764. /**
  79765. * Callback called when a file is processed
  79766. */
  79767. this.onProcessFileCallback = function () { return true; };
  79768. this._engine = engine;
  79769. this._currentScene = scene;
  79770. this._sceneLoadedCallback = sceneLoadedCallback;
  79771. this._progressCallback = progressCallback;
  79772. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  79773. this._textureLoadingCallback = textureLoadingCallback;
  79774. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  79775. this._onReloadCallback = onReloadCallback;
  79776. this._errorCallback = errorCallback;
  79777. }
  79778. /**
  79779. * Calls this function to listen to drag'n'drop events on a specific DOM element
  79780. * @param elementToMonitor defines the DOM element to track
  79781. */
  79782. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  79783. var _this = this;
  79784. if (elementToMonitor) {
  79785. this._elementToMonitor = elementToMonitor;
  79786. this._dragEnterHandler = function (e) { _this.drag(e); };
  79787. this._dragOverHandler = function (e) { _this.drag(e); };
  79788. this._dropHandler = function (e) { _this.drop(e); };
  79789. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  79790. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  79791. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  79792. }
  79793. };
  79794. /**
  79795. * Release all associated resources
  79796. */
  79797. FilesInput.prototype.dispose = function () {
  79798. if (!this._elementToMonitor) {
  79799. return;
  79800. }
  79801. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  79802. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  79803. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  79804. };
  79805. FilesInput.prototype.renderFunction = function () {
  79806. if (this._additionalRenderLoopLogicCallback) {
  79807. this._additionalRenderLoopLogicCallback();
  79808. }
  79809. if (this._currentScene) {
  79810. if (this._textureLoadingCallback) {
  79811. var remaining = this._currentScene.getWaitingItemsCount();
  79812. if (remaining > 0) {
  79813. this._textureLoadingCallback(remaining);
  79814. }
  79815. }
  79816. this._currentScene.render();
  79817. }
  79818. };
  79819. FilesInput.prototype.drag = function (e) {
  79820. e.stopPropagation();
  79821. e.preventDefault();
  79822. };
  79823. FilesInput.prototype.drop = function (eventDrop) {
  79824. eventDrop.stopPropagation();
  79825. eventDrop.preventDefault();
  79826. this.loadFiles(eventDrop);
  79827. };
  79828. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  79829. var _this = this;
  79830. var reader = folder.createReader();
  79831. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  79832. reader.readEntries(function (entries) {
  79833. remaining.count += entries.length;
  79834. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  79835. var entry = entries_1[_i];
  79836. if (entry.isFile) {
  79837. entry.file(function (file) {
  79838. file.correctName = relativePath + file.name;
  79839. files.push(file);
  79840. if (--remaining.count === 0) {
  79841. callback();
  79842. }
  79843. });
  79844. }
  79845. else if (entry.isDirectory) {
  79846. _this._traverseFolder(entry, files, remaining, callback);
  79847. }
  79848. }
  79849. if (--remaining.count) {
  79850. callback();
  79851. }
  79852. });
  79853. };
  79854. FilesInput.prototype._processFiles = function (files) {
  79855. for (var i = 0; i < files.length; i++) {
  79856. var name = files[i].correctName.toLowerCase();
  79857. var extension = name.split('.').pop();
  79858. if (!this.onProcessFileCallback(files[i], name, extension)) {
  79859. continue;
  79860. }
  79861. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  79862. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  79863. this._sceneFileToLoad = files[i];
  79864. }
  79865. FilesInput.FilesToLoad[name] = files[i];
  79866. }
  79867. };
  79868. /**
  79869. * Load files from a drop event
  79870. * @param event defines the drop event to use as source
  79871. */
  79872. FilesInput.prototype.loadFiles = function (event) {
  79873. var _this = this;
  79874. // Handling data transfer via drag'n'drop
  79875. if (event && event.dataTransfer && event.dataTransfer.files) {
  79876. this._filesToLoad = event.dataTransfer.files;
  79877. }
  79878. // Handling files from input files
  79879. if (event && event.target && event.target.files) {
  79880. this._filesToLoad = event.target.files;
  79881. }
  79882. if (!this._filesToLoad || this._filesToLoad.length === 0) {
  79883. return;
  79884. }
  79885. if (this._startingProcessingFilesCallback) {
  79886. this._startingProcessingFilesCallback(this._filesToLoad);
  79887. }
  79888. if (this._filesToLoad && this._filesToLoad.length > 0) {
  79889. var files_1 = new Array();
  79890. var folders = [];
  79891. var items = event.dataTransfer ? event.dataTransfer.items : null;
  79892. for (var i = 0; i < this._filesToLoad.length; i++) {
  79893. var fileToLoad = this._filesToLoad[i];
  79894. var name_1 = fileToLoad.name.toLowerCase();
  79895. var entry = void 0;
  79896. fileToLoad.correctName = name_1;
  79897. if (items) {
  79898. var item = items[i];
  79899. if (item.getAsEntry) {
  79900. entry = item.getAsEntry();
  79901. }
  79902. else if (item.webkitGetAsEntry) {
  79903. entry = item.webkitGetAsEntry();
  79904. }
  79905. }
  79906. if (!entry) {
  79907. files_1.push(fileToLoad);
  79908. }
  79909. else {
  79910. if (entry.isDirectory) {
  79911. folders.push(entry);
  79912. }
  79913. else {
  79914. files_1.push(fileToLoad);
  79915. }
  79916. }
  79917. }
  79918. if (folders.length === 0) {
  79919. this._processFiles(files_1);
  79920. this._processReload();
  79921. }
  79922. else {
  79923. var remaining = { count: folders.length };
  79924. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  79925. var folder = folders_1[_i];
  79926. this._traverseFolder(folder, files_1, remaining, function () {
  79927. _this._processFiles(files_1);
  79928. if (remaining.count === 0) {
  79929. _this._processReload();
  79930. }
  79931. });
  79932. }
  79933. }
  79934. }
  79935. };
  79936. FilesInput.prototype._processReload = function () {
  79937. if (this._onReloadCallback) {
  79938. this._onReloadCallback(this._sceneFileToLoad);
  79939. }
  79940. else {
  79941. this.reload();
  79942. }
  79943. };
  79944. /**
  79945. * Reload the current scene from the loaded files
  79946. */
  79947. FilesInput.prototype.reload = function () {
  79948. var _this = this;
  79949. // If a scene file has been provided
  79950. if (this._sceneFileToLoad) {
  79951. if (this._currentScene) {
  79952. if (BABYLON.Tools.errorsCount > 0) {
  79953. BABYLON.Tools.ClearLogCache();
  79954. }
  79955. this._engine.stopRenderLoop();
  79956. }
  79957. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  79958. if (_this._progressCallback) {
  79959. _this._progressCallback(progress);
  79960. }
  79961. }).then(function (scene) {
  79962. if (_this._currentScene) {
  79963. _this._currentScene.dispose();
  79964. }
  79965. _this._currentScene = scene;
  79966. if (_this._sceneLoadedCallback) {
  79967. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  79968. }
  79969. // Wait for textures and shaders to be ready
  79970. _this._currentScene.executeWhenReady(function () {
  79971. _this._engine.runRenderLoop(function () {
  79972. _this.renderFunction();
  79973. });
  79974. });
  79975. }).catch(function (error) {
  79976. if (_this._errorCallback) {
  79977. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  79978. }
  79979. });
  79980. }
  79981. else {
  79982. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  79983. }
  79984. };
  79985. /**
  79986. * List of files ready to be loaded
  79987. */
  79988. FilesInput.FilesToLoad = {};
  79989. return FilesInput;
  79990. }());
  79991. BABYLON.FilesInput = FilesInput;
  79992. })(BABYLON || (BABYLON = {}));
  79993. //# sourceMappingURL=babylon.filesInput.js.map
  79994. var BABYLON;
  79995. (function (BABYLON) {
  79996. /**
  79997. * Class used to store custom tags
  79998. */
  79999. var Tags = /** @class */ (function () {
  80000. function Tags() {
  80001. }
  80002. /**
  80003. * Adds support for tags on the given object
  80004. * @param obj defines the object to use
  80005. */
  80006. Tags.EnableFor = function (obj) {
  80007. obj._tags = obj._tags || {};
  80008. obj.hasTags = function () {
  80009. return Tags.HasTags(obj);
  80010. };
  80011. obj.addTags = function (tagsString) {
  80012. return Tags.AddTagsTo(obj, tagsString);
  80013. };
  80014. obj.removeTags = function (tagsString) {
  80015. return Tags.RemoveTagsFrom(obj, tagsString);
  80016. };
  80017. obj.matchesTagsQuery = function (tagsQuery) {
  80018. return Tags.MatchesQuery(obj, tagsQuery);
  80019. };
  80020. };
  80021. /**
  80022. * Removes tags support
  80023. * @param obj defines the object to use
  80024. */
  80025. Tags.DisableFor = function (obj) {
  80026. delete obj._tags;
  80027. delete obj.hasTags;
  80028. delete obj.addTags;
  80029. delete obj.removeTags;
  80030. delete obj.matchesTagsQuery;
  80031. };
  80032. /**
  80033. * Gets a boolean indicating if the given object has tags
  80034. * @param obj defines the object to use
  80035. * @returns a boolean
  80036. */
  80037. Tags.HasTags = function (obj) {
  80038. if (!obj._tags) {
  80039. return false;
  80040. }
  80041. return !BABYLON.Tools.IsEmpty(obj._tags);
  80042. };
  80043. /**
  80044. * Gets the tags available on a given object
  80045. * @param obj defines the object to use
  80046. * @param asString defines if the tags must be returned as a string instead of an array of strings
  80047. * @returns the tags
  80048. */
  80049. Tags.GetTags = function (obj, asString) {
  80050. if (asString === void 0) { asString = true; }
  80051. if (!obj._tags) {
  80052. return null;
  80053. }
  80054. if (asString) {
  80055. var tagsArray = [];
  80056. for (var tag in obj._tags) {
  80057. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  80058. tagsArray.push(tag);
  80059. }
  80060. }
  80061. return tagsArray.join(" ");
  80062. }
  80063. else {
  80064. return obj._tags;
  80065. }
  80066. };
  80067. /**
  80068. * Adds tags to an object
  80069. * @param obj defines the object to use
  80070. * @param tagsString defines the tag string. The tags 'true' and 'false' are reserved and cannot be used as tags.
  80071. * A tag cannot start with '||', '&&', and '!'. It cannot contain whitespaces
  80072. */
  80073. Tags.AddTagsTo = function (obj, tagsString) {
  80074. if (!tagsString) {
  80075. return;
  80076. }
  80077. if (typeof tagsString !== "string") {
  80078. return;
  80079. }
  80080. var tags = tagsString.split(" ");
  80081. tags.forEach(function (tag, index, array) {
  80082. Tags._AddTagTo(obj, tag);
  80083. });
  80084. };
  80085. /**
  80086. * @hidden
  80087. */
  80088. Tags._AddTagTo = function (obj, tag) {
  80089. tag = tag.trim();
  80090. if (tag === "" || tag === "true" || tag === "false") {
  80091. return;
  80092. }
  80093. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  80094. return;
  80095. }
  80096. Tags.EnableFor(obj);
  80097. obj._tags[tag] = true;
  80098. };
  80099. /**
  80100. * Removes specific tags from a specific object
  80101. * @param obj defines the object to use
  80102. * @param tagsString defines the tags to remove
  80103. */
  80104. Tags.RemoveTagsFrom = function (obj, tagsString) {
  80105. if (!Tags.HasTags(obj)) {
  80106. return;
  80107. }
  80108. var tags = tagsString.split(" ");
  80109. for (var t in tags) {
  80110. Tags._RemoveTagFrom(obj, tags[t]);
  80111. }
  80112. };
  80113. /**
  80114. * @hidden
  80115. */
  80116. Tags._RemoveTagFrom = function (obj, tag) {
  80117. delete obj._tags[tag];
  80118. };
  80119. /**
  80120. * Defines if tags hosted on an object match a given query
  80121. * @param obj defines the object to use
  80122. * @param tagsQuery defines the tag query
  80123. * @returns a boolean
  80124. */
  80125. Tags.MatchesQuery = function (obj, tagsQuery) {
  80126. if (tagsQuery === undefined) {
  80127. return true;
  80128. }
  80129. if (tagsQuery === "") {
  80130. return Tags.HasTags(obj);
  80131. }
  80132. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  80133. };
  80134. return Tags;
  80135. }());
  80136. BABYLON.Tags = Tags;
  80137. })(BABYLON || (BABYLON = {}));
  80138. //# sourceMappingURL=babylon.tags.js.map
  80139. var BABYLON;
  80140. (function (BABYLON) {
  80141. /**
  80142. * Class used to evalaute queries containing `and` and `or` operators
  80143. */
  80144. var AndOrNotEvaluator = /** @class */ (function () {
  80145. function AndOrNotEvaluator() {
  80146. }
  80147. /**
  80148. * Evaluate a query
  80149. * @param query defines the query to evaluate
  80150. * @param evaluateCallback defines the callback used to filter result
  80151. * @returns true if the query matches
  80152. */
  80153. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  80154. if (!query.match(/\([^\(\)]*\)/g)) {
  80155. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  80156. }
  80157. else {
  80158. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  80159. // remove parenthesis
  80160. r = r.slice(1, r.length - 1);
  80161. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  80162. });
  80163. }
  80164. if (query === "true") {
  80165. return true;
  80166. }
  80167. if (query === "false") {
  80168. return false;
  80169. }
  80170. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  80171. };
  80172. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  80173. evaluateCallback = evaluateCallback || (function (r) {
  80174. return r === "true" ? true : false;
  80175. });
  80176. var result;
  80177. var or = parenthesisContent.split("||");
  80178. for (var i in or) {
  80179. if (or.hasOwnProperty(i)) {
  80180. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  80181. var and = ori.split("&&");
  80182. if (and.length > 1) {
  80183. for (var j = 0; j < and.length; ++j) {
  80184. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  80185. if (andj !== "true" && andj !== "false") {
  80186. if (andj[0] === "!") {
  80187. result = !evaluateCallback(andj.substring(1));
  80188. }
  80189. else {
  80190. result = evaluateCallback(andj);
  80191. }
  80192. }
  80193. else {
  80194. result = andj === "true" ? true : false;
  80195. }
  80196. if (!result) { // no need to continue since 'false && ... && ...' will always return false
  80197. ori = "false";
  80198. break;
  80199. }
  80200. }
  80201. }
  80202. if (result || ori === "true") { // no need to continue since 'true || ... || ...' will always return true
  80203. result = true;
  80204. break;
  80205. }
  80206. // result equals false (or undefined)
  80207. if (ori !== "true" && ori !== "false") {
  80208. if (ori[0] === "!") {
  80209. result = !evaluateCallback(ori.substring(1));
  80210. }
  80211. else {
  80212. result = evaluateCallback(ori);
  80213. }
  80214. }
  80215. else {
  80216. result = ori === "true" ? true : false;
  80217. }
  80218. }
  80219. }
  80220. // the whole parenthesis scope is replaced by 'true' or 'false'
  80221. return result ? "true" : "false";
  80222. };
  80223. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  80224. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  80225. // remove whitespaces
  80226. r = r.replace(/[\s]/g, function () { return ""; });
  80227. return r.length % 2 ? "!" : "";
  80228. });
  80229. booleanString = booleanString.trim();
  80230. if (booleanString === "!true") {
  80231. booleanString = "false";
  80232. }
  80233. else if (booleanString === "!false") {
  80234. booleanString = "true";
  80235. }
  80236. return booleanString;
  80237. };
  80238. return AndOrNotEvaluator;
  80239. }());
  80240. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  80241. })(BABYLON || (BABYLON = {}));
  80242. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  80243. var BABYLON;
  80244. (function (BABYLON) {
  80245. // Sets the default offline provider to Babylon.js
  80246. BABYLON.Engine.OfflineProviderFactory = function (urlToScene, callbackManifestChecked, disableManifestCheck) {
  80247. if (disableManifestCheck === void 0) { disableManifestCheck = false; }
  80248. return new Database(urlToScene, callbackManifestChecked, disableManifestCheck);
  80249. };
  80250. /**
  80251. * Class used to enable access to IndexedDB
  80252. * @see http://doc.babylonjs.com/how_to/caching_resources_in_indexeddb
  80253. */
  80254. var Database = /** @class */ (function () {
  80255. /**
  80256. * Creates a new Database
  80257. * @param urlToScene defines the url to load the scene
  80258. * @param callbackManifestChecked defines the callback to use when manifest is checked
  80259. * @param disableManifestCheck defines a boolean indicating that we want to skip the manifest validation (it will be considered validated and up to date)
  80260. */
  80261. function Database(urlToScene, callbackManifestChecked, disableManifestCheck) {
  80262. if (disableManifestCheck === void 0) { disableManifestCheck = false; }
  80263. var _this = this;
  80264. // Handling various flavors of prefixed version of IndexedDB
  80265. this._idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  80266. this._callbackManifestChecked = callbackManifestChecked;
  80267. this._currentSceneUrl = Database._ReturnFullUrlLocation(urlToScene);
  80268. this._db = null;
  80269. this._enableSceneOffline = false;
  80270. this._enableTexturesOffline = false;
  80271. this._manifestVersionFound = 0;
  80272. this._mustUpdateRessources = false;
  80273. this._hasReachedQuota = false;
  80274. if (!Database.IDBStorageEnabled) {
  80275. this._callbackManifestChecked(true);
  80276. }
  80277. else {
  80278. if (disableManifestCheck) {
  80279. this._enableSceneOffline = true;
  80280. this._enableTexturesOffline = true;
  80281. this._manifestVersionFound = 1;
  80282. BABYLON.Tools.SetImmediate(function () {
  80283. _this._callbackManifestChecked(true);
  80284. });
  80285. }
  80286. else {
  80287. this._checkManifestFile();
  80288. }
  80289. }
  80290. }
  80291. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  80292. /**
  80293. * Gets a boolean indicating if scene must be saved in the database
  80294. */
  80295. get: function () {
  80296. return this._enableSceneOffline;
  80297. },
  80298. enumerable: true,
  80299. configurable: true
  80300. });
  80301. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  80302. /**
  80303. * Gets a boolean indicating if textures must be saved in the database
  80304. */
  80305. get: function () {
  80306. return this._enableTexturesOffline;
  80307. },
  80308. enumerable: true,
  80309. configurable: true
  80310. });
  80311. Database.prototype._checkManifestFile = function () {
  80312. var _this = this;
  80313. var noManifestFile = function () {
  80314. _this._enableSceneOffline = false;
  80315. _this._enableTexturesOffline = false;
  80316. _this._callbackManifestChecked(false);
  80317. };
  80318. var timeStampUsed = false;
  80319. var manifestURL = this._currentSceneUrl + ".manifest";
  80320. var xhr = new XMLHttpRequest();
  80321. if (navigator.onLine) {
  80322. // Adding a timestamp to by-pass browsers' cache
  80323. timeStampUsed = true;
  80324. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + Date.now();
  80325. }
  80326. xhr.open("GET", manifestURL, true);
  80327. xhr.addEventListener("load", function () {
  80328. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  80329. try {
  80330. var manifestFile = JSON.parse(xhr.response);
  80331. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  80332. _this._enableTexturesOffline = manifestFile.enableTexturesOffline && Database.IsUASupportingBlobStorage;
  80333. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  80334. _this._manifestVersionFound = manifestFile.version;
  80335. }
  80336. if (_this._callbackManifestChecked) {
  80337. _this._callbackManifestChecked(true);
  80338. }
  80339. }
  80340. catch (ex) {
  80341. noManifestFile();
  80342. }
  80343. }
  80344. else {
  80345. noManifestFile();
  80346. }
  80347. }, false);
  80348. xhr.addEventListener("error", function (event) {
  80349. if (timeStampUsed) {
  80350. timeStampUsed = false;
  80351. // Let's retry without the timeStamp
  80352. // It could fail when coupled with HTML5 Offline API
  80353. var retryManifestURL = _this._currentSceneUrl + ".manifest";
  80354. xhr.open("GET", retryManifestURL, true);
  80355. if (BABYLON.Tools.UseCustomRequestHeaders) {
  80356. BABYLON.Tools.InjectCustomRequestHeaders(xhr);
  80357. }
  80358. xhr.send();
  80359. }
  80360. else {
  80361. noManifestFile();
  80362. }
  80363. }, false);
  80364. try {
  80365. if (BABYLON.Tools.UseCustomRequestHeaders) {
  80366. BABYLON.Tools.InjectCustomRequestHeaders(xhr);
  80367. }
  80368. xhr.send();
  80369. }
  80370. catch (ex) {
  80371. BABYLON.Tools.Error("Error on XHR send request.");
  80372. this._callbackManifestChecked(false);
  80373. }
  80374. };
  80375. /**
  80376. * Open the database and make it available
  80377. * @param successCallback defines the callback to call on success
  80378. * @param errorCallback defines the callback to call on error
  80379. */
  80380. Database.prototype.open = function (successCallback, errorCallback) {
  80381. var _this = this;
  80382. var handleError = function () {
  80383. _this._isSupported = false;
  80384. if (errorCallback) {
  80385. errorCallback();
  80386. }
  80387. };
  80388. if (!this._idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  80389. // Your browser doesn't support IndexedDB
  80390. this._isSupported = false;
  80391. if (errorCallback) {
  80392. errorCallback();
  80393. }
  80394. }
  80395. else {
  80396. // If the DB hasn't been opened or created yet
  80397. if (!this._db) {
  80398. this._hasReachedQuota = false;
  80399. this._isSupported = true;
  80400. var request = this._idbFactory.open("babylonjs", 1);
  80401. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  80402. request.onerror = function (event) {
  80403. handleError();
  80404. };
  80405. // executes when a version change transaction cannot complete due to other active transactions
  80406. request.onblocked = function (event) {
  80407. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  80408. handleError();
  80409. };
  80410. // DB has been opened successfully
  80411. request.onsuccess = function (event) {
  80412. _this._db = request.result;
  80413. successCallback();
  80414. };
  80415. // Initialization of the DB. Creating Scenes & Textures stores
  80416. request.onupgradeneeded = function (event) {
  80417. _this._db = (event.target).result;
  80418. if (_this._db) {
  80419. try {
  80420. _this._db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  80421. _this._db.createObjectStore("versions", { keyPath: "sceneUrl" });
  80422. _this._db.createObjectStore("textures", { keyPath: "textureUrl" });
  80423. }
  80424. catch (ex) {
  80425. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  80426. handleError();
  80427. }
  80428. }
  80429. };
  80430. }
  80431. // DB has already been created and opened
  80432. else {
  80433. if (successCallback) {
  80434. successCallback();
  80435. }
  80436. }
  80437. }
  80438. };
  80439. /**
  80440. * Loads an image from the database
  80441. * @param url defines the url to load from
  80442. * @param image defines the target DOM image
  80443. */
  80444. Database.prototype.loadImage = function (url, image) {
  80445. var _this = this;
  80446. var completeURL = Database._ReturnFullUrlLocation(url);
  80447. var saveAndLoadImage = function () {
  80448. if (!_this._hasReachedQuota && _this._db !== null) {
  80449. // the texture is not yet in the DB, let's try to save it
  80450. _this._saveImageIntoDBAsync(completeURL, image);
  80451. }
  80452. // If the texture is not in the DB and we've reached the DB quota limit
  80453. // let's load it directly from the web
  80454. else {
  80455. image.src = url;
  80456. }
  80457. };
  80458. if (!this._mustUpdateRessources) {
  80459. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  80460. }
  80461. // First time we're download the images or update requested in the manifest file by a version change
  80462. else {
  80463. saveAndLoadImage();
  80464. }
  80465. };
  80466. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  80467. if (this._isSupported && this._db !== null) {
  80468. var texture;
  80469. var transaction = this._db.transaction(["textures"]);
  80470. transaction.onabort = function (event) {
  80471. image.src = url;
  80472. };
  80473. transaction.oncomplete = function (event) {
  80474. var blobTextureURL;
  80475. if (texture) {
  80476. var URL = window.URL || window.webkitURL;
  80477. blobTextureURL = URL.createObjectURL(texture.data);
  80478. image.onerror = function () {
  80479. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  80480. image.src = url;
  80481. };
  80482. image.src = blobTextureURL;
  80483. }
  80484. else {
  80485. notInDBCallback();
  80486. }
  80487. };
  80488. var getRequest = transaction.objectStore("textures").get(url);
  80489. getRequest.onsuccess = function (event) {
  80490. texture = (event.target).result;
  80491. };
  80492. getRequest.onerror = function (event) {
  80493. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  80494. image.src = url;
  80495. };
  80496. }
  80497. else {
  80498. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  80499. image.src = url;
  80500. }
  80501. };
  80502. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  80503. var _this = this;
  80504. if (this._isSupported) {
  80505. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  80506. var generateBlobUrl = function () {
  80507. var blobTextureURL;
  80508. if (blob) {
  80509. var URL = window.URL || window.webkitURL;
  80510. try {
  80511. blobTextureURL = URL.createObjectURL(blob);
  80512. }
  80513. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  80514. catch (ex) {
  80515. blobTextureURL = URL.createObjectURL(blob);
  80516. }
  80517. }
  80518. if (blobTextureURL) {
  80519. image.src = blobTextureURL;
  80520. }
  80521. };
  80522. if (Database.IsUASupportingBlobStorage) { // Create XHR
  80523. var xhr = new XMLHttpRequest(), blob;
  80524. xhr.open("GET", url, true);
  80525. xhr.responseType = "blob";
  80526. xhr.addEventListener("load", function () {
  80527. if (xhr.status === 200 && _this._db) {
  80528. // Blob as response (XHR2)
  80529. blob = xhr.response;
  80530. var transaction = _this._db.transaction(["textures"], "readwrite");
  80531. // the transaction could abort because of a QuotaExceededError error
  80532. transaction.onabort = function (event) {
  80533. try {
  80534. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  80535. var srcElement = (event.srcElement || event.target);
  80536. var error = srcElement.error;
  80537. if (error && error.name === "QuotaExceededError") {
  80538. _this._hasReachedQuota = true;
  80539. }
  80540. }
  80541. catch (ex) { }
  80542. generateBlobUrl();
  80543. };
  80544. transaction.oncomplete = function (event) {
  80545. generateBlobUrl();
  80546. };
  80547. var newTexture = { textureUrl: url, data: blob };
  80548. try {
  80549. // Put the blob into the dabase
  80550. var addRequest = transaction.objectStore("textures").put(newTexture);
  80551. addRequest.onsuccess = function (event) {
  80552. };
  80553. addRequest.onerror = function (event) {
  80554. generateBlobUrl();
  80555. };
  80556. }
  80557. catch (ex) {
  80558. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  80559. if (ex.code === 25) {
  80560. Database.IsUASupportingBlobStorage = false;
  80561. _this._enableTexturesOffline = false;
  80562. }
  80563. image.src = url;
  80564. }
  80565. }
  80566. else {
  80567. image.src = url;
  80568. }
  80569. }, false);
  80570. xhr.addEventListener("error", function (event) {
  80571. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  80572. image.src = url;
  80573. }, false);
  80574. if (BABYLON.Tools.CustomRequestHeaders) {
  80575. BABYLON.Tools.InjectCustomRequestHeaders(xhr);
  80576. }
  80577. xhr.send();
  80578. }
  80579. else {
  80580. image.src = url;
  80581. }
  80582. }
  80583. else {
  80584. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  80585. image.src = url;
  80586. }
  80587. };
  80588. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  80589. var _this = this;
  80590. var updateVersion = function () {
  80591. // the version is not yet in the DB or we need to update it
  80592. _this._saveVersionIntoDBAsync(url, versionLoaded);
  80593. };
  80594. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  80595. };
  80596. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  80597. var _this = this;
  80598. if (this._isSupported && this._db) {
  80599. var version;
  80600. try {
  80601. var transaction = this._db.transaction(["versions"]);
  80602. transaction.oncomplete = function (event) {
  80603. if (version) {
  80604. // If the version in the JSON file is different from the version in DB
  80605. if (_this._manifestVersionFound !== version.data) {
  80606. _this._mustUpdateRessources = true;
  80607. updateInDBCallback();
  80608. }
  80609. else {
  80610. callback(version.data);
  80611. }
  80612. }
  80613. // version was not found in DB
  80614. else {
  80615. _this._mustUpdateRessources = true;
  80616. updateInDBCallback();
  80617. }
  80618. };
  80619. transaction.onabort = function (event) {
  80620. callback(-1);
  80621. };
  80622. var getRequest = transaction.objectStore("versions").get(url);
  80623. getRequest.onsuccess = function (event) {
  80624. version = (event.target).result;
  80625. };
  80626. getRequest.onerror = function (event) {
  80627. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  80628. callback(-1);
  80629. };
  80630. }
  80631. catch (ex) {
  80632. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  80633. callback(-1);
  80634. }
  80635. }
  80636. else {
  80637. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  80638. callback(-1);
  80639. }
  80640. };
  80641. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  80642. var _this = this;
  80643. if (this._isSupported && !this._hasReachedQuota && this._db) {
  80644. try {
  80645. // Open a transaction to the database
  80646. var transaction = this._db.transaction(["versions"], "readwrite");
  80647. // the transaction could abort because of a QuotaExceededError error
  80648. transaction.onabort = function (event) {
  80649. try { //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  80650. var error = event.srcElement['error'];
  80651. if (error && error.name === "QuotaExceededError") {
  80652. _this._hasReachedQuota = true;
  80653. }
  80654. }
  80655. catch (ex) { }
  80656. callback(-1);
  80657. };
  80658. transaction.oncomplete = function (event) {
  80659. callback(_this._manifestVersionFound);
  80660. };
  80661. var newVersion = { sceneUrl: url, data: this._manifestVersionFound };
  80662. // Put the scene into the database
  80663. var addRequest = transaction.objectStore("versions").put(newVersion);
  80664. addRequest.onsuccess = function (event) {
  80665. };
  80666. addRequest.onerror = function (event) {
  80667. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  80668. };
  80669. }
  80670. catch (ex) {
  80671. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  80672. callback(-1);
  80673. }
  80674. }
  80675. else {
  80676. callback(-1);
  80677. }
  80678. };
  80679. /**
  80680. * Loads a file from database
  80681. * @param url defines the URL to load from
  80682. * @param sceneLoaded defines a callback to call on success
  80683. * @param progressCallBack defines a callback to call when progress changed
  80684. * @param errorCallback defines a callback to call on error
  80685. * @param useArrayBuffer defines a boolean to use array buffer instead of text string
  80686. */
  80687. Database.prototype.loadFile = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  80688. var _this = this;
  80689. var completeUrl = Database._ReturnFullUrlLocation(url);
  80690. var saveAndLoadFile = function () {
  80691. // the scene is not yet in the DB, let's try to save it
  80692. _this._saveFileAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
  80693. };
  80694. this._checkVersionFromDB(completeUrl, function (version) {
  80695. if (version !== -1) {
  80696. if (!_this._mustUpdateRessources) {
  80697. _this._loadFileAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  80698. }
  80699. else {
  80700. _this._saveFileAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
  80701. }
  80702. }
  80703. else {
  80704. if (errorCallback) {
  80705. errorCallback();
  80706. }
  80707. }
  80708. });
  80709. };
  80710. Database.prototype._loadFileAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  80711. if (this._isSupported && this._db) {
  80712. var targetStore;
  80713. if (url.indexOf(".babylon") !== -1) {
  80714. targetStore = "scenes";
  80715. }
  80716. else {
  80717. targetStore = "textures";
  80718. }
  80719. var file;
  80720. var transaction = this._db.transaction([targetStore]);
  80721. transaction.oncomplete = function (event) {
  80722. if (file) {
  80723. callback(file.data);
  80724. }
  80725. // file was not found in DB
  80726. else {
  80727. notInDBCallback();
  80728. }
  80729. };
  80730. transaction.onabort = function (event) {
  80731. notInDBCallback();
  80732. };
  80733. var getRequest = transaction.objectStore(targetStore).get(url);
  80734. getRequest.onsuccess = function (event) {
  80735. file = (event.target).result;
  80736. };
  80737. getRequest.onerror = function (event) {
  80738. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  80739. notInDBCallback();
  80740. };
  80741. }
  80742. else {
  80743. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  80744. callback();
  80745. }
  80746. };
  80747. Database.prototype._saveFileAsync = function (url, callback, progressCallback, useArrayBuffer, errorCallback) {
  80748. var _this = this;
  80749. if (this._isSupported) {
  80750. var targetStore;
  80751. if (url.indexOf(".babylon") !== -1) {
  80752. targetStore = "scenes";
  80753. }
  80754. else {
  80755. targetStore = "textures";
  80756. }
  80757. // Create XHR
  80758. var xhr = new XMLHttpRequest();
  80759. var fileData;
  80760. xhr.open("GET", url + "?" + Date.now(), true);
  80761. if (useArrayBuffer) {
  80762. xhr.responseType = "arraybuffer";
  80763. }
  80764. if (progressCallback) {
  80765. xhr.onprogress = progressCallback;
  80766. }
  80767. xhr.addEventListener("load", function () {
  80768. if (xhr.status === 200 || (xhr.status < 400 && BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6))) {
  80769. // Blob as response (XHR2)
  80770. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  80771. if (!_this._hasReachedQuota && _this._db) {
  80772. // Open a transaction to the database
  80773. var transaction = _this._db.transaction([targetStore], "readwrite");
  80774. // the transaction could abort because of a QuotaExceededError error
  80775. transaction.onabort = function (event) {
  80776. try {
  80777. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  80778. var error = event.srcElement['error'];
  80779. if (error && error.name === "QuotaExceededError") {
  80780. _this._hasReachedQuota = true;
  80781. }
  80782. }
  80783. catch (ex) { }
  80784. callback(fileData);
  80785. };
  80786. transaction.oncomplete = function (event) {
  80787. callback(fileData);
  80788. };
  80789. var newFile;
  80790. if (targetStore === "scenes") {
  80791. newFile = { sceneUrl: url, data: fileData, version: _this._manifestVersionFound };
  80792. }
  80793. else {
  80794. newFile = { textureUrl: url, data: fileData };
  80795. }
  80796. try {
  80797. // Put the scene into the database
  80798. var addRequest = transaction.objectStore(targetStore).put(newFile);
  80799. addRequest.onsuccess = function (event) {
  80800. };
  80801. addRequest.onerror = function (event) {
  80802. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  80803. };
  80804. }
  80805. catch (ex) {
  80806. callback(fileData);
  80807. }
  80808. }
  80809. else {
  80810. callback(fileData);
  80811. }
  80812. }
  80813. else {
  80814. if (xhr.status >= 400 && errorCallback) {
  80815. errorCallback(xhr);
  80816. }
  80817. else {
  80818. callback();
  80819. }
  80820. }
  80821. }, false);
  80822. xhr.addEventListener("error", function (event) {
  80823. BABYLON.Tools.Error("error on XHR request.");
  80824. callback();
  80825. }, false);
  80826. if (BABYLON.Tools.UseCustomRequestHeaders) {
  80827. BABYLON.Tools.InjectCustomRequestHeaders(xhr);
  80828. }
  80829. xhr.send();
  80830. }
  80831. else {
  80832. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or Babylon.js Database is not open.");
  80833. callback();
  80834. }
  80835. };
  80836. /** Gets a boolean indicating if the user agent supports blob storage (this value will be updated after creating the first Database object) */
  80837. Database.IsUASupportingBlobStorage = true;
  80838. /**
  80839. * Gets a boolean indicating if Database storate is enabled (off by default)
  80840. */
  80841. Database.IDBStorageEnabled = false;
  80842. Database._ParseURL = function (url) {
  80843. var a = document.createElement('a');
  80844. a.href = url;
  80845. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  80846. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  80847. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  80848. return absLocation;
  80849. };
  80850. Database._ReturnFullUrlLocation = function (url) {
  80851. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  80852. return (Database._ParseURL(window.location.href) + url);
  80853. }
  80854. else {
  80855. return url;
  80856. }
  80857. };
  80858. return Database;
  80859. }());
  80860. BABYLON.Database = Database;
  80861. })(BABYLON || (BABYLON = {}));
  80862. //# sourceMappingURL=babylon.database.js.map
  80863. var BABYLON;
  80864. (function (BABYLON) {
  80865. /**
  80866. * This represents all the required information to add a fresnel effect on a material:
  80867. * @see http://doc.babylonjs.com/how_to/how_to_use_fresnelparameters
  80868. */
  80869. var FresnelParameters = /** @class */ (function () {
  80870. function FresnelParameters() {
  80871. this._isEnabled = true;
  80872. /**
  80873. * Define the color used on edges (grazing angle)
  80874. */
  80875. this.leftColor = BABYLON.Color3.White();
  80876. /**
  80877. * Define the color used on center
  80878. */
  80879. this.rightColor = BABYLON.Color3.Black();
  80880. /**
  80881. * Define bias applied to computed fresnel term
  80882. */
  80883. this.bias = 0;
  80884. /**
  80885. * Defined the power exponent applied to fresnel term
  80886. */
  80887. this.power = 1;
  80888. }
  80889. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  80890. /**
  80891. * Define if the fresnel effect is enable or not.
  80892. */
  80893. get: function () {
  80894. return this._isEnabled;
  80895. },
  80896. set: function (value) {
  80897. if (this._isEnabled === value) {
  80898. return;
  80899. }
  80900. this._isEnabled = value;
  80901. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  80902. },
  80903. enumerable: true,
  80904. configurable: true
  80905. });
  80906. /**
  80907. * Clones the current fresnel and its valuues
  80908. * @returns a clone fresnel configuration
  80909. */
  80910. FresnelParameters.prototype.clone = function () {
  80911. var newFresnelParameters = new FresnelParameters();
  80912. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  80913. return newFresnelParameters;
  80914. };
  80915. /**
  80916. * Serializes the current fresnel parameters to a JSON representation.
  80917. * @return the JSON serialization
  80918. */
  80919. FresnelParameters.prototype.serialize = function () {
  80920. var serializationObject = {};
  80921. serializationObject.isEnabled = this.isEnabled;
  80922. serializationObject.leftColor = this.leftColor.asArray();
  80923. serializationObject.rightColor = this.rightColor.asArray();
  80924. serializationObject.bias = this.bias;
  80925. serializationObject.power = this.power;
  80926. return serializationObject;
  80927. };
  80928. /**
  80929. * Parse a JSON object and deserialize it to a new Fresnel parameter object.
  80930. * @param parsedFresnelParameters Define the JSON representation
  80931. * @returns the parsed parameters
  80932. */
  80933. FresnelParameters.Parse = function (parsedFresnelParameters) {
  80934. var fresnelParameters = new FresnelParameters();
  80935. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  80936. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  80937. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  80938. fresnelParameters.bias = parsedFresnelParameters.bias;
  80939. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  80940. return fresnelParameters;
  80941. };
  80942. return FresnelParameters;
  80943. }());
  80944. BABYLON.FresnelParameters = FresnelParameters;
  80945. })(BABYLON || (BABYLON = {}));
  80946. //# sourceMappingURL=babylon.fresnelParameters.js.map
  80947. var BABYLON;
  80948. (function (BABYLON) {
  80949. /**
  80950. * A multi-material is used to apply different materials to different parts of the same object without the need of
  80951. * separate meshes. This can be use to improve performances.
  80952. * @see http://doc.babylonjs.com/how_to/multi_materials
  80953. */
  80954. var MultiMaterial = /** @class */ (function (_super) {
  80955. __extends(MultiMaterial, _super);
  80956. /**
  80957. * Instantiates a new Multi Material
  80958. * A multi-material is used to apply different materials to different parts of the same object without the need of
  80959. * separate meshes. This can be use to improve performances.
  80960. * @see http://doc.babylonjs.com/how_to/multi_materials
  80961. * @param name Define the name in the scene
  80962. * @param scene Define the scene the material belongs to
  80963. */
  80964. function MultiMaterial(name, scene) {
  80965. var _this = _super.call(this, name, scene, true) || this;
  80966. scene.multiMaterials.push(_this);
  80967. _this.subMaterials = new Array();
  80968. _this._storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  80969. return _this;
  80970. }
  80971. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  80972. /**
  80973. * Gets or Sets the list of Materials used within the multi material.
  80974. * They need to be ordered according to the submeshes order in the associated mesh
  80975. */
  80976. get: function () {
  80977. return this._subMaterials;
  80978. },
  80979. set: function (value) {
  80980. this._subMaterials = value;
  80981. this._hookArray(value);
  80982. },
  80983. enumerable: true,
  80984. configurable: true
  80985. });
  80986. /**
  80987. * Function used to align with Node.getChildren()
  80988. * @returns the list of Materials used within the multi material
  80989. */
  80990. MultiMaterial.prototype.getChildren = function () {
  80991. return this.subMaterials;
  80992. };
  80993. MultiMaterial.prototype._hookArray = function (array) {
  80994. var _this = this;
  80995. var oldPush = array.push;
  80996. array.push = function () {
  80997. var items = [];
  80998. for (var _i = 0; _i < arguments.length; _i++) {
  80999. items[_i] = arguments[_i];
  81000. }
  81001. var result = oldPush.apply(array, items);
  81002. _this._markAllSubMeshesAsTexturesDirty();
  81003. return result;
  81004. };
  81005. var oldSplice = array.splice;
  81006. array.splice = function (index, deleteCount) {
  81007. var deleted = oldSplice.apply(array, [index, deleteCount]);
  81008. _this._markAllSubMeshesAsTexturesDirty();
  81009. return deleted;
  81010. };
  81011. };
  81012. /**
  81013. * Get one of the submaterial by its index in the submaterials array
  81014. * @param index The index to look the sub material at
  81015. * @returns The Material if the index has been defined
  81016. */
  81017. MultiMaterial.prototype.getSubMaterial = function (index) {
  81018. if (index < 0 || index >= this.subMaterials.length) {
  81019. return this.getScene().defaultMaterial;
  81020. }
  81021. return this.subMaterials[index];
  81022. };
  81023. /**
  81024. * Get the list of active textures for the whole sub materials list.
  81025. * @returns All the textures that will be used during the rendering
  81026. */
  81027. MultiMaterial.prototype.getActiveTextures = function () {
  81028. var _a;
  81029. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  81030. if (subMaterial) {
  81031. return subMaterial.getActiveTextures();
  81032. }
  81033. else {
  81034. return [];
  81035. }
  81036. }));
  81037. };
  81038. /**
  81039. * Gets the current class name of the material e.g. "MultiMaterial"
  81040. * Mainly use in serialization.
  81041. * @returns the class name
  81042. */
  81043. MultiMaterial.prototype.getClassName = function () {
  81044. return "MultiMaterial";
  81045. };
  81046. /**
  81047. * Checks if the material is ready to render the requested sub mesh
  81048. * @param mesh Define the mesh the submesh belongs to
  81049. * @param subMesh Define the sub mesh to look readyness for
  81050. * @param useInstances Define whether or not the material is used with instances
  81051. * @returns true if ready, otherwise false
  81052. */
  81053. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  81054. for (var index = 0; index < this.subMaterials.length; index++) {
  81055. var subMaterial = this.subMaterials[index];
  81056. if (subMaterial) {
  81057. if (subMaterial._storeEffectOnSubMeshes) {
  81058. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  81059. return false;
  81060. }
  81061. continue;
  81062. }
  81063. if (!subMaterial.isReady(mesh)) {
  81064. return false;
  81065. }
  81066. }
  81067. }
  81068. return true;
  81069. };
  81070. /**
  81071. * Clones the current material and its related sub materials
  81072. * @param name Define the name of the newly cloned material
  81073. * @param cloneChildren Define if submaterial will be cloned or shared with the parent instance
  81074. * @returns the cloned material
  81075. */
  81076. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  81077. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  81078. for (var index = 0; index < this.subMaterials.length; index++) {
  81079. var subMaterial = null;
  81080. var current = this.subMaterials[index];
  81081. if (cloneChildren && current) {
  81082. subMaterial = current.clone(name + "-" + current.name);
  81083. }
  81084. else {
  81085. subMaterial = this.subMaterials[index];
  81086. }
  81087. newMultiMaterial.subMaterials.push(subMaterial);
  81088. }
  81089. return newMultiMaterial;
  81090. };
  81091. /**
  81092. * Serializes the materials into a JSON representation.
  81093. * @returns the JSON representation
  81094. */
  81095. MultiMaterial.prototype.serialize = function () {
  81096. var serializationObject = {};
  81097. serializationObject.name = this.name;
  81098. serializationObject.id = this.id;
  81099. if (BABYLON.Tags) {
  81100. serializationObject.tags = BABYLON.Tags.GetTags(this);
  81101. }
  81102. serializationObject.materials = [];
  81103. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  81104. var subMat = this.subMaterials[matIndex];
  81105. if (subMat) {
  81106. serializationObject.materials.push(subMat.id);
  81107. }
  81108. else {
  81109. serializationObject.materials.push(null);
  81110. }
  81111. }
  81112. return serializationObject;
  81113. };
  81114. /**
  81115. * Dispose the material and release its associated resources
  81116. * @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)
  81117. * @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)
  81118. */
  81119. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  81120. var scene = this.getScene();
  81121. if (!scene) {
  81122. return;
  81123. }
  81124. var index = scene.multiMaterials.indexOf(this);
  81125. if (index >= 0) {
  81126. scene.multiMaterials.splice(index, 1);
  81127. }
  81128. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  81129. };
  81130. return MultiMaterial;
  81131. }(BABYLON.Material));
  81132. BABYLON.MultiMaterial = MultiMaterial;
  81133. })(BABYLON || (BABYLON = {}));
  81134. //# sourceMappingURL=babylon.multiMaterial.js.map
  81135. var BABYLON;
  81136. (function (BABYLON) {
  81137. /**
  81138. * Manage the touch inputs to control the movement of a free camera.
  81139. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  81140. */
  81141. var FreeCameraTouchInput = /** @class */ (function () {
  81142. function FreeCameraTouchInput() {
  81143. /**
  81144. * Defines the touch sensibility for rotation.
  81145. * The higher the faster.
  81146. */
  81147. this.touchAngularSensibility = 200000.0;
  81148. /**
  81149. * Defines the touch sensibility for move.
  81150. * The higher the faster.
  81151. */
  81152. this.touchMoveSensibility = 250.0;
  81153. this._offsetX = null;
  81154. this._offsetY = null;
  81155. this._pointerPressed = new Array();
  81156. }
  81157. /**
  81158. * Attach the input controls to a specific dom element to get the input from.
  81159. * @param element Defines the element the controls should be listened from
  81160. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  81161. */
  81162. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  81163. var _this = this;
  81164. var previousPosition = null;
  81165. if (this._pointerInput === undefined) {
  81166. this._onLostFocus = function (evt) {
  81167. _this._offsetX = null;
  81168. _this._offsetY = null;
  81169. };
  81170. this._pointerInput = function (p, s) {
  81171. var evt = p.event;
  81172. if (evt.pointerType === "mouse") {
  81173. return;
  81174. }
  81175. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  81176. if (!noPreventDefault) {
  81177. evt.preventDefault();
  81178. }
  81179. _this._pointerPressed.push(evt.pointerId);
  81180. if (_this._pointerPressed.length !== 1) {
  81181. return;
  81182. }
  81183. previousPosition = {
  81184. x: evt.clientX,
  81185. y: evt.clientY
  81186. };
  81187. }
  81188. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  81189. if (!noPreventDefault) {
  81190. evt.preventDefault();
  81191. }
  81192. var index = _this._pointerPressed.indexOf(evt.pointerId);
  81193. if (index === -1) {
  81194. return;
  81195. }
  81196. _this._pointerPressed.splice(index, 1);
  81197. if (index != 0) {
  81198. return;
  81199. }
  81200. previousPosition = null;
  81201. _this._offsetX = null;
  81202. _this._offsetY = null;
  81203. }
  81204. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  81205. if (!noPreventDefault) {
  81206. evt.preventDefault();
  81207. }
  81208. if (!previousPosition) {
  81209. return;
  81210. }
  81211. var index = _this._pointerPressed.indexOf(evt.pointerId);
  81212. if (index != 0) {
  81213. return;
  81214. }
  81215. _this._offsetX = evt.clientX - previousPosition.x;
  81216. _this._offsetY = -(evt.clientY - previousPosition.y);
  81217. }
  81218. };
  81219. }
  81220. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  81221. if (this._onLostFocus) {
  81222. element.addEventListener("blur", this._onLostFocus);
  81223. }
  81224. };
  81225. /**
  81226. * Detach the current controls from the specified dom element.
  81227. * @param element Defines the element to stop listening the inputs from
  81228. */
  81229. FreeCameraTouchInput.prototype.detachControl = function (element) {
  81230. if (this._pointerInput && element) {
  81231. if (this._observer) {
  81232. this.camera.getScene().onPointerObservable.remove(this._observer);
  81233. this._observer = null;
  81234. }
  81235. if (this._onLostFocus) {
  81236. element.removeEventListener("blur", this._onLostFocus);
  81237. this._onLostFocus = null;
  81238. }
  81239. this._pointerPressed = [];
  81240. this._offsetX = null;
  81241. this._offsetY = null;
  81242. }
  81243. };
  81244. /**
  81245. * Update the current camera state depending on the inputs that have been used this frame.
  81246. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  81247. */
  81248. FreeCameraTouchInput.prototype.checkInputs = function () {
  81249. if (this._offsetX && this._offsetY) {
  81250. var camera = this.camera;
  81251. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  81252. if (this._pointerPressed.length > 1) {
  81253. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  81254. }
  81255. else {
  81256. var speed = camera._computeLocalCameraSpeed();
  81257. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  81258. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  81259. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  81260. }
  81261. }
  81262. };
  81263. /**
  81264. * Gets the class name of the current intput.
  81265. * @returns the class name
  81266. */
  81267. FreeCameraTouchInput.prototype.getClassName = function () {
  81268. return "FreeCameraTouchInput";
  81269. };
  81270. /**
  81271. * Get the friendly name associated with the input class.
  81272. * @returns the input friendly name
  81273. */
  81274. FreeCameraTouchInput.prototype.getSimpleName = function () {
  81275. return "touch";
  81276. };
  81277. __decorate([
  81278. BABYLON.serialize()
  81279. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  81280. __decorate([
  81281. BABYLON.serialize()
  81282. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  81283. return FreeCameraTouchInput;
  81284. }());
  81285. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  81286. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  81287. })(BABYLON || (BABYLON = {}));
  81288. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  81289. var BABYLON;
  81290. (function (BABYLON) {
  81291. BABYLON.Node.AddNodeConstructor("TouchCamera", function (name, scene) {
  81292. return function () { return new TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  81293. });
  81294. /**
  81295. * This represents a FPS type of camera controlled by touch.
  81296. * This is like a universal camera minus the Gamepad controls.
  81297. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  81298. */
  81299. var TouchCamera = /** @class */ (function (_super) {
  81300. __extends(TouchCamera, _super);
  81301. /**
  81302. * Instantiates a new touch camera.
  81303. * This represents a FPS type of camera controlled by touch.
  81304. * This is like a universal camera minus the Gamepad controls.
  81305. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  81306. * @param name Define the name of the camera in the scene
  81307. * @param position Define the start position of the camera in the scene
  81308. * @param scene Define the scene the camera belongs to
  81309. */
  81310. function TouchCamera(name, position, scene) {
  81311. var _this = _super.call(this, name, position, scene) || this;
  81312. _this.inputs.addTouch();
  81313. _this._setupInputs();
  81314. return _this;
  81315. }
  81316. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  81317. /**
  81318. * Defines the touch sensibility for rotation.
  81319. * The higher the faster.
  81320. */
  81321. get: function () {
  81322. var touch = this.inputs.attached["touch"];
  81323. if (touch) {
  81324. return touch.touchAngularSensibility;
  81325. }
  81326. return 0;
  81327. },
  81328. set: function (value) {
  81329. var touch = this.inputs.attached["touch"];
  81330. if (touch) {
  81331. touch.touchAngularSensibility = value;
  81332. }
  81333. },
  81334. enumerable: true,
  81335. configurable: true
  81336. });
  81337. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  81338. /**
  81339. * Defines the touch sensibility for move.
  81340. * The higher the faster.
  81341. */
  81342. get: function () {
  81343. var touch = this.inputs.attached["touch"];
  81344. if (touch) {
  81345. return touch.touchMoveSensibility;
  81346. }
  81347. return 0;
  81348. },
  81349. set: function (value) {
  81350. var touch = this.inputs.attached["touch"];
  81351. if (touch) {
  81352. touch.touchMoveSensibility = value;
  81353. }
  81354. },
  81355. enumerable: true,
  81356. configurable: true
  81357. });
  81358. /**
  81359. * Gets the current object class name.
  81360. * @return the class name
  81361. */
  81362. TouchCamera.prototype.getClassName = function () {
  81363. return "TouchCamera";
  81364. };
  81365. /** @hidden */
  81366. TouchCamera.prototype._setupInputs = function () {
  81367. var mouse = this.inputs.attached["mouse"];
  81368. if (mouse) {
  81369. mouse.touchEnabled = false;
  81370. }
  81371. };
  81372. return TouchCamera;
  81373. }(BABYLON.FreeCamera));
  81374. BABYLON.TouchCamera = TouchCamera;
  81375. })(BABYLON || (BABYLON = {}));
  81376. //# sourceMappingURL=babylon.touchCamera.js.map
  81377. var BABYLON;
  81378. (function (BABYLON) {
  81379. /**
  81380. * 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.
  81381. * This is the base class of any Procedural texture and contains most of the shareable code.
  81382. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  81383. */
  81384. var ProceduralTexture = /** @class */ (function (_super) {
  81385. __extends(ProceduralTexture, _super);
  81386. /**
  81387. * Instantiates a new procedural texture.
  81388. * 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.
  81389. * This is the base class of any Procedural texture and contains most of the shareable code.
  81390. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  81391. * @param name Define the name of the texture
  81392. * @param size Define the size of the texture to create
  81393. * @param fragment Define the fragment shader to use to generate the texture or null if it is defined later
  81394. * @param scene Define the scene the texture belongs to
  81395. * @param fallbackTexture Define a fallback texture in case there were issues to create the custom texture
  81396. * @param generateMipMaps Define if the texture should creates mip maps or not
  81397. * @param isCube Define if the texture is a cube texture or not (this will render each faces of the cube)
  81398. */
  81399. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  81400. if (fallbackTexture === void 0) { fallbackTexture = null; }
  81401. if (generateMipMaps === void 0) { generateMipMaps = true; }
  81402. if (isCube === void 0) { isCube = false; }
  81403. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  81404. _this.isCube = isCube;
  81405. /**
  81406. * Define if the texture is enabled or not (disabled texture will not render)
  81407. */
  81408. _this.isEnabled = true;
  81409. /**
  81410. * Define if the texture must be cleared before rendering (default is true)
  81411. */
  81412. _this.autoClear = true;
  81413. /**
  81414. * Event raised when the texture is generated
  81415. */
  81416. _this.onGeneratedObservable = new BABYLON.Observable();
  81417. /** @hidden */
  81418. _this._textures = {};
  81419. _this._currentRefreshId = -1;
  81420. _this._refreshRate = 1;
  81421. _this._vertexBuffers = {};
  81422. _this._uniforms = new Array();
  81423. _this._samplers = new Array();
  81424. _this._floats = {};
  81425. _this._ints = {};
  81426. _this._floatsArrays = {};
  81427. _this._colors3 = {};
  81428. _this._colors4 = {};
  81429. _this._vectors2 = {};
  81430. _this._vectors3 = {};
  81431. _this._matrices = {};
  81432. _this._fallbackTextureUsed = false;
  81433. _this._cachedDefines = "";
  81434. _this._contentUpdateId = -1;
  81435. scene = _this.getScene();
  81436. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_PROCEDURALTEXTURE);
  81437. if (!component) {
  81438. component = new BABYLON.ProceduralTextureSceneComponent(scene);
  81439. scene._addComponent(component);
  81440. }
  81441. scene.proceduralTextures.push(_this);
  81442. _this._engine = scene.getEngine();
  81443. _this.name = name;
  81444. _this.isRenderTarget = true;
  81445. _this._size = size;
  81446. _this._generateMipMaps = generateMipMaps;
  81447. _this.setFragment(fragment);
  81448. _this._fallbackTexture = fallbackTexture;
  81449. if (isCube) {
  81450. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps, generateDepthBuffer: false, generateStencilBuffer: false });
  81451. _this.setFloat("face", 0);
  81452. }
  81453. else {
  81454. _this._texture = _this._engine.createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, generateDepthBuffer: false, generateStencilBuffer: false });
  81455. }
  81456. // VBO
  81457. var vertices = [];
  81458. vertices.push(1, 1);
  81459. vertices.push(-1, 1);
  81460. vertices.push(-1, -1);
  81461. vertices.push(1, -1);
  81462. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  81463. _this._createIndexBuffer();
  81464. return _this;
  81465. }
  81466. /**
  81467. * The effect that is created when initializing the post process.
  81468. * @returns The created effect corrisponding the the postprocess.
  81469. */
  81470. ProceduralTexture.prototype.getEffect = function () {
  81471. return this._effect;
  81472. };
  81473. /**
  81474. * Gets texture content (Use this function wisely as reading from a texture can be slow)
  81475. * @returns an ArrayBufferView (Uint8Array or Float32Array)
  81476. */
  81477. ProceduralTexture.prototype.getContent = function () {
  81478. if (this._contentData && this._currentRefreshId == this._contentUpdateId) {
  81479. return this._contentData;
  81480. }
  81481. this._contentData = this.readPixels(0, 0, this._contentData);
  81482. this._contentUpdateId = this._currentRefreshId;
  81483. return this._contentData;
  81484. };
  81485. ProceduralTexture.prototype._createIndexBuffer = function () {
  81486. var engine = this._engine;
  81487. // Indices
  81488. var indices = [];
  81489. indices.push(0);
  81490. indices.push(1);
  81491. indices.push(2);
  81492. indices.push(0);
  81493. indices.push(2);
  81494. indices.push(3);
  81495. this._indexBuffer = engine.createIndexBuffer(indices);
  81496. };
  81497. /** @hidden */
  81498. ProceduralTexture.prototype._rebuild = function () {
  81499. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  81500. if (vb) {
  81501. vb._rebuild();
  81502. }
  81503. this._createIndexBuffer();
  81504. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  81505. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  81506. }
  81507. };
  81508. /**
  81509. * Resets the texture in order to recreate its associated resources.
  81510. * This can be called in case of context loss
  81511. */
  81512. ProceduralTexture.prototype.reset = function () {
  81513. if (this._effect === undefined) {
  81514. return;
  81515. }
  81516. var engine = this._engine;
  81517. engine._releaseEffect(this._effect);
  81518. };
  81519. ProceduralTexture.prototype._getDefines = function () {
  81520. return "";
  81521. };
  81522. /**
  81523. * Is the texture ready to be used ? (rendered at least once)
  81524. * @returns true if ready, otherwise, false.
  81525. */
  81526. ProceduralTexture.prototype.isReady = function () {
  81527. var _this = this;
  81528. var engine = this._engine;
  81529. var shaders;
  81530. if (!this._fragment) {
  81531. return false;
  81532. }
  81533. if (this._fallbackTextureUsed) {
  81534. return true;
  81535. }
  81536. var defines = this._getDefines();
  81537. if (this._effect && defines === this._cachedDefines && this._effect.isReady()) {
  81538. return true;
  81539. }
  81540. if (this._fragment.fragmentElement !== undefined) {
  81541. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  81542. }
  81543. else {
  81544. shaders = { vertex: "procedural", fragment: this._fragment };
  81545. }
  81546. this._cachedDefines = defines;
  81547. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, defines, undefined, undefined, function () {
  81548. _this.releaseInternalTexture();
  81549. if (_this._fallbackTexture) {
  81550. _this._texture = _this._fallbackTexture._texture;
  81551. if (_this._texture) {
  81552. _this._texture.incrementReferences();
  81553. }
  81554. }
  81555. _this._fallbackTextureUsed = true;
  81556. });
  81557. return this._effect.isReady();
  81558. };
  81559. /**
  81560. * Resets the refresh counter of the texture and start bak from scratch.
  81561. * Could be useful to regenerate the texture if it is setup to render only once.
  81562. */
  81563. ProceduralTexture.prototype.resetRefreshCounter = function () {
  81564. this._currentRefreshId = -1;
  81565. };
  81566. /**
  81567. * Set the fragment shader to use in order to render the texture.
  81568. * @param fragment This can be set to a path (into the shader store) or to a json object containing a fragmentElement property.
  81569. */
  81570. ProceduralTexture.prototype.setFragment = function (fragment) {
  81571. this._fragment = fragment;
  81572. };
  81573. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  81574. /**
  81575. * Define the refresh rate of the texture or the rendering frequency.
  81576. * Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  81577. */
  81578. get: function () {
  81579. return this._refreshRate;
  81580. },
  81581. set: function (value) {
  81582. this._refreshRate = value;
  81583. this.resetRefreshCounter();
  81584. },
  81585. enumerable: true,
  81586. configurable: true
  81587. });
  81588. /** @hidden */
  81589. ProceduralTexture.prototype._shouldRender = function () {
  81590. if (!this.isEnabled || !this.isReady() || !this._texture) {
  81591. if (this._texture) {
  81592. this._texture.isReady = false;
  81593. }
  81594. return false;
  81595. }
  81596. if (this._fallbackTextureUsed) {
  81597. return false;
  81598. }
  81599. if (this._currentRefreshId === -1) { // At least render once
  81600. this._currentRefreshId = 1;
  81601. return true;
  81602. }
  81603. if (this.refreshRate === this._currentRefreshId) {
  81604. this._currentRefreshId = 1;
  81605. return true;
  81606. }
  81607. this._currentRefreshId++;
  81608. return false;
  81609. };
  81610. /**
  81611. * Get the size the texture is rendering at.
  81612. * @returns the size (texture is always squared)
  81613. */
  81614. ProceduralTexture.prototype.getRenderSize = function () {
  81615. return this._size;
  81616. };
  81617. /**
  81618. * Resize the texture to new value.
  81619. * @param size Define the new size the texture should have
  81620. * @param generateMipMaps Define whether the new texture should create mip maps
  81621. */
  81622. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  81623. if (this._fallbackTextureUsed) {
  81624. return;
  81625. }
  81626. this.releaseInternalTexture();
  81627. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  81628. // Update properties
  81629. this._size = size;
  81630. this._generateMipMaps = generateMipMaps;
  81631. };
  81632. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  81633. if (this._uniforms.indexOf(uniformName) === -1) {
  81634. this._uniforms.push(uniformName);
  81635. }
  81636. };
  81637. /**
  81638. * Set a texture in the shader program used to render.
  81639. * @param name Define the name of the uniform samplers as defined in the shader
  81640. * @param texture Define the texture to bind to this sampler
  81641. * @return the texture itself allowing "fluent" like uniform updates
  81642. */
  81643. ProceduralTexture.prototype.setTexture = function (name, texture) {
  81644. if (this._samplers.indexOf(name) === -1) {
  81645. this._samplers.push(name);
  81646. }
  81647. this._textures[name] = texture;
  81648. return this;
  81649. };
  81650. /**
  81651. * Set a float in the shader.
  81652. * @param name Define the name of the uniform as defined in the shader
  81653. * @param value Define the value to give to the uniform
  81654. * @return the texture itself allowing "fluent" like uniform updates
  81655. */
  81656. ProceduralTexture.prototype.setFloat = function (name, value) {
  81657. this._checkUniform(name);
  81658. this._floats[name] = value;
  81659. return this;
  81660. };
  81661. /**
  81662. * Set a int in the shader.
  81663. * @param name Define the name of the uniform as defined in the shader
  81664. * @param value Define the value to give to the uniform
  81665. * @return the texture itself allowing "fluent" like uniform updates
  81666. */
  81667. ProceduralTexture.prototype.setInt = function (name, value) {
  81668. this._checkUniform(name);
  81669. this._ints[name] = value;
  81670. return this;
  81671. };
  81672. /**
  81673. * Set an array of floats in the shader.
  81674. * @param name Define the name of the uniform as defined in the shader
  81675. * @param value Define the value to give to the uniform
  81676. * @return the texture itself allowing "fluent" like uniform updates
  81677. */
  81678. ProceduralTexture.prototype.setFloats = function (name, value) {
  81679. this._checkUniform(name);
  81680. this._floatsArrays[name] = value;
  81681. return this;
  81682. };
  81683. /**
  81684. * Set a vec3 in the shader from a Color3.
  81685. * @param name Define the name of the uniform as defined in the shader
  81686. * @param value Define the value to give to the uniform
  81687. * @return the texture itself allowing "fluent" like uniform updates
  81688. */
  81689. ProceduralTexture.prototype.setColor3 = function (name, value) {
  81690. this._checkUniform(name);
  81691. this._colors3[name] = value;
  81692. return this;
  81693. };
  81694. /**
  81695. * Set a vec4 in the shader from a Color4.
  81696. * @param name Define the name of the uniform as defined in the shader
  81697. * @param value Define the value to give to the uniform
  81698. * @return the texture itself allowing "fluent" like uniform updates
  81699. */
  81700. ProceduralTexture.prototype.setColor4 = function (name, value) {
  81701. this._checkUniform(name);
  81702. this._colors4[name] = value;
  81703. return this;
  81704. };
  81705. /**
  81706. * Set a vec2 in the shader from a Vector2.
  81707. * @param name Define the name of the uniform as defined in the shader
  81708. * @param value Define the value to give to the uniform
  81709. * @return the texture itself allowing "fluent" like uniform updates
  81710. */
  81711. ProceduralTexture.prototype.setVector2 = function (name, value) {
  81712. this._checkUniform(name);
  81713. this._vectors2[name] = value;
  81714. return this;
  81715. };
  81716. /**
  81717. * Set a vec3 in the shader from a Vector3.
  81718. * @param name Define the name of the uniform as defined in the shader
  81719. * @param value Define the value to give to the uniform
  81720. * @return the texture itself allowing "fluent" like uniform updates
  81721. */
  81722. ProceduralTexture.prototype.setVector3 = function (name, value) {
  81723. this._checkUniform(name);
  81724. this._vectors3[name] = value;
  81725. return this;
  81726. };
  81727. /**
  81728. * Set a mat4 in the shader from a MAtrix.
  81729. * @param name Define the name of the uniform as defined in the shader
  81730. * @param value Define the value to give to the uniform
  81731. * @return the texture itself allowing "fluent" like uniform updates
  81732. */
  81733. ProceduralTexture.prototype.setMatrix = function (name, value) {
  81734. this._checkUniform(name);
  81735. this._matrices[name] = value;
  81736. return this;
  81737. };
  81738. /**
  81739. * Render the texture to its associated render target.
  81740. * @param useCameraPostProcess Define if camera post process should be applied to the texture
  81741. */
  81742. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  81743. var scene = this.getScene();
  81744. if (!scene) {
  81745. return;
  81746. }
  81747. var engine = this._engine;
  81748. // Render
  81749. engine.enableEffect(this._effect);
  81750. engine.setState(false);
  81751. // Texture
  81752. for (var name in this._textures) {
  81753. this._effect.setTexture(name, this._textures[name]);
  81754. }
  81755. // Float
  81756. for (name in this._ints) {
  81757. this._effect.setInt(name, this._ints[name]);
  81758. }
  81759. // Float
  81760. for (name in this._floats) {
  81761. this._effect.setFloat(name, this._floats[name]);
  81762. }
  81763. // Floats
  81764. for (name in this._floatsArrays) {
  81765. this._effect.setArray(name, this._floatsArrays[name]);
  81766. }
  81767. // Color3
  81768. for (name in this._colors3) {
  81769. this._effect.setColor3(name, this._colors3[name]);
  81770. }
  81771. // Color4
  81772. for (name in this._colors4) {
  81773. var color = this._colors4[name];
  81774. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  81775. }
  81776. // Vector2
  81777. for (name in this._vectors2) {
  81778. this._effect.setVector2(name, this._vectors2[name]);
  81779. }
  81780. // Vector3
  81781. for (name in this._vectors3) {
  81782. this._effect.setVector3(name, this._vectors3[name]);
  81783. }
  81784. // Matrix
  81785. for (name in this._matrices) {
  81786. this._effect.setMatrix(name, this._matrices[name]);
  81787. }
  81788. if (!this._texture) {
  81789. return;
  81790. }
  81791. if (this.isCube) {
  81792. for (var face = 0; face < 6; face++) {
  81793. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  81794. // VBOs
  81795. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  81796. this._effect.setFloat("face", face);
  81797. // Clear
  81798. if (this.autoClear) {
  81799. engine.clear(scene.clearColor, true, false, false);
  81800. }
  81801. // Draw order
  81802. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  81803. // Mipmaps
  81804. if (face === 5) {
  81805. engine.generateMipMapsForCubemap(this._texture);
  81806. }
  81807. }
  81808. }
  81809. else {
  81810. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  81811. // VBOs
  81812. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  81813. // Clear
  81814. if (this.autoClear) {
  81815. engine.clear(scene.clearColor, true, false, false);
  81816. }
  81817. // Draw order
  81818. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  81819. }
  81820. // Unbind
  81821. engine.unBindFramebuffer(this._texture, this.isCube);
  81822. if (this.onGenerated) {
  81823. this.onGenerated();
  81824. }
  81825. this.onGeneratedObservable.notifyObservers(this);
  81826. };
  81827. /**
  81828. * Clone the texture.
  81829. * @returns the cloned texture
  81830. */
  81831. ProceduralTexture.prototype.clone = function () {
  81832. var textureSize = this.getSize();
  81833. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  81834. // Base texture
  81835. newTexture.hasAlpha = this.hasAlpha;
  81836. newTexture.level = this.level;
  81837. // RenderTarget Texture
  81838. newTexture.coordinatesMode = this.coordinatesMode;
  81839. return newTexture;
  81840. };
  81841. /**
  81842. * Dispose the texture and release its asoociated resources.
  81843. */
  81844. ProceduralTexture.prototype.dispose = function () {
  81845. var scene = this.getScene();
  81846. if (!scene) {
  81847. return;
  81848. }
  81849. var index = scene.proceduralTextures.indexOf(this);
  81850. if (index >= 0) {
  81851. scene.proceduralTextures.splice(index, 1);
  81852. }
  81853. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  81854. if (vertexBuffer) {
  81855. vertexBuffer.dispose();
  81856. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  81857. }
  81858. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  81859. this._indexBuffer = null;
  81860. }
  81861. _super.prototype.dispose.call(this);
  81862. };
  81863. __decorate([
  81864. BABYLON.serialize()
  81865. ], ProceduralTexture.prototype, "isEnabled", void 0);
  81866. __decorate([
  81867. BABYLON.serialize()
  81868. ], ProceduralTexture.prototype, "autoClear", void 0);
  81869. __decorate([
  81870. BABYLON.serialize()
  81871. ], ProceduralTexture.prototype, "_generateMipMaps", void 0);
  81872. __decorate([
  81873. BABYLON.serialize()
  81874. ], ProceduralTexture.prototype, "_size", void 0);
  81875. __decorate([
  81876. BABYLON.serialize()
  81877. ], ProceduralTexture.prototype, "refreshRate", null);
  81878. return ProceduralTexture;
  81879. }(BABYLON.Texture));
  81880. BABYLON.ProceduralTexture = ProceduralTexture;
  81881. })(BABYLON || (BABYLON = {}));
  81882. //# sourceMappingURL=babylon.proceduralTexture.js.map
  81883. var BABYLON;
  81884. (function (BABYLON) {
  81885. /**
  81886. * Defines the Procedural Texture scene component responsible to manage any Procedural Texture
  81887. * in a given scene.
  81888. */
  81889. var ProceduralTextureSceneComponent = /** @class */ (function () {
  81890. /**
  81891. * Creates a new instance of the component for the given scene
  81892. * @param scene Defines the scene to register the component in
  81893. */
  81894. function ProceduralTextureSceneComponent(scene) {
  81895. /**
  81896. * The component name helpfull to identify the component in the list of scene components.
  81897. */
  81898. this.name = BABYLON.SceneComponentConstants.NAME_PROCEDURALTEXTURE;
  81899. this.scene = scene;
  81900. this.scene.proceduralTextures = new Array();
  81901. scene.layers = new Array();
  81902. }
  81903. /**
  81904. * Registers the component in a given scene
  81905. */
  81906. ProceduralTextureSceneComponent.prototype.register = function () {
  81907. this.scene._beforeClearStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECLEAR_PROCEDURALTEXTURE, this, this._beforeClear);
  81908. };
  81909. /**
  81910. * Rebuilds the elements related to this component in case of
  81911. * context lost for instance.
  81912. */
  81913. ProceduralTextureSceneComponent.prototype.rebuild = function () {
  81914. // Nothing to do here.
  81915. };
  81916. /**
  81917. * Disposes the component and the associated ressources.
  81918. */
  81919. ProceduralTextureSceneComponent.prototype.dispose = function () {
  81920. // Nothing to do here.
  81921. };
  81922. ProceduralTextureSceneComponent.prototype._beforeClear = function () {
  81923. if (this.scene.proceduralTexturesEnabled) {
  81924. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.scene.proceduralTextures.length > 0);
  81925. for (var proceduralIndex = 0; proceduralIndex < this.scene.proceduralTextures.length; proceduralIndex++) {
  81926. var proceduralTexture = this.scene.proceduralTextures[proceduralIndex];
  81927. if (proceduralTexture._shouldRender()) {
  81928. proceduralTexture.render();
  81929. }
  81930. }
  81931. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.scene.proceduralTextures.length > 0);
  81932. }
  81933. };
  81934. return ProceduralTextureSceneComponent;
  81935. }());
  81936. BABYLON.ProceduralTextureSceneComponent = ProceduralTextureSceneComponent;
  81937. })(BABYLON || (BABYLON = {}));
  81938. //# sourceMappingURL=babylon.proceduralTextureSceneComponent.js.map
  81939. var BABYLON;
  81940. (function (BABYLON) {
  81941. /**
  81942. * 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.
  81943. * Custom Procedural textures are the easiest way to create your own procedural in your application.
  81944. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures#creating-custom-procedural-textures
  81945. */
  81946. var CustomProceduralTexture = /** @class */ (function (_super) {
  81947. __extends(CustomProceduralTexture, _super);
  81948. /**
  81949. * Instantiates a new Custom Procedural Texture.
  81950. * 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.
  81951. * Custom Procedural textures are the easiest way to create your own procedural in your application.
  81952. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures#creating-custom-procedural-textures
  81953. * @param name Define the name of the texture
  81954. * @param texturePath Define the folder path containing all the cutom texture related files (config, shaders...)
  81955. * @param size Define the size of the texture to create
  81956. * @param scene Define the scene the texture belongs to
  81957. * @param fallbackTexture Define a fallback texture in case there were issues to create the custom texture
  81958. * @param generateMipMaps Define if the texture should creates mip maps or not
  81959. */
  81960. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  81961. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  81962. _this._animate = true;
  81963. _this._time = 0;
  81964. _this._texturePath = texturePath;
  81965. //Try to load json
  81966. _this._loadJson(texturePath);
  81967. _this.refreshRate = 1;
  81968. return _this;
  81969. }
  81970. CustomProceduralTexture.prototype._loadJson = function (jsonUrl) {
  81971. var _this = this;
  81972. var noConfigFile = function () {
  81973. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  81974. try {
  81975. _this.setFragment(_this._texturePath);
  81976. }
  81977. catch (ex) {
  81978. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  81979. }
  81980. };
  81981. var configFileUrl = jsonUrl + "/config.json";
  81982. var xhr = new XMLHttpRequest();
  81983. xhr.open("GET", configFileUrl, true);
  81984. xhr.addEventListener("load", function () {
  81985. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  81986. try {
  81987. _this._config = JSON.parse(xhr.response);
  81988. _this.updateShaderUniforms();
  81989. _this.updateTextures();
  81990. _this.setFragment(_this._texturePath + "/custom");
  81991. _this._animate = _this._config.animate;
  81992. _this.refreshRate = _this._config.refreshrate;
  81993. }
  81994. catch (ex) {
  81995. noConfigFile();
  81996. }
  81997. }
  81998. else {
  81999. noConfigFile();
  82000. }
  82001. }, false);
  82002. xhr.addEventListener("error", function () {
  82003. noConfigFile();
  82004. }, false);
  82005. try {
  82006. if (BABYLON.Tools.UseCustomRequestHeaders) {
  82007. BABYLON.Tools.InjectCustomRequestHeaders(xhr);
  82008. }
  82009. xhr.send();
  82010. }
  82011. catch (ex) {
  82012. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  82013. }
  82014. };
  82015. /**
  82016. * Is the texture ready to be used ? (rendered at least once)
  82017. * @returns true if ready, otherwise, false.
  82018. */
  82019. CustomProceduralTexture.prototype.isReady = function () {
  82020. if (!_super.prototype.isReady.call(this)) {
  82021. return false;
  82022. }
  82023. for (var name in this._textures) {
  82024. var texture = this._textures[name];
  82025. if (!texture.isReady()) {
  82026. return false;
  82027. }
  82028. }
  82029. return true;
  82030. };
  82031. /**
  82032. * Render the texture to its associated render target.
  82033. * @param useCameraPostProcess Define if camera post process should be applied to the texture
  82034. */
  82035. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  82036. var scene = this.getScene();
  82037. if (this._animate && scene) {
  82038. this._time += scene.getAnimationRatio() * 0.03;
  82039. this.updateShaderUniforms();
  82040. }
  82041. _super.prototype.render.call(this, useCameraPostProcess);
  82042. };
  82043. /**
  82044. * Update the list of dependant textures samplers in the shader.
  82045. */
  82046. CustomProceduralTexture.prototype.updateTextures = function () {
  82047. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  82048. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  82049. }
  82050. };
  82051. /**
  82052. * Update the uniform values of the procedural texture in the shader.
  82053. */
  82054. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  82055. if (this._config) {
  82056. for (var j = 0; j < this._config.uniforms.length; j++) {
  82057. var uniform = this._config.uniforms[j];
  82058. switch (uniform.type) {
  82059. case "float":
  82060. this.setFloat(uniform.name, uniform.value);
  82061. break;
  82062. case "color3":
  82063. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  82064. break;
  82065. case "color4":
  82066. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  82067. break;
  82068. case "vector2":
  82069. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  82070. break;
  82071. case "vector3":
  82072. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  82073. break;
  82074. }
  82075. }
  82076. }
  82077. this.setFloat("time", this._time);
  82078. };
  82079. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  82080. /**
  82081. * Define if the texture animates or not.
  82082. */
  82083. get: function () {
  82084. return this._animate;
  82085. },
  82086. set: function (value) {
  82087. this._animate = value;
  82088. },
  82089. enumerable: true,
  82090. configurable: true
  82091. });
  82092. return CustomProceduralTexture;
  82093. }(BABYLON.ProceduralTexture));
  82094. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  82095. })(BABYLON || (BABYLON = {}));
  82096. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  82097. var BABYLON;
  82098. (function (BABYLON) {
  82099. /**
  82100. * Manage the gamepad inputs to control a free camera.
  82101. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  82102. */
  82103. var FreeCameraGamepadInput = /** @class */ (function () {
  82104. function FreeCameraGamepadInput() {
  82105. /**
  82106. * Defines the gamepad rotation sensiblity.
  82107. * This is the threshold from when rotation starts to be accounted for to prevent jittering.
  82108. */
  82109. this.gamepadAngularSensibility = 200;
  82110. /**
  82111. * Defines the gamepad move sensiblity.
  82112. * This is the threshold from when moving starts to be accounted for for to prevent jittering.
  82113. */
  82114. this.gamepadMoveSensibility = 40;
  82115. this._cameraTransform = BABYLON.Matrix.Identity();
  82116. this._deltaTransform = BABYLON.Vector3.Zero();
  82117. this._vector3 = BABYLON.Vector3.Zero();
  82118. this._vector2 = BABYLON.Vector2.Zero();
  82119. }
  82120. /**
  82121. * Attach the input controls to a specific dom element to get the input from.
  82122. * @param element Defines the element the controls should be listened from
  82123. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  82124. */
  82125. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  82126. var _this = this;
  82127. var manager = this.camera.getScene().gamepadManager;
  82128. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  82129. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  82130. // prioritize XBOX gamepads.
  82131. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  82132. _this.gamepad = gamepad;
  82133. }
  82134. }
  82135. });
  82136. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  82137. if (_this.gamepad === gamepad) {
  82138. _this.gamepad = null;
  82139. }
  82140. });
  82141. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  82142. };
  82143. /**
  82144. * Detach the current controls from the specified dom element.
  82145. * @param element Defines the element to stop listening the inputs from
  82146. */
  82147. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  82148. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  82149. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  82150. this.gamepad = null;
  82151. };
  82152. /**
  82153. * Update the current camera state depending on the inputs that have been used this frame.
  82154. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  82155. */
  82156. FreeCameraGamepadInput.prototype.checkInputs = function () {
  82157. if (this.gamepad && this.gamepad.leftStick) {
  82158. var camera = this.camera;
  82159. var LSValues = this.gamepad.leftStick;
  82160. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  82161. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  82162. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  82163. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  82164. var RSValues = this.gamepad.rightStick;
  82165. if (RSValues) {
  82166. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  82167. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  82168. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  82169. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  82170. }
  82171. else {
  82172. RSValues = { x: 0, y: 0 };
  82173. }
  82174. if (!camera.rotationQuaternion) {
  82175. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  82176. }
  82177. else {
  82178. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  82179. }
  82180. var speed = camera._computeLocalCameraSpeed() * 50.0;
  82181. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  82182. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  82183. camera.cameraDirection.addInPlace(this._deltaTransform);
  82184. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  82185. camera.cameraRotation.addInPlace(this._vector2);
  82186. }
  82187. };
  82188. /**
  82189. * Gets the class name of the current intput.
  82190. * @returns the class name
  82191. */
  82192. FreeCameraGamepadInput.prototype.getClassName = function () {
  82193. return "FreeCameraGamepadInput";
  82194. };
  82195. /**
  82196. * Get the friendly name associated with the input class.
  82197. * @returns the input friendly name
  82198. */
  82199. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  82200. return "gamepad";
  82201. };
  82202. __decorate([
  82203. BABYLON.serialize()
  82204. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  82205. __decorate([
  82206. BABYLON.serialize()
  82207. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  82208. return FreeCameraGamepadInput;
  82209. }());
  82210. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  82211. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  82212. })(BABYLON || (BABYLON = {}));
  82213. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  82214. var BABYLON;
  82215. (function (BABYLON) {
  82216. /**
  82217. * Manage the gamepad inputs to control an arc rotate camera.
  82218. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  82219. */
  82220. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  82221. function ArcRotateCameraGamepadInput() {
  82222. /**
  82223. * Defines the gamepad rotation sensiblity.
  82224. * This is the threshold from when rotation starts to be accounted for to prevent jittering.
  82225. */
  82226. this.gamepadRotationSensibility = 80;
  82227. /**
  82228. * Defines the gamepad move sensiblity.
  82229. * This is the threshold from when moving starts to be accounted for for to prevent jittering.
  82230. */
  82231. this.gamepadMoveSensibility = 40;
  82232. }
  82233. /**
  82234. * Attach the input controls to a specific dom element to get the input from.
  82235. * @param element Defines the element the controls should be listened from
  82236. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  82237. */
  82238. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  82239. var _this = this;
  82240. var manager = this.camera.getScene().gamepadManager;
  82241. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  82242. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  82243. // prioritize XBOX gamepads.
  82244. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  82245. _this.gamepad = gamepad;
  82246. }
  82247. }
  82248. });
  82249. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  82250. if (_this.gamepad === gamepad) {
  82251. _this.gamepad = null;
  82252. }
  82253. });
  82254. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  82255. };
  82256. /**
  82257. * Detach the current controls from the specified dom element.
  82258. * @param element Defines the element to stop listening the inputs from
  82259. */
  82260. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  82261. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  82262. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  82263. this.gamepad = null;
  82264. };
  82265. /**
  82266. * Update the current camera state depending on the inputs that have been used this frame.
  82267. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  82268. */
  82269. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  82270. if (this.gamepad) {
  82271. var camera = this.camera;
  82272. var RSValues = this.gamepad.rightStick;
  82273. if (RSValues) {
  82274. if (RSValues.x != 0) {
  82275. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  82276. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  82277. camera.inertialAlphaOffset += normalizedRX;
  82278. }
  82279. }
  82280. if (RSValues.y != 0) {
  82281. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  82282. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  82283. camera.inertialBetaOffset += normalizedRY;
  82284. }
  82285. }
  82286. }
  82287. var LSValues = this.gamepad.leftStick;
  82288. if (LSValues && LSValues.y != 0) {
  82289. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  82290. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  82291. this.camera.inertialRadiusOffset -= normalizedLY;
  82292. }
  82293. }
  82294. }
  82295. };
  82296. /**
  82297. * Gets the class name of the current intput.
  82298. * @returns the class name
  82299. */
  82300. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  82301. return "ArcRotateCameraGamepadInput";
  82302. };
  82303. /**
  82304. * Get the friendly name associated with the input class.
  82305. * @returns the input friendly name
  82306. */
  82307. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  82308. return "gamepad";
  82309. };
  82310. __decorate([
  82311. BABYLON.serialize()
  82312. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  82313. __decorate([
  82314. BABYLON.serialize()
  82315. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  82316. return ArcRotateCameraGamepadInput;
  82317. }());
  82318. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  82319. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  82320. })(BABYLON || (BABYLON = {}));
  82321. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  82322. var BABYLON;
  82323. (function (BABYLON) {
  82324. /**
  82325. * Manager for handling gamepads
  82326. */
  82327. var GamepadManager = /** @class */ (function () {
  82328. /**
  82329. * Initializes the gamepad manager
  82330. * @param _scene BabylonJS scene
  82331. */
  82332. function GamepadManager(_scene) {
  82333. var _this = this;
  82334. this._scene = _scene;
  82335. this._babylonGamepads = [];
  82336. this._oneGamepadConnected = false;
  82337. /** @hidden */
  82338. this._isMonitoring = false;
  82339. /**
  82340. * observable to be triggered when the gamepad controller has been disconnected
  82341. */
  82342. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  82343. if (!BABYLON.Tools.IsWindowObjectExist()) {
  82344. this._gamepadEventSupported = false;
  82345. }
  82346. else {
  82347. this._gamepadEventSupported = 'GamepadEvent' in window;
  82348. this._gamepadSupport = (navigator.getGamepads ||
  82349. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  82350. }
  82351. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  82352. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  82353. for (var i in _this._babylonGamepads) {
  82354. var gamepad = _this._babylonGamepads[i];
  82355. if (gamepad && gamepad._isConnected) {
  82356. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  82357. }
  82358. }
  82359. });
  82360. this._onGamepadConnectedEvent = function (evt) {
  82361. var gamepad = evt.gamepad;
  82362. if (gamepad.index in _this._babylonGamepads) {
  82363. if (_this._babylonGamepads[gamepad.index].isConnected) {
  82364. return;
  82365. }
  82366. }
  82367. var newGamepad;
  82368. if (_this._babylonGamepads[gamepad.index]) {
  82369. newGamepad = _this._babylonGamepads[gamepad.index];
  82370. newGamepad.browserGamepad = gamepad;
  82371. newGamepad._isConnected = true;
  82372. }
  82373. else {
  82374. newGamepad = _this._addNewGamepad(gamepad);
  82375. }
  82376. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  82377. _this._startMonitoringGamepads();
  82378. };
  82379. this._onGamepadDisconnectedEvent = function (evt) {
  82380. var gamepad = evt.gamepad;
  82381. // Remove the gamepad from the list of gamepads to monitor.
  82382. for (var i in _this._babylonGamepads) {
  82383. if (_this._babylonGamepads[i].index === gamepad.index) {
  82384. var disconnectedGamepad = _this._babylonGamepads[i];
  82385. disconnectedGamepad._isConnected = false;
  82386. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  82387. break;
  82388. }
  82389. }
  82390. };
  82391. if (this._gamepadSupport) {
  82392. //first add already-connected gamepads
  82393. this._updateGamepadObjects();
  82394. if (this._babylonGamepads.length) {
  82395. this._startMonitoringGamepads();
  82396. }
  82397. // Checking if the gamepad connected event is supported (like in Firefox)
  82398. if (this._gamepadEventSupported) {
  82399. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  82400. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  82401. }
  82402. else {
  82403. this._startMonitoringGamepads();
  82404. }
  82405. }
  82406. }
  82407. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  82408. /**
  82409. * The gamepads in the game pad manager
  82410. */
  82411. get: function () {
  82412. return this._babylonGamepads;
  82413. },
  82414. enumerable: true,
  82415. configurable: true
  82416. });
  82417. /**
  82418. * Get the gamepad controllers based on type
  82419. * @param type The type of gamepad controller
  82420. * @returns Nullable gamepad
  82421. */
  82422. GamepadManager.prototype.getGamepadByType = function (type) {
  82423. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  82424. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  82425. var gamepad = _a[_i];
  82426. if (gamepad && gamepad.type === type) {
  82427. return gamepad;
  82428. }
  82429. }
  82430. return null;
  82431. };
  82432. /**
  82433. * Disposes the gamepad manager
  82434. */
  82435. GamepadManager.prototype.dispose = function () {
  82436. if (this._gamepadEventSupported) {
  82437. if (this._onGamepadConnectedEvent) {
  82438. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  82439. }
  82440. if (this._onGamepadDisconnectedEvent) {
  82441. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  82442. }
  82443. this._onGamepadConnectedEvent = null;
  82444. this._onGamepadDisconnectedEvent = null;
  82445. }
  82446. this._babylonGamepads.forEach(function (gamepad) {
  82447. gamepad.dispose();
  82448. });
  82449. this.onGamepadConnectedObservable.clear();
  82450. this.onGamepadDisconnectedObservable.clear();
  82451. this._oneGamepadConnected = false;
  82452. this._stopMonitoringGamepads();
  82453. this._babylonGamepads = [];
  82454. };
  82455. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  82456. if (!this._oneGamepadConnected) {
  82457. this._oneGamepadConnected = true;
  82458. }
  82459. var newGamepad;
  82460. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  82461. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  82462. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  82463. }
  82464. // if pose is supported, use the (WebVR) pose enabled controller
  82465. else if (gamepad.pose) {
  82466. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  82467. }
  82468. else {
  82469. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  82470. }
  82471. this._babylonGamepads[newGamepad.index] = newGamepad;
  82472. return newGamepad;
  82473. };
  82474. GamepadManager.prototype._startMonitoringGamepads = function () {
  82475. if (!this._isMonitoring) {
  82476. this._isMonitoring = true;
  82477. //back-comp
  82478. if (!this._scene) {
  82479. this._checkGamepadsStatus();
  82480. }
  82481. }
  82482. };
  82483. GamepadManager.prototype._stopMonitoringGamepads = function () {
  82484. this._isMonitoring = false;
  82485. };
  82486. /** @hidden */
  82487. GamepadManager.prototype._checkGamepadsStatus = function () {
  82488. var _this = this;
  82489. // Hack to be compatible Chrome
  82490. this._updateGamepadObjects();
  82491. for (var i in this._babylonGamepads) {
  82492. var gamepad = this._babylonGamepads[i];
  82493. if (!gamepad || !gamepad.isConnected) {
  82494. continue;
  82495. }
  82496. gamepad.update();
  82497. }
  82498. if (this._isMonitoring && !this._scene) {
  82499. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  82500. }
  82501. };
  82502. // This function is called only on Chrome, which does not properly support
  82503. // connection/disconnection events and forces you to recopy again the gamepad object
  82504. GamepadManager.prototype._updateGamepadObjects = function () {
  82505. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  82506. for (var i = 0; i < gamepads.length; i++) {
  82507. var gamepad = gamepads[i];
  82508. if (gamepad) {
  82509. if (!this._babylonGamepads[gamepad.index]) {
  82510. var newGamepad = this._addNewGamepad(gamepad);
  82511. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  82512. }
  82513. else {
  82514. // Forced to copy again this object for Chrome for unknown reason
  82515. this._babylonGamepads[i].browserGamepad = gamepad;
  82516. if (!this._babylonGamepads[i].isConnected) {
  82517. this._babylonGamepads[i]._isConnected = true;
  82518. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  82519. }
  82520. }
  82521. }
  82522. }
  82523. };
  82524. return GamepadManager;
  82525. }());
  82526. BABYLON.GamepadManager = GamepadManager;
  82527. })(BABYLON || (BABYLON = {}));
  82528. //# sourceMappingURL=babylon.gamepadManager.js.map
  82529. var BABYLON;
  82530. (function (BABYLON) {
  82531. /**
  82532. * Represents a gamepad control stick position
  82533. */
  82534. var StickValues = /** @class */ (function () {
  82535. /**
  82536. * Initializes the gamepad x and y control stick values
  82537. * @param x The x component of the gamepad control stick value
  82538. * @param y The y component of the gamepad control stick value
  82539. */
  82540. function StickValues(
  82541. /**
  82542. * The x component of the control stick
  82543. */
  82544. x,
  82545. /**
  82546. * The y component of the control stick
  82547. */
  82548. y) {
  82549. this.x = x;
  82550. this.y = y;
  82551. }
  82552. return StickValues;
  82553. }());
  82554. BABYLON.StickValues = StickValues;
  82555. /**
  82556. * Represents a gamepad
  82557. */
  82558. var Gamepad = /** @class */ (function () {
  82559. /**
  82560. * Initializes the gamepad
  82561. * @param id The id of the gamepad
  82562. * @param index The index of the gamepad
  82563. * @param browserGamepad The browser gamepad
  82564. * @param leftStickX The x component of the left joystick
  82565. * @param leftStickY The y component of the left joystick
  82566. * @param rightStickX The x component of the right joystick
  82567. * @param rightStickY The y component of the right joystick
  82568. */
  82569. function Gamepad(
  82570. /**
  82571. * The id of the gamepad
  82572. */
  82573. id,
  82574. /**
  82575. * The index of the gamepad
  82576. */
  82577. index,
  82578. /**
  82579. * The browser gamepad
  82580. */
  82581. browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  82582. if (leftStickX === void 0) { leftStickX = 0; }
  82583. if (leftStickY === void 0) { leftStickY = 1; }
  82584. if (rightStickX === void 0) { rightStickX = 2; }
  82585. if (rightStickY === void 0) { rightStickY = 3; }
  82586. this.id = id;
  82587. this.index = index;
  82588. this.browserGamepad = browserGamepad;
  82589. this._leftStick = { x: 0, y: 0 };
  82590. this._rightStick = { x: 0, y: 0 };
  82591. /** @hidden */
  82592. this._isConnected = true;
  82593. /**
  82594. * Specifies whether the left control stick should be Y-inverted
  82595. */
  82596. this._invertLeftStickY = false;
  82597. this.type = Gamepad.GAMEPAD;
  82598. this._leftStickAxisX = leftStickX;
  82599. this._leftStickAxisY = leftStickY;
  82600. this._rightStickAxisX = rightStickX;
  82601. this._rightStickAxisY = rightStickY;
  82602. if (this.browserGamepad.axes.length >= 2) {
  82603. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  82604. }
  82605. if (this.browserGamepad.axes.length >= 4) {
  82606. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  82607. }
  82608. }
  82609. Object.defineProperty(Gamepad.prototype, "isConnected", {
  82610. /**
  82611. * Specifies if the gamepad has been connected
  82612. */
  82613. get: function () {
  82614. return this._isConnected;
  82615. },
  82616. enumerable: true,
  82617. configurable: true
  82618. });
  82619. /**
  82620. * Callback triggered when the left joystick has changed
  82621. * @param callback
  82622. */
  82623. Gamepad.prototype.onleftstickchanged = function (callback) {
  82624. this._onleftstickchanged = callback;
  82625. };
  82626. /**
  82627. * Callback triggered when the right joystick has changed
  82628. * @param callback
  82629. */
  82630. Gamepad.prototype.onrightstickchanged = function (callback) {
  82631. this._onrightstickchanged = callback;
  82632. };
  82633. Object.defineProperty(Gamepad.prototype, "leftStick", {
  82634. /**
  82635. * Gets the left joystick
  82636. */
  82637. get: function () {
  82638. return this._leftStick;
  82639. },
  82640. /**
  82641. * Sets the left joystick values
  82642. */
  82643. set: function (newValues) {
  82644. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  82645. this._onleftstickchanged(newValues);
  82646. }
  82647. this._leftStick = newValues;
  82648. },
  82649. enumerable: true,
  82650. configurable: true
  82651. });
  82652. Object.defineProperty(Gamepad.prototype, "rightStick", {
  82653. /**
  82654. * Gets the right joystick
  82655. */
  82656. get: function () {
  82657. return this._rightStick;
  82658. },
  82659. /**
  82660. * Sets the right joystick value
  82661. */
  82662. set: function (newValues) {
  82663. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  82664. this._onrightstickchanged(newValues);
  82665. }
  82666. this._rightStick = newValues;
  82667. },
  82668. enumerable: true,
  82669. configurable: true
  82670. });
  82671. /**
  82672. * Updates the gamepad joystick positions
  82673. */
  82674. Gamepad.prototype.update = function () {
  82675. if (this._leftStick) {
  82676. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  82677. if (this._invertLeftStickY) {
  82678. this.leftStick.y *= -1;
  82679. }
  82680. }
  82681. if (this._rightStick) {
  82682. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  82683. }
  82684. };
  82685. /**
  82686. * Disposes the gamepad
  82687. */
  82688. Gamepad.prototype.dispose = function () {
  82689. };
  82690. /**
  82691. * Represents a gamepad controller
  82692. */
  82693. Gamepad.GAMEPAD = 0;
  82694. /**
  82695. * Represents a generic controller
  82696. */
  82697. Gamepad.GENERIC = 1;
  82698. /**
  82699. * Represents an XBox controller
  82700. */
  82701. Gamepad.XBOX = 2;
  82702. /**
  82703. * Represents a pose-enabled controller
  82704. */
  82705. Gamepad.POSE_ENABLED = 3;
  82706. return Gamepad;
  82707. }());
  82708. BABYLON.Gamepad = Gamepad;
  82709. /**
  82710. * Represents a generic gamepad
  82711. */
  82712. var GenericPad = /** @class */ (function (_super) {
  82713. __extends(GenericPad, _super);
  82714. /**
  82715. * Initializes the generic gamepad
  82716. * @param id The id of the generic gamepad
  82717. * @param index The index of the generic gamepad
  82718. * @param browserGamepad The browser gamepad
  82719. */
  82720. function GenericPad(id, index, browserGamepad) {
  82721. var _this = _super.call(this, id, index, browserGamepad) || this;
  82722. /**
  82723. * Observable triggered when a button has been pressed
  82724. */
  82725. _this.onButtonDownObservable = new BABYLON.Observable();
  82726. /**
  82727. * Observable triggered when a button has been released
  82728. */
  82729. _this.onButtonUpObservable = new BABYLON.Observable();
  82730. _this.type = Gamepad.GENERIC;
  82731. _this._buttons = new Array(browserGamepad.buttons.length);
  82732. return _this;
  82733. }
  82734. /**
  82735. * Callback triggered when a button has been pressed
  82736. * @param callback Called when a button has been pressed
  82737. */
  82738. GenericPad.prototype.onbuttondown = function (callback) {
  82739. this._onbuttondown = callback;
  82740. };
  82741. /**
  82742. * Callback triggered when a button has been released
  82743. * @param callback Called when a button has been released
  82744. */
  82745. GenericPad.prototype.onbuttonup = function (callback) {
  82746. this._onbuttonup = callback;
  82747. };
  82748. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  82749. if (newValue !== currentValue) {
  82750. if (newValue === 1) {
  82751. if (this._onbuttondown) {
  82752. this._onbuttondown(buttonIndex);
  82753. }
  82754. this.onButtonDownObservable.notifyObservers(buttonIndex);
  82755. }
  82756. if (newValue === 0) {
  82757. if (this._onbuttonup) {
  82758. this._onbuttonup(buttonIndex);
  82759. }
  82760. this.onButtonUpObservable.notifyObservers(buttonIndex);
  82761. }
  82762. }
  82763. return newValue;
  82764. };
  82765. /**
  82766. * Updates the generic gamepad
  82767. */
  82768. GenericPad.prototype.update = function () {
  82769. _super.prototype.update.call(this);
  82770. for (var index = 0; index < this._buttons.length; index++) {
  82771. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  82772. }
  82773. };
  82774. /**
  82775. * Disposes the generic gamepad
  82776. */
  82777. GenericPad.prototype.dispose = function () {
  82778. _super.prototype.dispose.call(this);
  82779. this.onButtonDownObservable.clear();
  82780. this.onButtonUpObservable.clear();
  82781. };
  82782. return GenericPad;
  82783. }(Gamepad));
  82784. BABYLON.GenericPad = GenericPad;
  82785. })(BABYLON || (BABYLON = {}));
  82786. //# sourceMappingURL=babylon.gamepad.js.map
  82787. var BABYLON;
  82788. (function (BABYLON) {
  82789. /**
  82790. * Defines supported buttons for XBox360 compatible gamepads
  82791. */
  82792. var Xbox360Button;
  82793. (function (Xbox360Button) {
  82794. /** A */
  82795. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  82796. /** B */
  82797. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  82798. /** X */
  82799. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  82800. /** Y */
  82801. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  82802. /** Start */
  82803. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  82804. /** Back */
  82805. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  82806. /** Left button */
  82807. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  82808. /** Right button */
  82809. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  82810. /** Left stick */
  82811. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  82812. /** Right stick */
  82813. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  82814. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  82815. /** Defines values for XBox360 DPad */
  82816. var Xbox360Dpad;
  82817. (function (Xbox360Dpad) {
  82818. /** Up */
  82819. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  82820. /** Down */
  82821. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  82822. /** Left */
  82823. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  82824. /** Right */
  82825. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  82826. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  82827. /**
  82828. * Defines a XBox360 gamepad
  82829. */
  82830. var Xbox360Pad = /** @class */ (function (_super) {
  82831. __extends(Xbox360Pad, _super);
  82832. /**
  82833. * Creates a new XBox360 gamepad object
  82834. * @param id defines the id of this gamepad
  82835. * @param index defines its index
  82836. * @param gamepad defines the internal HTML gamepad object
  82837. * @param xboxOne defines if it is a XBox One gamepad
  82838. */
  82839. function Xbox360Pad(id, index, gamepad, xboxOne) {
  82840. if (xboxOne === void 0) { xboxOne = false; }
  82841. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  82842. _this._leftTrigger = 0;
  82843. _this._rightTrigger = 0;
  82844. /** Observable raised when a button is pressed */
  82845. _this.onButtonDownObservable = new BABYLON.Observable();
  82846. /** Observable raised when a button is released */
  82847. _this.onButtonUpObservable = new BABYLON.Observable();
  82848. /** Observable raised when a pad is pressed */
  82849. _this.onPadDownObservable = new BABYLON.Observable();
  82850. /** Observable raised when a pad is released */
  82851. _this.onPadUpObservable = new BABYLON.Observable();
  82852. _this._buttonA = 0;
  82853. _this._buttonB = 0;
  82854. _this._buttonX = 0;
  82855. _this._buttonY = 0;
  82856. _this._buttonBack = 0;
  82857. _this._buttonStart = 0;
  82858. _this._buttonLB = 0;
  82859. _this._buttonRB = 0;
  82860. _this._buttonLeftStick = 0;
  82861. _this._buttonRightStick = 0;
  82862. _this._dPadUp = 0;
  82863. _this._dPadDown = 0;
  82864. _this._dPadLeft = 0;
  82865. _this._dPadRight = 0;
  82866. _this._isXboxOnePad = false;
  82867. _this.type = BABYLON.Gamepad.XBOX;
  82868. _this._isXboxOnePad = xboxOne;
  82869. return _this;
  82870. }
  82871. /**
  82872. * Defines the callback to call when left trigger is pressed
  82873. * @param callback defines the callback to use
  82874. */
  82875. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  82876. this._onlefttriggerchanged = callback;
  82877. };
  82878. /**
  82879. * Defines the callback to call when right trigger is pressed
  82880. * @param callback defines the callback to use
  82881. */
  82882. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  82883. this._onrighttriggerchanged = callback;
  82884. };
  82885. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  82886. /**
  82887. * Gets the left trigger value
  82888. */
  82889. get: function () {
  82890. return this._leftTrigger;
  82891. },
  82892. /**
  82893. * Sets the left trigger value
  82894. */
  82895. set: function (newValue) {
  82896. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  82897. this._onlefttriggerchanged(newValue);
  82898. }
  82899. this._leftTrigger = newValue;
  82900. },
  82901. enumerable: true,
  82902. configurable: true
  82903. });
  82904. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  82905. /**
  82906. * Gets the right trigger value
  82907. */
  82908. get: function () {
  82909. return this._rightTrigger;
  82910. },
  82911. /**
  82912. * Sets the right trigger value
  82913. */
  82914. set: function (newValue) {
  82915. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  82916. this._onrighttriggerchanged(newValue);
  82917. }
  82918. this._rightTrigger = newValue;
  82919. },
  82920. enumerable: true,
  82921. configurable: true
  82922. });
  82923. /**
  82924. * Defines the callback to call when a button is pressed
  82925. * @param callback defines the callback to use
  82926. */
  82927. Xbox360Pad.prototype.onbuttondown = function (callback) {
  82928. this._onbuttondown = callback;
  82929. };
  82930. /**
  82931. * Defines the callback to call when a button is released
  82932. * @param callback defines the callback to use
  82933. */
  82934. Xbox360Pad.prototype.onbuttonup = function (callback) {
  82935. this._onbuttonup = callback;
  82936. };
  82937. /**
  82938. * Defines the callback to call when a pad is pressed
  82939. * @param callback defines the callback to use
  82940. */
  82941. Xbox360Pad.prototype.ondpaddown = function (callback) {
  82942. this._ondpaddown = callback;
  82943. };
  82944. /**
  82945. * Defines the callback to call when a pad is released
  82946. * @param callback defines the callback to use
  82947. */
  82948. Xbox360Pad.prototype.ondpadup = function (callback) {
  82949. this._ondpadup = callback;
  82950. };
  82951. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  82952. if (newValue !== currentValue) {
  82953. if (newValue === 1) {
  82954. if (this._onbuttondown) {
  82955. this._onbuttondown(buttonType);
  82956. }
  82957. this.onButtonDownObservable.notifyObservers(buttonType);
  82958. }
  82959. if (newValue === 0) {
  82960. if (this._onbuttonup) {
  82961. this._onbuttonup(buttonType);
  82962. }
  82963. this.onButtonUpObservable.notifyObservers(buttonType);
  82964. }
  82965. }
  82966. return newValue;
  82967. };
  82968. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  82969. if (newValue !== currentValue) {
  82970. if (newValue === 1) {
  82971. if (this._ondpaddown) {
  82972. this._ondpaddown(buttonType);
  82973. }
  82974. this.onPadDownObservable.notifyObservers(buttonType);
  82975. }
  82976. if (newValue === 0) {
  82977. if (this._ondpadup) {
  82978. this._ondpadup(buttonType);
  82979. }
  82980. this.onPadUpObservable.notifyObservers(buttonType);
  82981. }
  82982. }
  82983. return newValue;
  82984. };
  82985. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  82986. /**
  82987. * Gets the value of the `A` button
  82988. */
  82989. get: function () {
  82990. return this._buttonA;
  82991. },
  82992. /**
  82993. * Sets the value of the `A` button
  82994. */
  82995. set: function (value) {
  82996. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  82997. },
  82998. enumerable: true,
  82999. configurable: true
  83000. });
  83001. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  83002. /**
  83003. * Gets the value of the `B` button
  83004. */
  83005. get: function () {
  83006. return this._buttonB;
  83007. },
  83008. /**
  83009. * Sets the value of the `B` button
  83010. */
  83011. set: function (value) {
  83012. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  83013. },
  83014. enumerable: true,
  83015. configurable: true
  83016. });
  83017. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  83018. /**
  83019. * Gets the value of the `X` button
  83020. */
  83021. get: function () {
  83022. return this._buttonX;
  83023. },
  83024. /**
  83025. * Sets the value of the `X` button
  83026. */
  83027. set: function (value) {
  83028. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  83029. },
  83030. enumerable: true,
  83031. configurable: true
  83032. });
  83033. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  83034. /**
  83035. * Gets the value of the `Y` button
  83036. */
  83037. get: function () {
  83038. return this._buttonY;
  83039. },
  83040. /**
  83041. * Sets the value of the `Y` button
  83042. */
  83043. set: function (value) {
  83044. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  83045. },
  83046. enumerable: true,
  83047. configurable: true
  83048. });
  83049. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  83050. /**
  83051. * Gets the value of the `Start` button
  83052. */
  83053. get: function () {
  83054. return this._buttonStart;
  83055. },
  83056. /**
  83057. * Sets the value of the `Start` button
  83058. */
  83059. set: function (value) {
  83060. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  83061. },
  83062. enumerable: true,
  83063. configurable: true
  83064. });
  83065. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  83066. /**
  83067. * Gets the value of the `Back` button
  83068. */
  83069. get: function () {
  83070. return this._buttonBack;
  83071. },
  83072. /**
  83073. * Sets the value of the `Back` button
  83074. */
  83075. set: function (value) {
  83076. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  83077. },
  83078. enumerable: true,
  83079. configurable: true
  83080. });
  83081. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  83082. /**
  83083. * Gets the value of the `Left` button
  83084. */
  83085. get: function () {
  83086. return this._buttonLB;
  83087. },
  83088. /**
  83089. * Sets the value of the `Left` button
  83090. */
  83091. set: function (value) {
  83092. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  83093. },
  83094. enumerable: true,
  83095. configurable: true
  83096. });
  83097. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  83098. /**
  83099. * Gets the value of the `Right` button
  83100. */
  83101. get: function () {
  83102. return this._buttonRB;
  83103. },
  83104. /**
  83105. * Sets the value of the `Right` button
  83106. */
  83107. set: function (value) {
  83108. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  83109. },
  83110. enumerable: true,
  83111. configurable: true
  83112. });
  83113. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  83114. /**
  83115. * Gets the value of the Left joystick
  83116. */
  83117. get: function () {
  83118. return this._buttonLeftStick;
  83119. },
  83120. /**
  83121. * Sets the value of the Left joystick
  83122. */
  83123. set: function (value) {
  83124. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  83125. },
  83126. enumerable: true,
  83127. configurable: true
  83128. });
  83129. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  83130. /**
  83131. * Gets the value of the Right joystick
  83132. */
  83133. get: function () {
  83134. return this._buttonRightStick;
  83135. },
  83136. /**
  83137. * Sets the value of the Right joystick
  83138. */
  83139. set: function (value) {
  83140. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  83141. },
  83142. enumerable: true,
  83143. configurable: true
  83144. });
  83145. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  83146. /**
  83147. * Gets the value of D-pad up
  83148. */
  83149. get: function () {
  83150. return this._dPadUp;
  83151. },
  83152. /**
  83153. * Sets the value of D-pad up
  83154. */
  83155. set: function (value) {
  83156. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  83157. },
  83158. enumerable: true,
  83159. configurable: true
  83160. });
  83161. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  83162. /**
  83163. * Gets the value of D-pad down
  83164. */
  83165. get: function () {
  83166. return this._dPadDown;
  83167. },
  83168. /**
  83169. * Sets the value of D-pad down
  83170. */
  83171. set: function (value) {
  83172. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  83173. },
  83174. enumerable: true,
  83175. configurable: true
  83176. });
  83177. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  83178. /**
  83179. * Gets the value of D-pad left
  83180. */
  83181. get: function () {
  83182. return this._dPadLeft;
  83183. },
  83184. /**
  83185. * Sets the value of D-pad left
  83186. */
  83187. set: function (value) {
  83188. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  83189. },
  83190. enumerable: true,
  83191. configurable: true
  83192. });
  83193. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  83194. /**
  83195. * Gets the value of D-pad right
  83196. */
  83197. get: function () {
  83198. return this._dPadRight;
  83199. },
  83200. /**
  83201. * Sets the value of D-pad right
  83202. */
  83203. set: function (value) {
  83204. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  83205. },
  83206. enumerable: true,
  83207. configurable: true
  83208. });
  83209. /**
  83210. * Force the gamepad to synchronize with device values
  83211. */
  83212. Xbox360Pad.prototype.update = function () {
  83213. _super.prototype.update.call(this);
  83214. if (this._isXboxOnePad) {
  83215. this.buttonA = this.browserGamepad.buttons[0].value;
  83216. this.buttonB = this.browserGamepad.buttons[1].value;
  83217. this.buttonX = this.browserGamepad.buttons[2].value;
  83218. this.buttonY = this.browserGamepad.buttons[3].value;
  83219. this.buttonLB = this.browserGamepad.buttons[4].value;
  83220. this.buttonRB = this.browserGamepad.buttons[5].value;
  83221. this.leftTrigger = this.browserGamepad.axes[2];
  83222. this.rightTrigger = this.browserGamepad.axes[5];
  83223. this.buttonBack = this.browserGamepad.buttons[9].value;
  83224. this.buttonStart = this.browserGamepad.buttons[8].value;
  83225. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  83226. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  83227. this.dPadUp = this.browserGamepad.buttons[11].value;
  83228. this.dPadDown = this.browserGamepad.buttons[12].value;
  83229. this.dPadLeft = this.browserGamepad.buttons[13].value;
  83230. this.dPadRight = this.browserGamepad.buttons[14].value;
  83231. }
  83232. else {
  83233. this.buttonA = this.browserGamepad.buttons[0].value;
  83234. this.buttonB = this.browserGamepad.buttons[1].value;
  83235. this.buttonX = this.browserGamepad.buttons[2].value;
  83236. this.buttonY = this.browserGamepad.buttons[3].value;
  83237. this.buttonLB = this.browserGamepad.buttons[4].value;
  83238. this.buttonRB = this.browserGamepad.buttons[5].value;
  83239. this.leftTrigger = this.browserGamepad.buttons[6].value;
  83240. this.rightTrigger = this.browserGamepad.buttons[7].value;
  83241. this.buttonBack = this.browserGamepad.buttons[8].value;
  83242. this.buttonStart = this.browserGamepad.buttons[9].value;
  83243. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  83244. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  83245. this.dPadUp = this.browserGamepad.buttons[12].value;
  83246. this.dPadDown = this.browserGamepad.buttons[13].value;
  83247. this.dPadLeft = this.browserGamepad.buttons[14].value;
  83248. this.dPadRight = this.browserGamepad.buttons[15].value;
  83249. }
  83250. };
  83251. /**
  83252. * Disposes the gamepad
  83253. */
  83254. Xbox360Pad.prototype.dispose = function () {
  83255. _super.prototype.dispose.call(this);
  83256. this.onButtonDownObservable.clear();
  83257. this.onButtonUpObservable.clear();
  83258. this.onPadDownObservable.clear();
  83259. this.onPadUpObservable.clear();
  83260. };
  83261. return Xbox360Pad;
  83262. }(BABYLON.Gamepad));
  83263. BABYLON.Xbox360Pad = Xbox360Pad;
  83264. })(BABYLON || (BABYLON = {}));
  83265. //# sourceMappingURL=babylon.xboxGamepad.js.map
  83266. var BABYLON;
  83267. (function (BABYLON) {
  83268. /**
  83269. * Defines the types of pose enabled controllers that are supported
  83270. */
  83271. var PoseEnabledControllerType;
  83272. (function (PoseEnabledControllerType) {
  83273. /**
  83274. * HTC Vive
  83275. */
  83276. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  83277. /**
  83278. * Oculus Rift
  83279. */
  83280. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  83281. /**
  83282. * Windows mixed reality
  83283. */
  83284. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  83285. /**
  83286. * Samsung gear VR
  83287. */
  83288. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  83289. /**
  83290. * Google Daydream
  83291. */
  83292. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  83293. /**
  83294. * Generic
  83295. */
  83296. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  83297. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  83298. /**
  83299. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  83300. */
  83301. var PoseEnabledControllerHelper = /** @class */ (function () {
  83302. function PoseEnabledControllerHelper() {
  83303. }
  83304. /**
  83305. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  83306. * @param vrGamepad the gamepad to initialized
  83307. * @returns a vr controller of the type the gamepad identified as
  83308. */
  83309. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  83310. // Oculus Touch
  83311. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  83312. return new BABYLON.OculusTouchController(vrGamepad);
  83313. }
  83314. // Windows Mixed Reality controllers
  83315. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  83316. return new BABYLON.WindowsMotionController(vrGamepad);
  83317. }
  83318. // HTC Vive
  83319. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  83320. return new BABYLON.ViveController(vrGamepad);
  83321. }
  83322. // Samsung/Oculus Gear VR or Oculus Go
  83323. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0 || vrGamepad.id.indexOf('Oculus Go') !== -1) {
  83324. return new BABYLON.GearVRController(vrGamepad);
  83325. }
  83326. // Google Daydream
  83327. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  83328. return new BABYLON.DaydreamController(vrGamepad);
  83329. }
  83330. // Generic
  83331. else {
  83332. return new BABYLON.GenericController(vrGamepad);
  83333. }
  83334. };
  83335. return PoseEnabledControllerHelper;
  83336. }());
  83337. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  83338. /**
  83339. * Defines the PoseEnabledController object that contains state of a vr capable controller
  83340. */
  83341. var PoseEnabledController = /** @class */ (function (_super) {
  83342. __extends(PoseEnabledController, _super);
  83343. /**
  83344. * Creates a new PoseEnabledController from a gamepad
  83345. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  83346. */
  83347. function PoseEnabledController(browserGamepad) {
  83348. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  83349. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  83350. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  83351. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  83352. /**
  83353. * The device position in babylon space
  83354. */
  83355. _this.devicePosition = BABYLON.Vector3.Zero();
  83356. /**
  83357. * The device rotation in babylon space
  83358. */
  83359. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  83360. /**
  83361. * The scale factor of the device in babylon space
  83362. */
  83363. _this.deviceScaleFactor = 1;
  83364. // Used to convert 6dof controllers to 3dof
  83365. _this._trackPosition = true;
  83366. _this._maxRotationDistFromHeadset = Math.PI / 5;
  83367. _this._draggedRoomRotation = 0;
  83368. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  83369. /**
  83370. * Internal, matrix used to convert room space to babylon space
  83371. * @hidden
  83372. */
  83373. _this._deviceToWorld = BABYLON.Matrix.Identity();
  83374. /**
  83375. * Node to be used when casting a ray from the controller
  83376. * @hidden
  83377. */
  83378. _this._pointingPoseNode = null;
  83379. _this._workingMatrix = BABYLON.Matrix.Identity();
  83380. /**
  83381. * @hidden
  83382. */
  83383. _this._meshAttachedObservable = new BABYLON.Observable();
  83384. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  83385. _this.controllerType = PoseEnabledControllerType.GENERIC;
  83386. _this.position = BABYLON.Vector3.Zero();
  83387. _this.rotationQuaternion = new BABYLON.Quaternion();
  83388. _this._calculatedPosition = BABYLON.Vector3.Zero();
  83389. _this._calculatedRotation = new BABYLON.Quaternion();
  83390. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  83391. return _this;
  83392. }
  83393. /**
  83394. * @hidden
  83395. */
  83396. PoseEnabledController.prototype._disableTrackPosition = function (fixedPosition) {
  83397. if (this._trackPosition) {
  83398. this._calculatedPosition.copyFrom(fixedPosition);
  83399. this._trackPosition = false;
  83400. }
  83401. };
  83402. /**
  83403. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  83404. */
  83405. PoseEnabledController.prototype.update = function () {
  83406. _super.prototype.update.call(this);
  83407. this._updatePoseAndMesh();
  83408. };
  83409. /**
  83410. * Updates only the pose device and mesh without doing any button event checking
  83411. */
  83412. PoseEnabledController.prototype._updatePoseAndMesh = function () {
  83413. var pose = this.browserGamepad.pose;
  83414. this.updateFromDevice(pose);
  83415. if (!this._trackPosition && BABYLON.Engine.LastCreatedScene && BABYLON.Engine.LastCreatedScene.activeCamera && BABYLON.Engine.LastCreatedScene.activeCamera.devicePosition) {
  83416. var camera = BABYLON.Engine.LastCreatedScene.activeCamera;
  83417. camera._computeDevicePosition();
  83418. this._deviceToWorld.setTranslation(camera.devicePosition);
  83419. if (camera.deviceRotationQuaternion) {
  83420. var camera = camera;
  83421. camera._deviceRoomRotationQuaternion.toEulerAnglesToRef(BABYLON.Tmp.Vector3[0]);
  83422. // Find the radian distance away that the headset is from the controllers rotation
  83423. var distanceAway = Math.atan2(Math.sin(BABYLON.Tmp.Vector3[0].y - this._draggedRoomRotation), Math.cos(BABYLON.Tmp.Vector3[0].y - this._draggedRoomRotation));
  83424. if (Math.abs(distanceAway) > this._maxRotationDistFromHeadset) {
  83425. // Only rotate enouph to be within the _maxRotationDistFromHeadset
  83426. var rotationAmount = distanceAway - (distanceAway < 0 ? -this._maxRotationDistFromHeadset : this._maxRotationDistFromHeadset);
  83427. this._draggedRoomRotation += rotationAmount;
  83428. // Rotate controller around headset
  83429. var sin = Math.sin(-rotationAmount);
  83430. var cos = Math.cos(-rotationAmount);
  83431. this._calculatedPosition.x = this._calculatedPosition.x * cos - this._calculatedPosition.z * sin;
  83432. this._calculatedPosition.z = this._calculatedPosition.x * sin + this._calculatedPosition.z * cos;
  83433. }
  83434. }
  83435. }
  83436. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  83437. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  83438. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  83439. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  83440. if (this._mesh) {
  83441. this._mesh.position.copyFrom(this.devicePosition);
  83442. if (this._mesh.rotationQuaternion) {
  83443. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  83444. }
  83445. }
  83446. };
  83447. /**
  83448. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  83449. * @param poseData raw pose fromthe device
  83450. */
  83451. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  83452. if (poseData) {
  83453. this.rawPose = poseData;
  83454. if (poseData.position) {
  83455. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  83456. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  83457. this._deviceRoomPosition.z *= -1;
  83458. }
  83459. if (this._trackPosition) {
  83460. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  83461. }
  83462. this._calculatedPosition.addInPlace(this.position);
  83463. }
  83464. var pose = this.rawPose;
  83465. if (poseData.orientation && pose.orientation) {
  83466. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  83467. if (this._mesh) {
  83468. if (this._mesh.getScene().useRightHandedSystem) {
  83469. this._deviceRoomRotationQuaternion.z *= -1;
  83470. this._deviceRoomRotationQuaternion.w *= -1;
  83471. }
  83472. else {
  83473. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  83474. }
  83475. }
  83476. // if the camera is set, rotate to the camera's rotation
  83477. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  83478. }
  83479. }
  83480. };
  83481. /**
  83482. * Attaches a mesh to the controller
  83483. * @param mesh the mesh to be attached
  83484. */
  83485. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  83486. if (this._mesh) {
  83487. this._mesh.parent = null;
  83488. }
  83489. this._mesh = mesh;
  83490. if (this._poseControlledCamera) {
  83491. this._mesh.parent = this._poseControlledCamera;
  83492. }
  83493. if (!this._mesh.rotationQuaternion) {
  83494. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  83495. }
  83496. // 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
  83497. this._updatePoseAndMesh();
  83498. if (this._pointingPoseNode) {
  83499. var parents = [];
  83500. var obj = this._pointingPoseNode;
  83501. while (obj.parent) {
  83502. parents.push(obj.parent);
  83503. obj = obj.parent;
  83504. }
  83505. parents.reverse().forEach(function (p) { p.computeWorldMatrix(true); });
  83506. }
  83507. this._meshAttachedObservable.notifyObservers(mesh);
  83508. };
  83509. /**
  83510. * Attaches the controllers mesh to a camera
  83511. * @param camera the camera the mesh should be attached to
  83512. */
  83513. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  83514. this._poseControlledCamera = camera;
  83515. if (this._mesh) {
  83516. this._mesh.parent = this._poseControlledCamera;
  83517. }
  83518. };
  83519. /**
  83520. * Disposes of the controller
  83521. */
  83522. PoseEnabledController.prototype.dispose = function () {
  83523. if (this._mesh) {
  83524. this._mesh.dispose();
  83525. }
  83526. this._mesh = null;
  83527. _super.prototype.dispose.call(this);
  83528. };
  83529. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  83530. /**
  83531. * The mesh that is attached to the controller
  83532. */
  83533. get: function () {
  83534. return this._mesh;
  83535. },
  83536. enumerable: true,
  83537. configurable: true
  83538. });
  83539. /**
  83540. * Gets the ray of the controller in the direction the controller is pointing
  83541. * @param length the length the resulting ray should be
  83542. * @returns a ray in the direction the controller is pointing
  83543. */
  83544. PoseEnabledController.prototype.getForwardRay = function (length) {
  83545. if (length === void 0) { length = 100; }
  83546. if (!this.mesh) {
  83547. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  83548. }
  83549. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  83550. var origin = m.getTranslation();
  83551. var forward = new BABYLON.Vector3(0, 0, -1);
  83552. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  83553. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  83554. return new BABYLON.Ray(origin, direction, length);
  83555. };
  83556. /**
  83557. * Name of the child mesh that can be used to cast a ray from the controller
  83558. */
  83559. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  83560. return PoseEnabledController;
  83561. }(BABYLON.Gamepad));
  83562. BABYLON.PoseEnabledController = PoseEnabledController;
  83563. })(BABYLON || (BABYLON = {}));
  83564. //# sourceMappingURL=babylon.poseEnabledController.js.map
  83565. var BABYLON;
  83566. (function (BABYLON) {
  83567. /**
  83568. * Defines the WebVRController object that represents controllers tracked in 3D space
  83569. */
  83570. var WebVRController = /** @class */ (function (_super) {
  83571. __extends(WebVRController, _super);
  83572. /**
  83573. * Creates a new WebVRController from a gamepad
  83574. * @param vrGamepad the gamepad that the WebVRController should be created from
  83575. */
  83576. function WebVRController(vrGamepad) {
  83577. var _this = _super.call(this, vrGamepad) || this;
  83578. // Observables
  83579. /**
  83580. * Fired when the trigger state has changed
  83581. */
  83582. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  83583. /**
  83584. * Fired when the main button state has changed
  83585. */
  83586. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  83587. /**
  83588. * Fired when the secondary button state has changed
  83589. */
  83590. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  83591. /**
  83592. * Fired when the pad state has changed
  83593. */
  83594. _this.onPadStateChangedObservable = new BABYLON.Observable();
  83595. /**
  83596. * Fired when controllers stick values have changed
  83597. */
  83598. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  83599. /**
  83600. * X and Y axis corrisponding to the controllers joystick
  83601. */
  83602. _this.pad = { x: 0, y: 0 };
  83603. // avoid GC, store state in a tmp object
  83604. _this._changes = {
  83605. pressChanged: false,
  83606. touchChanged: false,
  83607. valueChanged: false,
  83608. changed: false
  83609. };
  83610. _this._buttons = new Array(vrGamepad.buttons.length);
  83611. _this.hand = vrGamepad.hand;
  83612. return _this;
  83613. }
  83614. /**
  83615. * Fired when a controller button's state has changed
  83616. * @param callback the callback containing the button that was modified
  83617. */
  83618. WebVRController.prototype.onButtonStateChange = function (callback) {
  83619. this._onButtonStateChange = callback;
  83620. };
  83621. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  83622. /**
  83623. * The default controller model for the controller
  83624. */
  83625. get: function () {
  83626. return this._defaultModel;
  83627. },
  83628. enumerable: true,
  83629. configurable: true
  83630. });
  83631. /**
  83632. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  83633. */
  83634. WebVRController.prototype.update = function () {
  83635. _super.prototype.update.call(this);
  83636. for (var index = 0; index < this._buttons.length; index++) {
  83637. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  83638. }
  83639. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  83640. this.pad.x = this.leftStick.x;
  83641. this.pad.y = this.leftStick.y;
  83642. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  83643. }
  83644. };
  83645. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  83646. if (!newState) {
  83647. newState = {
  83648. pressed: false,
  83649. touched: false,
  83650. value: 0
  83651. };
  83652. }
  83653. if (!currentState) {
  83654. this._buttons[buttonIndex] = {
  83655. pressed: newState.pressed,
  83656. touched: newState.touched,
  83657. value: newState.value
  83658. };
  83659. return;
  83660. }
  83661. this._checkChanges(newState, currentState);
  83662. if (this._changes.changed) {
  83663. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  83664. this._handleButtonChange(buttonIndex, newState, this._changes);
  83665. }
  83666. this._buttons[buttonIndex].pressed = newState.pressed;
  83667. this._buttons[buttonIndex].touched = newState.touched;
  83668. // oculus triggers are never 0, thou not touched.
  83669. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  83670. };
  83671. WebVRController.prototype._checkChanges = function (newState, currentState) {
  83672. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  83673. this._changes.touchChanged = newState.touched !== currentState.touched;
  83674. this._changes.valueChanged = newState.value !== currentState.value;
  83675. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  83676. return this._changes;
  83677. };
  83678. /**
  83679. * Disposes of th webVRCOntroller
  83680. */
  83681. WebVRController.prototype.dispose = function () {
  83682. _super.prototype.dispose.call(this);
  83683. this.onTriggerStateChangedObservable.clear();
  83684. this.onMainButtonStateChangedObservable.clear();
  83685. this.onSecondaryButtonStateChangedObservable.clear();
  83686. this.onPadStateChangedObservable.clear();
  83687. this.onPadValuesChangedObservable.clear();
  83688. };
  83689. return WebVRController;
  83690. }(BABYLON.PoseEnabledController));
  83691. BABYLON.WebVRController = WebVRController;
  83692. })(BABYLON || (BABYLON = {}));
  83693. //# sourceMappingURL=babylon.webVRController.js.map
  83694. var BABYLON;
  83695. (function (BABYLON) {
  83696. /**
  83697. * Oculus Touch Controller
  83698. */
  83699. var OculusTouchController = /** @class */ (function (_super) {
  83700. __extends(OculusTouchController, _super);
  83701. /**
  83702. * Creates a new OculusTouchController from a gamepad
  83703. * @param vrGamepad the gamepad that the controller should be created from
  83704. */
  83705. function OculusTouchController(vrGamepad) {
  83706. var _this = _super.call(this, vrGamepad) || this;
  83707. /**
  83708. * Fired when the secondary trigger on this controller is modified
  83709. */
  83710. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  83711. /**
  83712. * Fired when the thumb rest on this controller is modified
  83713. */
  83714. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  83715. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  83716. return _this;
  83717. }
  83718. /**
  83719. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  83720. * @param scene scene in which to add meshes
  83721. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  83722. */
  83723. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  83724. var _this = this;
  83725. var meshName;
  83726. // Hand
  83727. if (this.hand === 'left') {
  83728. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  83729. }
  83730. else { // Right is the default if no hand is specified
  83731. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  83732. }
  83733. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  83734. /*
  83735. Parent Mesh name: oculus_touch_left
  83736. - body
  83737. - trigger
  83738. - thumbstick
  83739. - grip
  83740. - button_y
  83741. - button_x
  83742. - button_enter
  83743. */
  83744. _this._defaultModel = newMeshes[1];
  83745. _this.attachToMesh(_this._defaultModel);
  83746. if (meshLoaded) {
  83747. meshLoaded(_this._defaultModel);
  83748. }
  83749. });
  83750. };
  83751. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  83752. /**
  83753. * Fired when the A button on this controller is modified
  83754. */
  83755. get: function () {
  83756. if (this.hand === 'right') {
  83757. return this.onMainButtonStateChangedObservable;
  83758. }
  83759. else {
  83760. throw new Error('No A button on left hand');
  83761. }
  83762. },
  83763. enumerable: true,
  83764. configurable: true
  83765. });
  83766. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  83767. /**
  83768. * Fired when the B button on this controller is modified
  83769. */
  83770. get: function () {
  83771. if (this.hand === 'right') {
  83772. return this.onSecondaryButtonStateChangedObservable;
  83773. }
  83774. else {
  83775. throw new Error('No B button on left hand');
  83776. }
  83777. },
  83778. enumerable: true,
  83779. configurable: true
  83780. });
  83781. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  83782. /**
  83783. * Fired when the X button on this controller is modified
  83784. */
  83785. get: function () {
  83786. if (this.hand === 'left') {
  83787. return this.onMainButtonStateChangedObservable;
  83788. }
  83789. else {
  83790. throw new Error('No X button on right hand');
  83791. }
  83792. },
  83793. enumerable: true,
  83794. configurable: true
  83795. });
  83796. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  83797. /**
  83798. * Fired when the Y button on this controller is modified
  83799. */
  83800. get: function () {
  83801. if (this.hand === 'left') {
  83802. return this.onSecondaryButtonStateChangedObservable;
  83803. }
  83804. else {
  83805. throw new Error('No Y button on right hand');
  83806. }
  83807. },
  83808. enumerable: true,
  83809. configurable: true
  83810. });
  83811. /**
  83812. * Called once for each button that changed state since the last frame
  83813. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  83814. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  83815. * 2) secondary trigger (same)
  83816. * 3) A (right) X (left), touch, pressed = value
  83817. * 4) B / Y
  83818. * 5) thumb rest
  83819. * @param buttonIdx Which button index changed
  83820. * @param state New state of the button
  83821. * @param changes Which properties on the state changed since last frame
  83822. */
  83823. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  83824. var notifyObject = state; //{ state: state, changes: changes };
  83825. var triggerDirection = this.hand === 'right' ? -1 : 1;
  83826. switch (buttonIdx) {
  83827. case 0:
  83828. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  83829. return;
  83830. case 1: // index trigger
  83831. if (this._defaultModel) {
  83832. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  83833. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  83834. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  83835. }
  83836. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  83837. return;
  83838. case 2: // secondary trigger
  83839. if (this._defaultModel) {
  83840. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  83841. }
  83842. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  83843. return;
  83844. case 3:
  83845. if (this._defaultModel) {
  83846. if (notifyObject.pressed) {
  83847. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  83848. }
  83849. else {
  83850. (this._defaultModel.getChildren()[1]).position.y = 0;
  83851. }
  83852. }
  83853. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  83854. return;
  83855. case 4:
  83856. if (this._defaultModel) {
  83857. if (notifyObject.pressed) {
  83858. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  83859. }
  83860. else {
  83861. (this._defaultModel.getChildren()[2]).position.y = 0;
  83862. }
  83863. }
  83864. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  83865. return;
  83866. case 5:
  83867. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  83868. return;
  83869. }
  83870. };
  83871. /**
  83872. * Base Url for the controller model.
  83873. */
  83874. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  83875. /**
  83876. * File name for the left controller model.
  83877. */
  83878. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  83879. /**
  83880. * File name for the right controller model.
  83881. */
  83882. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  83883. return OculusTouchController;
  83884. }(BABYLON.WebVRController));
  83885. BABYLON.OculusTouchController = OculusTouchController;
  83886. })(BABYLON || (BABYLON = {}));
  83887. //# sourceMappingURL=babylon.oculusTouchController.js.map
  83888. var BABYLON;
  83889. (function (BABYLON) {
  83890. /**
  83891. * Vive Controller
  83892. */
  83893. var ViveController = /** @class */ (function (_super) {
  83894. __extends(ViveController, _super);
  83895. /**
  83896. * Creates a new ViveController from a gamepad
  83897. * @param vrGamepad the gamepad that the controller should be created from
  83898. */
  83899. function ViveController(vrGamepad) {
  83900. var _this = _super.call(this, vrGamepad) || this;
  83901. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  83902. _this._invertLeftStickY = true;
  83903. return _this;
  83904. }
  83905. /**
  83906. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  83907. * @param scene scene in which to add meshes
  83908. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  83909. */
  83910. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  83911. var _this = this;
  83912. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  83913. /*
  83914. Parent Mesh name: ViveWand
  83915. - body
  83916. - r_gripper
  83917. - l_gripper
  83918. - menu_button
  83919. - system_button
  83920. - trackpad
  83921. - trigger
  83922. - LED
  83923. */
  83924. _this._defaultModel = newMeshes[1];
  83925. _this.attachToMesh(_this._defaultModel);
  83926. if (meshLoaded) {
  83927. meshLoaded(_this._defaultModel);
  83928. }
  83929. });
  83930. };
  83931. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  83932. /**
  83933. * Fired when the left button on this controller is modified
  83934. */
  83935. get: function () {
  83936. return this.onMainButtonStateChangedObservable;
  83937. },
  83938. enumerable: true,
  83939. configurable: true
  83940. });
  83941. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  83942. /**
  83943. * Fired when the right button on this controller is modified
  83944. */
  83945. get: function () {
  83946. return this.onMainButtonStateChangedObservable;
  83947. },
  83948. enumerable: true,
  83949. configurable: true
  83950. });
  83951. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  83952. /**
  83953. * Fired when the menu button on this controller is modified
  83954. */
  83955. get: function () {
  83956. return this.onSecondaryButtonStateChangedObservable;
  83957. },
  83958. enumerable: true,
  83959. configurable: true
  83960. });
  83961. /**
  83962. * Called once for each button that changed state since the last frame
  83963. * Vive mapping:
  83964. * 0: touchpad
  83965. * 1: trigger
  83966. * 2: left AND right buttons
  83967. * 3: menu button
  83968. * @param buttonIdx Which button index changed
  83969. * @param state New state of the button
  83970. * @param changes Which properties on the state changed since last frame
  83971. */
  83972. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  83973. var notifyObject = state; //{ state: state, changes: changes };
  83974. switch (buttonIdx) {
  83975. case 0:
  83976. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  83977. return;
  83978. case 1: // index trigger
  83979. if (this._defaultModel) {
  83980. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  83981. }
  83982. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  83983. return;
  83984. case 2: // left AND right button
  83985. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  83986. return;
  83987. case 3:
  83988. if (this._defaultModel) {
  83989. if (notifyObject.pressed) {
  83990. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  83991. }
  83992. else {
  83993. (this._defaultModel.getChildren()[2]).position.y = 0;
  83994. }
  83995. }
  83996. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  83997. return;
  83998. }
  83999. };
  84000. /**
  84001. * Base Url for the controller model.
  84002. */
  84003. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  84004. /**
  84005. * File name for the controller model.
  84006. */
  84007. ViveController.MODEL_FILENAME = 'wand.babylon';
  84008. return ViveController;
  84009. }(BABYLON.WebVRController));
  84010. BABYLON.ViveController = ViveController;
  84011. })(BABYLON || (BABYLON = {}));
  84012. //# sourceMappingURL=babylon.viveController.js.map
  84013. var BABYLON;
  84014. (function (BABYLON) {
  84015. /**
  84016. * Generic Controller
  84017. */
  84018. var GenericController = /** @class */ (function (_super) {
  84019. __extends(GenericController, _super);
  84020. /**
  84021. * Creates a new GenericController from a gamepad
  84022. * @param vrGamepad the gamepad that the controller should be created from
  84023. */
  84024. function GenericController(vrGamepad) {
  84025. return _super.call(this, vrGamepad) || this;
  84026. }
  84027. /**
  84028. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  84029. * @param scene scene in which to add meshes
  84030. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  84031. */
  84032. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  84033. var _this = this;
  84034. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  84035. _this._defaultModel = newMeshes[1];
  84036. _this.attachToMesh(_this._defaultModel);
  84037. if (meshLoaded) {
  84038. meshLoaded(_this._defaultModel);
  84039. }
  84040. });
  84041. };
  84042. /**
  84043. * Called once for each button that changed state since the last frame
  84044. * @param buttonIdx Which button index changed
  84045. * @param state New state of the button
  84046. * @param changes Which properties on the state changed since last frame
  84047. */
  84048. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  84049. console.log("Button id: " + buttonIdx + "state: ");
  84050. console.dir(state);
  84051. };
  84052. /**
  84053. * Base Url for the controller model.
  84054. */
  84055. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  84056. /**
  84057. * File name for the controller model.
  84058. */
  84059. GenericController.MODEL_FILENAME = 'generic.babylon';
  84060. return GenericController;
  84061. }(BABYLON.WebVRController));
  84062. BABYLON.GenericController = GenericController;
  84063. })(BABYLON || (BABYLON = {}));
  84064. //# sourceMappingURL=babylon.genericController.js.map
  84065. var BABYLON;
  84066. (function (BABYLON) {
  84067. /**
  84068. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  84069. */
  84070. var LoadedMeshInfo = /** @class */ (function () {
  84071. function LoadedMeshInfo() {
  84072. /**
  84073. * Map of the button meshes contained in the controller
  84074. */
  84075. this.buttonMeshes = {};
  84076. /**
  84077. * Map of the axis meshes contained in the controller
  84078. */
  84079. this.axisMeshes = {};
  84080. }
  84081. return LoadedMeshInfo;
  84082. }());
  84083. /**
  84084. * Defines the WindowsMotionController object that the state of the windows motion controller
  84085. */
  84086. var WindowsMotionController = /** @class */ (function (_super) {
  84087. __extends(WindowsMotionController, _super);
  84088. /**
  84089. * Creates a new WindowsMotionController from a gamepad
  84090. * @param vrGamepad the gamepad that the controller should be created from
  84091. */
  84092. function WindowsMotionController(vrGamepad) {
  84093. var _this = _super.call(this, vrGamepad) || this;
  84094. _this._mapping = {
  84095. // Semantic button names
  84096. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  84097. // A mapping of the button name to glTF model node name
  84098. // that should be transformed by button value.
  84099. buttonMeshNames: {
  84100. 'trigger': 'SELECT',
  84101. 'menu': 'MENU',
  84102. 'grip': 'GRASP',
  84103. 'thumbstick': 'THUMBSTICK_PRESS',
  84104. 'trackpad': 'TOUCHPAD_PRESS'
  84105. },
  84106. // This mapping is used to translate from the Motion Controller to Babylon semantics
  84107. buttonObservableNames: {
  84108. 'trigger': 'onTriggerStateChangedObservable',
  84109. 'menu': 'onSecondaryButtonStateChangedObservable',
  84110. 'grip': 'onMainButtonStateChangedObservable',
  84111. 'thumbstick': 'onPadStateChangedObservable',
  84112. 'trackpad': 'onTrackpadChangedObservable'
  84113. },
  84114. // A mapping of the axis name to glTF model node name
  84115. // that should be transformed by axis value.
  84116. // This array mirrors the browserGamepad.axes array, such that
  84117. // the mesh corresponding to axis 0 is in this array index 0.
  84118. axisMeshNames: [
  84119. 'THUMBSTICK_X',
  84120. 'THUMBSTICK_Y',
  84121. 'TOUCHPAD_TOUCH_X',
  84122. 'TOUCHPAD_TOUCH_Y'
  84123. ],
  84124. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  84125. };
  84126. /**
  84127. * Fired when the trackpad on this controller is clicked
  84128. */
  84129. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  84130. /**
  84131. * Fired when the trackpad on this controller is modified
  84132. */
  84133. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  84134. /**
  84135. * The current x and y values of this controller's trackpad
  84136. */
  84137. _this.trackpad = { x: 0, y: 0 };
  84138. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  84139. _this._loadedMeshInfo = null;
  84140. return _this;
  84141. }
  84142. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  84143. /**
  84144. * Fired when the trigger on this controller is modified
  84145. */
  84146. get: function () {
  84147. return this.onTriggerStateChangedObservable;
  84148. },
  84149. enumerable: true,
  84150. configurable: true
  84151. });
  84152. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  84153. /**
  84154. * Fired when the menu button on this controller is modified
  84155. */
  84156. get: function () {
  84157. return this.onSecondaryButtonStateChangedObservable;
  84158. },
  84159. enumerable: true,
  84160. configurable: true
  84161. });
  84162. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  84163. /**
  84164. * Fired when the grip button on this controller is modified
  84165. */
  84166. get: function () {
  84167. return this.onMainButtonStateChangedObservable;
  84168. },
  84169. enumerable: true,
  84170. configurable: true
  84171. });
  84172. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  84173. /**
  84174. * Fired when the thumbstick button on this controller is modified
  84175. */
  84176. get: function () {
  84177. return this.onPadStateChangedObservable;
  84178. },
  84179. enumerable: true,
  84180. configurable: true
  84181. });
  84182. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  84183. /**
  84184. * Fired when the touchpad button on this controller is modified
  84185. */
  84186. get: function () {
  84187. return this.onTrackpadChangedObservable;
  84188. },
  84189. enumerable: true,
  84190. configurable: true
  84191. });
  84192. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  84193. /**
  84194. * Fired when the touchpad values on this controller are modified
  84195. */
  84196. get: function () {
  84197. return this.onTrackpadValuesChangedObservable;
  84198. },
  84199. enumerable: true,
  84200. configurable: true
  84201. });
  84202. WindowsMotionController.prototype._updateTrackpad = function () {
  84203. if (this.browserGamepad.axes && (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y)) {
  84204. this.trackpad.x = this.browserGamepad["axes"][2];
  84205. this.trackpad.y = this.browserGamepad["axes"][3];
  84206. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  84207. }
  84208. };
  84209. /**
  84210. * Called once per frame by the engine.
  84211. */
  84212. WindowsMotionController.prototype.update = function () {
  84213. _super.prototype.update.call(this);
  84214. if (this.browserGamepad.axes) {
  84215. this._updateTrackpad();
  84216. // Only need to animate axes if there is a loaded mesh
  84217. if (this._loadedMeshInfo) {
  84218. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  84219. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  84220. }
  84221. }
  84222. }
  84223. };
  84224. /**
  84225. * Called once for each button that changed state since the last frame
  84226. * @param buttonIdx Which button index changed
  84227. * @param state New state of the button
  84228. * @param changes Which properties on the state changed since last frame
  84229. */
  84230. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  84231. var buttonName = this._mapping.buttons[buttonIdx];
  84232. if (!buttonName) {
  84233. return;
  84234. }
  84235. // Update the trackpad to ensure trackpad.x/y are accurate during button events between frames
  84236. this._updateTrackpad();
  84237. // Only emit events for buttons that we know how to map from index to name
  84238. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  84239. if (observable) {
  84240. observable.notifyObservers(state);
  84241. }
  84242. this._lerpButtonTransform(buttonName, state.value);
  84243. };
  84244. /**
  84245. * Moves the buttons on the controller mesh based on their current state
  84246. * @param buttonName the name of the button to move
  84247. * @param buttonValue the value of the button which determines the buttons new position
  84248. */
  84249. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  84250. // If there is no loaded mesh, there is nothing to transform.
  84251. if (!this._loadedMeshInfo) {
  84252. return;
  84253. }
  84254. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  84255. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  84256. return;
  84257. }
  84258. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  84259. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  84260. };
  84261. /**
  84262. * Moves the axis on the controller mesh based on its current state
  84263. * @param axis the index of the axis
  84264. * @param axisValue the value of the axis which determines the meshes new position
  84265. * @hidden
  84266. */
  84267. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  84268. if (!this._loadedMeshInfo) {
  84269. return;
  84270. }
  84271. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  84272. if (!meshInfo) {
  84273. return;
  84274. }
  84275. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  84276. return;
  84277. }
  84278. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  84279. var lerpValue = axisValue * 0.5 + 0.5;
  84280. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  84281. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  84282. };
  84283. /**
  84284. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  84285. * @param scene scene in which to add meshes
  84286. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  84287. */
  84288. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  84289. var _this = this;
  84290. if (forceDefault === void 0) { forceDefault = false; }
  84291. var path;
  84292. var filename;
  84293. // Checking if GLB loader is present
  84294. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  84295. // Determine the device specific folder based on the ID suffix
  84296. var device = 'default';
  84297. if (this.id && !forceDefault) {
  84298. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  84299. device = ((match && match[0]) || device);
  84300. }
  84301. // Hand
  84302. if (this.hand === 'left') {
  84303. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  84304. }
  84305. else { // Right is the default if no hand is specified
  84306. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  84307. }
  84308. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  84309. }
  84310. else {
  84311. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  84312. path = BABYLON.GenericController.MODEL_BASE_URL;
  84313. filename = BABYLON.GenericController.MODEL_FILENAME;
  84314. }
  84315. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  84316. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  84317. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  84318. if (!_this._loadedMeshInfo) {
  84319. return;
  84320. }
  84321. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  84322. _this.attachToMesh(_this._defaultModel);
  84323. if (meshLoaded) {
  84324. meshLoaded(_this._defaultModel);
  84325. }
  84326. }, null, function (scene, message) {
  84327. BABYLON.Tools.Log(message);
  84328. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  84329. if (!forceDefault) {
  84330. _this.initControllerMesh(scene, meshLoaded, true);
  84331. }
  84332. });
  84333. };
  84334. /**
  84335. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  84336. * can be transformed by button presses and axes values, based on this._mapping.
  84337. *
  84338. * @param scene scene in which the meshes exist
  84339. * @param meshes list of meshes that make up the controller model to process
  84340. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  84341. */
  84342. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  84343. var loadedMeshInfo = null;
  84344. // Create a new mesh to contain the glTF hierarchy
  84345. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  84346. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  84347. var childMesh = null;
  84348. for (var i = 0; i < meshes.length; i++) {
  84349. var mesh = meshes[i];
  84350. if (!mesh.parent) {
  84351. // Exclude controller meshes from picking results
  84352. mesh.isPickable = false;
  84353. // Handle root node, attach to the new parentMesh
  84354. childMesh = mesh;
  84355. break;
  84356. }
  84357. }
  84358. if (childMesh) {
  84359. childMesh.setParent(parentMesh);
  84360. // Create our mesh info. Note that this method will always return non-null.
  84361. loadedMeshInfo = this.createMeshInfo(parentMesh);
  84362. }
  84363. else {
  84364. BABYLON.Tools.Warn('Could not find root node in model file.');
  84365. }
  84366. return loadedMeshInfo;
  84367. };
  84368. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  84369. var loadedMeshInfo = new LoadedMeshInfo();
  84370. var i;
  84371. loadedMeshInfo.rootNode = rootNode;
  84372. // Reset the caches
  84373. loadedMeshInfo.buttonMeshes = {};
  84374. loadedMeshInfo.axisMeshes = {};
  84375. // Button Meshes
  84376. for (i = 0; i < this._mapping.buttons.length; i++) {
  84377. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  84378. if (!buttonMeshName) {
  84379. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  84380. continue;
  84381. }
  84382. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  84383. if (!buttonMesh) {
  84384. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  84385. continue;
  84386. }
  84387. var buttonMeshInfo = {
  84388. index: i,
  84389. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  84390. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  84391. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  84392. };
  84393. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  84394. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  84395. }
  84396. else {
  84397. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  84398. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  84399. '(VALUE: ' + !!buttonMeshInfo.value +
  84400. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  84401. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  84402. ')');
  84403. }
  84404. }
  84405. // Axis Meshes
  84406. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  84407. var axisMeshName = this._mapping.axisMeshNames[i];
  84408. if (!axisMeshName) {
  84409. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  84410. continue;
  84411. }
  84412. var axisMesh = getChildByName(rootNode, axisMeshName);
  84413. if (!axisMesh) {
  84414. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  84415. continue;
  84416. }
  84417. var axisMeshInfo = {
  84418. index: i,
  84419. value: getImmediateChildByName(axisMesh, 'VALUE'),
  84420. min: getImmediateChildByName(axisMesh, 'MIN'),
  84421. max: getImmediateChildByName(axisMesh, 'MAX')
  84422. };
  84423. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  84424. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  84425. }
  84426. else {
  84427. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  84428. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  84429. '(VALUE: ' + !!axisMeshInfo.value +
  84430. ', MIN: ' + !!axisMeshInfo.min +
  84431. ', MAX:' + !!axisMeshInfo.max +
  84432. ')');
  84433. }
  84434. }
  84435. // Pointing Ray
  84436. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  84437. if (!loadedMeshInfo.pointingPoseNode) {
  84438. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  84439. }
  84440. else {
  84441. this._pointingPoseNode = loadedMeshInfo.pointingPoseNode;
  84442. }
  84443. return loadedMeshInfo;
  84444. // Look through all children recursively. This will return null if no mesh exists with the given name.
  84445. function getChildByName(node, name) {
  84446. return node.getChildren(function (n) { return n.name === name; }, false)[0];
  84447. }
  84448. // Look through only immediate children. This will return null if no mesh exists with the given name.
  84449. function getImmediateChildByName(node, name) {
  84450. return node.getChildren(function (n) { return n.name == name; }, true)[0];
  84451. }
  84452. };
  84453. /**
  84454. * Gets the ray of the controller in the direction the controller is pointing
  84455. * @param length the length the resulting ray should be
  84456. * @returns a ray in the direction the controller is pointing
  84457. */
  84458. WindowsMotionController.prototype.getForwardRay = function (length) {
  84459. if (length === void 0) { length = 100; }
  84460. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  84461. return _super.prototype.getForwardRay.call(this, length);
  84462. }
  84463. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  84464. var origin = m.getTranslation();
  84465. var forward = new BABYLON.Vector3(0, 0, -1);
  84466. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  84467. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  84468. return new BABYLON.Ray(origin, direction, length);
  84469. };
  84470. /**
  84471. * Disposes of the controller
  84472. */
  84473. WindowsMotionController.prototype.dispose = function () {
  84474. _super.prototype.dispose.call(this);
  84475. this.onTrackpadChangedObservable.clear();
  84476. };
  84477. /**
  84478. * The base url used to load the left and right controller models
  84479. */
  84480. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  84481. /**
  84482. * The name of the left controller model file
  84483. */
  84484. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  84485. /**
  84486. * The name of the right controller model file
  84487. */
  84488. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  84489. /**
  84490. * The controller name prefix for this controller type
  84491. */
  84492. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  84493. /**
  84494. * The controller id pattern for this controller type
  84495. */
  84496. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  84497. return WindowsMotionController;
  84498. }(BABYLON.WebVRController));
  84499. BABYLON.WindowsMotionController = WindowsMotionController;
  84500. })(BABYLON || (BABYLON = {}));
  84501. //# sourceMappingURL=babylon.windowsMotionController.js.map
  84502. var BABYLON;
  84503. (function (BABYLON) {
  84504. /**
  84505. * Gear VR Controller
  84506. */
  84507. var GearVRController = /** @class */ (function (_super) {
  84508. __extends(GearVRController, _super);
  84509. /**
  84510. * Creates a new GearVRController from a gamepad
  84511. * @param vrGamepad the gamepad that the controller should be created from
  84512. */
  84513. function GearVRController(vrGamepad) {
  84514. var _this = _super.call(this, vrGamepad) || this;
  84515. _this._buttonIndexToObservableNameMap = [
  84516. 'onTrackpadChangedObservable',
  84517. 'onTriggerStateChangedObservable' // Trigger
  84518. ];
  84519. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  84520. // Initial starting position defaults to where hand would be (incase of only 3dof controller)
  84521. _this._calculatedPosition = new BABYLON.Vector3(_this.hand == "left" ? -0.15 : 0.15, -0.5, 0.25);
  84522. _this._disableTrackPosition(_this._calculatedPosition);
  84523. return _this;
  84524. }
  84525. /**
  84526. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  84527. * @param scene scene in which to add meshes
  84528. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  84529. */
  84530. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  84531. var _this = this;
  84532. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  84533. // Offset the controller so it will rotate around the users wrist
  84534. var mesh = new BABYLON.Mesh("", scene);
  84535. newMeshes[1].parent = mesh;
  84536. newMeshes[1].position.z = -0.15;
  84537. _this._defaultModel = mesh;
  84538. _this.attachToMesh(_this._defaultModel);
  84539. if (meshLoaded) {
  84540. meshLoaded(_this._defaultModel);
  84541. }
  84542. });
  84543. };
  84544. /**
  84545. * Called once for each button that changed state since the last frame
  84546. * @param buttonIdx Which button index changed
  84547. * @param state New state of the button
  84548. * @param changes Which properties on the state changed since last frame
  84549. */
  84550. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  84551. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  84552. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  84553. // Only emit events for buttons that we know how to map from index to observable
  84554. var observable = this[observableName];
  84555. if (observable) {
  84556. observable.notifyObservers(state);
  84557. }
  84558. }
  84559. };
  84560. /**
  84561. * Base Url for the controller model.
  84562. */
  84563. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  84564. /**
  84565. * File name for the controller model.
  84566. */
  84567. GearVRController.MODEL_FILENAME = 'generic.babylon';
  84568. /**
  84569. * Gamepad Id prefix used to identify this controller.
  84570. */
  84571. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  84572. return GearVRController;
  84573. }(BABYLON.WebVRController));
  84574. BABYLON.GearVRController = GearVRController;
  84575. })(BABYLON || (BABYLON = {}));
  84576. //# sourceMappingURL=babylon.gearVRController.js.map
  84577. var BABYLON;
  84578. (function (BABYLON) {
  84579. /**
  84580. * Google Daydream controller
  84581. */
  84582. var DaydreamController = /** @class */ (function (_super) {
  84583. __extends(DaydreamController, _super);
  84584. /**
  84585. * Creates a new DaydreamController from a gamepad
  84586. * @param vrGamepad the gamepad that the controller should be created from
  84587. */
  84588. function DaydreamController(vrGamepad) {
  84589. var _this = _super.call(this, vrGamepad) || this;
  84590. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  84591. return _this;
  84592. }
  84593. /**
  84594. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  84595. * @param scene scene in which to add meshes
  84596. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  84597. */
  84598. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  84599. var _this = this;
  84600. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  84601. _this._defaultModel = newMeshes[1];
  84602. _this.attachToMesh(_this._defaultModel);
  84603. if (meshLoaded) {
  84604. meshLoaded(_this._defaultModel);
  84605. }
  84606. });
  84607. };
  84608. /**
  84609. * Called once for each button that changed state since the last frame
  84610. * @param buttonIdx Which button index changed
  84611. * @param state New state of the button
  84612. * @param changes Which properties on the state changed since last frame
  84613. */
  84614. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  84615. // Daydream controller only has 1 GamepadButton (on the trackpad).
  84616. if (buttonIdx === 0) {
  84617. var observable = this.onTriggerStateChangedObservable;
  84618. if (observable) {
  84619. observable.notifyObservers(state);
  84620. }
  84621. }
  84622. else {
  84623. // If the app or home buttons are ever made available
  84624. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  84625. }
  84626. };
  84627. /**
  84628. * Base Url for the controller model.
  84629. */
  84630. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  84631. /**
  84632. * File name for the controller model.
  84633. */
  84634. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  84635. /**
  84636. * Gamepad Id prefix used to identify Daydream Controller.
  84637. */
  84638. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  84639. return DaydreamController;
  84640. }(BABYLON.WebVRController));
  84641. BABYLON.DaydreamController = DaydreamController;
  84642. })(BABYLON || (BABYLON = {}));
  84643. //# sourceMappingURL=babylon.daydreamController.js.map
  84644. var BABYLON;
  84645. (function (BABYLON) {
  84646. Object.defineProperty(BABYLON.Scene.prototype, "gamepadManager", {
  84647. get: function () {
  84648. if (!this._gamepadManager) {
  84649. this._gamepadManager = new BABYLON.GamepadManager(this);
  84650. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_GAMEPAD);
  84651. if (!component) {
  84652. component = new GamepadSystemSceneComponent(this);
  84653. this._addComponent(component);
  84654. }
  84655. }
  84656. return this._gamepadManager;
  84657. },
  84658. enumerable: true,
  84659. configurable: true
  84660. });
  84661. /**
  84662. * Adds a gamepad to the free camera inputs manager
  84663. */
  84664. BABYLON.FreeCameraInputsManager.prototype.addGamepad = function () {
  84665. this.add(new BABYLON.FreeCameraGamepadInput());
  84666. return this;
  84667. };
  84668. /**
  84669. * Adds a gamepad to the arc rotate camera inputs manager
  84670. */
  84671. BABYLON.ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  84672. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  84673. return this;
  84674. };
  84675. /**
  84676. * Defines the gamepad scene component responsible to manage gamepads in a given scene
  84677. */
  84678. var GamepadSystemSceneComponent = /** @class */ (function () {
  84679. /**
  84680. * Creates a new instance of the component for the given scene
  84681. * @param scene Defines the scene to register the component in
  84682. */
  84683. function GamepadSystemSceneComponent(scene) {
  84684. /**
  84685. * The component name helpfull to identify the component in the list of scene components.
  84686. */
  84687. this.name = BABYLON.SceneComponentConstants.NAME_GAMEPAD;
  84688. this.scene = scene;
  84689. }
  84690. /**
  84691. * Registers the component in a given scene
  84692. */
  84693. GamepadSystemSceneComponent.prototype.register = function () {
  84694. this.scene._beforeCameraUpdateStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD, this, this._beforeCameraUpdate);
  84695. };
  84696. /**
  84697. * Rebuilds the elements related to this component in case of
  84698. * context lost for instance.
  84699. */
  84700. GamepadSystemSceneComponent.prototype.rebuild = function () {
  84701. // Nothing to do for gamepads
  84702. };
  84703. /**
  84704. * Disposes the component and the associated ressources
  84705. */
  84706. GamepadSystemSceneComponent.prototype.dispose = function () {
  84707. var gamepadManager = this.scene._gamepadManager;
  84708. if (gamepadManager) {
  84709. gamepadManager.dispose();
  84710. this.scene._gamepadManager = null;
  84711. }
  84712. };
  84713. GamepadSystemSceneComponent.prototype._beforeCameraUpdate = function () {
  84714. var gamepadManager = this.scene._gamepadManager;
  84715. if (gamepadManager && gamepadManager._isMonitoring) {
  84716. gamepadManager._checkGamepadsStatus();
  84717. }
  84718. };
  84719. return GamepadSystemSceneComponent;
  84720. }());
  84721. BABYLON.GamepadSystemSceneComponent = GamepadSystemSceneComponent;
  84722. })(BABYLON || (BABYLON = {}));
  84723. //# sourceMappingURL=babylon.gamepadSceneComponent.js.map
  84724. var BABYLON;
  84725. (function (BABYLON) {
  84726. BABYLON.Node.AddNodeConstructor("FollowCamera", function (name, scene) {
  84727. return function () { return new FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  84728. });
  84729. BABYLON.Node.AddNodeConstructor("ArcFollowCamera", function (name, scene) {
  84730. return function () { return new ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  84731. });
  84732. /**
  84733. * A follow camera takes a mesh as a target and follows it as it moves. Both a free camera version followCamera and
  84734. * an arc rotate version arcFollowCamera are available.
  84735. * @see http://doc.babylonjs.com/features/cameras#follow-camera
  84736. */
  84737. var FollowCamera = /** @class */ (function (_super) {
  84738. __extends(FollowCamera, _super);
  84739. /**
  84740. * Instantiates the follow camera.
  84741. * @see http://doc.babylonjs.com/features/cameras#follow-camera
  84742. * @param name Define the name of the camera in the scene
  84743. * @param position Define the position of the camera
  84744. * @param scene Define the scene the camera belong to
  84745. * @param lockedTarget Define the target of the camera
  84746. */
  84747. function FollowCamera(name, position, scene, lockedTarget) {
  84748. if (lockedTarget === void 0) { lockedTarget = null; }
  84749. var _this = _super.call(this, name, position, scene) || this;
  84750. /**
  84751. * Distance the follow camera should follow an object at
  84752. */
  84753. _this.radius = 12;
  84754. /**
  84755. * Define a rotation offset between the camera and the object it follows
  84756. */
  84757. _this.rotationOffset = 0;
  84758. /**
  84759. * Define a height offset between the camera and the object it follows.
  84760. * It can help following an object from the top (like a car chaing a plane)
  84761. */
  84762. _this.heightOffset = 4;
  84763. /**
  84764. * Define how fast the camera can accelerate to follow it s target.
  84765. */
  84766. _this.cameraAcceleration = 0.05;
  84767. /**
  84768. * Define the speed limit of the camera following an object.
  84769. */
  84770. _this.maxCameraSpeed = 20;
  84771. _this.lockedTarget = lockedTarget;
  84772. return _this;
  84773. }
  84774. FollowCamera.prototype._follow = function (cameraTarget) {
  84775. if (!cameraTarget) {
  84776. return;
  84777. }
  84778. var yRotation;
  84779. if (cameraTarget.rotationQuaternion) {
  84780. var rotMatrix = new BABYLON.Matrix();
  84781. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  84782. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  84783. }
  84784. else {
  84785. yRotation = cameraTarget.rotation.y;
  84786. }
  84787. var radians = BABYLON.Tools.ToRadians(this.rotationOffset) + yRotation;
  84788. var targetPosition = cameraTarget.getAbsolutePosition();
  84789. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  84790. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  84791. var dx = targetX - this.position.x;
  84792. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  84793. var dz = (targetZ) - this.position.z;
  84794. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  84795. var vy = dy * this.cameraAcceleration;
  84796. var vz = dz * this.cameraAcceleration * 2;
  84797. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  84798. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  84799. }
  84800. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  84801. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  84802. }
  84803. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  84804. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  84805. }
  84806. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  84807. this.setTarget(targetPosition);
  84808. };
  84809. /** @hidden */
  84810. FollowCamera.prototype._checkInputs = function () {
  84811. _super.prototype._checkInputs.call(this);
  84812. if (this.lockedTarget) {
  84813. this._follow(this.lockedTarget);
  84814. }
  84815. };
  84816. /**
  84817. * Gets the camera class name.
  84818. * @returns the class name
  84819. */
  84820. FollowCamera.prototype.getClassName = function () {
  84821. return "FollowCamera";
  84822. };
  84823. __decorate([
  84824. BABYLON.serialize()
  84825. ], FollowCamera.prototype, "radius", void 0);
  84826. __decorate([
  84827. BABYLON.serialize()
  84828. ], FollowCamera.prototype, "rotationOffset", void 0);
  84829. __decorate([
  84830. BABYLON.serialize()
  84831. ], FollowCamera.prototype, "heightOffset", void 0);
  84832. __decorate([
  84833. BABYLON.serialize()
  84834. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  84835. __decorate([
  84836. BABYLON.serialize()
  84837. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  84838. __decorate([
  84839. BABYLON.serializeAsMeshReference("lockedTargetId")
  84840. ], FollowCamera.prototype, "lockedTarget", void 0);
  84841. return FollowCamera;
  84842. }(BABYLON.TargetCamera));
  84843. BABYLON.FollowCamera = FollowCamera;
  84844. /**
  84845. * Arc Rotate version of the follow camera.
  84846. * It still follows a Defined mesh but in an Arc Rotate Camera fashion.
  84847. * @see http://doc.babylonjs.com/features/cameras#follow-camera
  84848. */
  84849. var ArcFollowCamera = /** @class */ (function (_super) {
  84850. __extends(ArcFollowCamera, _super);
  84851. /**
  84852. * Instantiates a new ArcFollowCamera
  84853. * @see http://doc.babylonjs.com/features/cameras#follow-camera
  84854. * @param name Define the name of the camera
  84855. * @param alpha Define the rotation angle of the camera around the logitudinal axis
  84856. * @param beta Define the rotation angle of the camera around the elevation axis
  84857. * @param radius Define the radius of the camera from its target point
  84858. * @param target Define the target of the camera
  84859. * @param scene Define the scene the camera belongs to
  84860. */
  84861. function ArcFollowCamera(name,
  84862. /** The longitudinal angle of the camera */
  84863. alpha,
  84864. /** The latitudinal angle of the camera */
  84865. beta,
  84866. /** The radius of the camera from its target */
  84867. radius,
  84868. /** Define the camera target (the messh it should follow) */
  84869. target, scene) {
  84870. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  84871. _this.alpha = alpha;
  84872. _this.beta = beta;
  84873. _this.radius = radius;
  84874. _this.target = target;
  84875. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  84876. _this._follow();
  84877. return _this;
  84878. }
  84879. ArcFollowCamera.prototype._follow = function () {
  84880. if (!this.target) {
  84881. return;
  84882. }
  84883. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  84884. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  84885. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  84886. var targetPosition = this.target.getAbsolutePosition();
  84887. this.position = targetPosition.add(this._cartesianCoordinates);
  84888. this.setTarget(targetPosition);
  84889. };
  84890. /** @hidden */
  84891. ArcFollowCamera.prototype._checkInputs = function () {
  84892. _super.prototype._checkInputs.call(this);
  84893. this._follow();
  84894. };
  84895. /**
  84896. * Returns the class name of the object.
  84897. * It is mostly used internally for serialization purposes.
  84898. */
  84899. ArcFollowCamera.prototype.getClassName = function () {
  84900. return "ArcFollowCamera";
  84901. };
  84902. return ArcFollowCamera;
  84903. }(BABYLON.TargetCamera));
  84904. BABYLON.ArcFollowCamera = ArcFollowCamera;
  84905. })(BABYLON || (BABYLON = {}));
  84906. //# sourceMappingURL=babylon.followCamera.js.map
  84907. var BABYLON;
  84908. (function (BABYLON) {
  84909. /**
  84910. * 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,
  84911. * which still works and will still be found in many Playgrounds.
  84912. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  84913. */
  84914. var UniversalCamera = /** @class */ (function (_super) {
  84915. __extends(UniversalCamera, _super);
  84916. /**
  84917. * 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,
  84918. * which still works and will still be found in many Playgrounds.
  84919. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  84920. * @param name Define the name of the camera in the scene
  84921. * @param position Define the start position of the camera in the scene
  84922. * @param scene Define the scene the camera belongs to
  84923. */
  84924. function UniversalCamera(name, position, scene) {
  84925. var _this = _super.call(this, name, position, scene) || this;
  84926. _this.inputs.addGamepad();
  84927. return _this;
  84928. }
  84929. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  84930. /**
  84931. * Defines the gamepad rotation sensiblity.
  84932. * This is the threshold from when rotation starts to be accounted for to prevent jittering.
  84933. */
  84934. get: function () {
  84935. var gamepad = this.inputs.attached["gamepad"];
  84936. if (gamepad) {
  84937. return gamepad.gamepadAngularSensibility;
  84938. }
  84939. return 0;
  84940. },
  84941. set: function (value) {
  84942. var gamepad = this.inputs.attached["gamepad"];
  84943. if (gamepad) {
  84944. gamepad.gamepadAngularSensibility = value;
  84945. }
  84946. },
  84947. enumerable: true,
  84948. configurable: true
  84949. });
  84950. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  84951. /**
  84952. * Defines the gamepad move sensiblity.
  84953. * This is the threshold from when moving starts to be accounted for for to prevent jittering.
  84954. */
  84955. get: function () {
  84956. var gamepad = this.inputs.attached["gamepad"];
  84957. if (gamepad) {
  84958. return gamepad.gamepadMoveSensibility;
  84959. }
  84960. return 0;
  84961. },
  84962. set: function (value) {
  84963. var gamepad = this.inputs.attached["gamepad"];
  84964. if (gamepad) {
  84965. gamepad.gamepadMoveSensibility = value;
  84966. }
  84967. },
  84968. enumerable: true,
  84969. configurable: true
  84970. });
  84971. /**
  84972. * Gets the current object class name.
  84973. * @return the class name
  84974. */
  84975. UniversalCamera.prototype.getClassName = function () {
  84976. return "UniversalCamera";
  84977. };
  84978. return UniversalCamera;
  84979. }(BABYLON.TouchCamera));
  84980. BABYLON.UniversalCamera = UniversalCamera;
  84981. })(BABYLON || (BABYLON = {}));
  84982. //# sourceMappingURL=babylon.universalCamera.js.map
  84983. var BABYLON;
  84984. (function (BABYLON) {
  84985. BABYLON.Node.AddNodeConstructor("GamepadCamera", function (name, scene) {
  84986. return function () { return new GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  84987. });
  84988. /**
  84989. * This represents a FPS type of camera. This is only here for back compat purpose.
  84990. * Please use the UniversalCamera instead as both are identical.
  84991. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  84992. */
  84993. var GamepadCamera = /** @class */ (function (_super) {
  84994. __extends(GamepadCamera, _super);
  84995. /**
  84996. * Instantiates a new Gamepad Camera
  84997. * This represents a FPS type of camera. This is only here for back compat purpose.
  84998. * Please use the UniversalCamera instead as both are identical.
  84999. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  85000. * @param name Define the name of the camera in the scene
  85001. * @param position Define the start position of the camera in the scene
  85002. * @param scene Define the scene the camera belongs to
  85003. */
  85004. function GamepadCamera(name, position, scene) {
  85005. return _super.call(this, name, position, scene) || this;
  85006. }
  85007. /**
  85008. * Gets the current object class name.
  85009. * @return the class name
  85010. */
  85011. GamepadCamera.prototype.getClassName = function () {
  85012. return "GamepadCamera";
  85013. };
  85014. return GamepadCamera;
  85015. }(BABYLON.UniversalCamera));
  85016. BABYLON.GamepadCamera = GamepadCamera;
  85017. })(BABYLON || (BABYLON = {}));
  85018. //# sourceMappingURL=babylon.gamepadCamera.js.map
  85019. var BABYLON;
  85020. (function (BABYLON) {
  85021. /**
  85022. * PostProcessRenderPipelineManager class
  85023. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  85024. */
  85025. var PostProcessRenderPipelineManager = /** @class */ (function () {
  85026. /**
  85027. * Initializes a PostProcessRenderPipelineManager
  85028. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  85029. */
  85030. function PostProcessRenderPipelineManager() {
  85031. this._renderPipelines = {};
  85032. }
  85033. /**
  85034. * Adds a pipeline to the manager
  85035. * @param renderPipeline The pipeline to add
  85036. */
  85037. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  85038. this._renderPipelines[renderPipeline._name] = renderPipeline;
  85039. };
  85040. /**
  85041. * Attaches a camera to the pipeline
  85042. * @param renderPipelineName The name of the pipeline to attach to
  85043. * @param cameras the camera to attach
  85044. * @param unique if the camera can be attached multiple times to the pipeline
  85045. */
  85046. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  85047. if (unique === void 0) { unique = false; }
  85048. var renderPipeline = this._renderPipelines[renderPipelineName];
  85049. if (!renderPipeline) {
  85050. return;
  85051. }
  85052. renderPipeline._attachCameras(cameras, unique);
  85053. };
  85054. /**
  85055. * Detaches a camera from the pipeline
  85056. * @param renderPipelineName The name of the pipeline to detach from
  85057. * @param cameras the camera to detach
  85058. */
  85059. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  85060. var renderPipeline = this._renderPipelines[renderPipelineName];
  85061. if (!renderPipeline) {
  85062. return;
  85063. }
  85064. renderPipeline._detachCameras(cameras);
  85065. };
  85066. /**
  85067. * Enables an effect by name on a pipeline
  85068. * @param renderPipelineName the name of the pipeline to enable the effect in
  85069. * @param renderEffectName the name of the effect to enable
  85070. * @param cameras the cameras that the effect should be enabled on
  85071. */
  85072. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  85073. var renderPipeline = this._renderPipelines[renderPipelineName];
  85074. if (!renderPipeline) {
  85075. return;
  85076. }
  85077. renderPipeline._enableEffect(renderEffectName, cameras);
  85078. };
  85079. /**
  85080. * Disables an effect by name on a pipeline
  85081. * @param renderPipelineName the name of the pipeline to disable the effect in
  85082. * @param renderEffectName the name of the effect to disable
  85083. * @param cameras the cameras that the effect should be disabled on
  85084. */
  85085. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  85086. var renderPipeline = this._renderPipelines[renderPipelineName];
  85087. if (!renderPipeline) {
  85088. return;
  85089. }
  85090. renderPipeline._disableEffect(renderEffectName, cameras);
  85091. };
  85092. /**
  85093. * Updates the state of all contained render pipelines and disposes of any non supported pipelines
  85094. */
  85095. PostProcessRenderPipelineManager.prototype.update = function () {
  85096. for (var renderPipelineName in this._renderPipelines) {
  85097. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  85098. var pipeline = this._renderPipelines[renderPipelineName];
  85099. if (!pipeline.isSupported) {
  85100. pipeline.dispose();
  85101. delete this._renderPipelines[renderPipelineName];
  85102. }
  85103. else {
  85104. pipeline._update();
  85105. }
  85106. }
  85107. }
  85108. };
  85109. /** @hidden */
  85110. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  85111. for (var renderPipelineName in this._renderPipelines) {
  85112. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  85113. var pipeline = this._renderPipelines[renderPipelineName];
  85114. pipeline._rebuild();
  85115. }
  85116. }
  85117. };
  85118. /**
  85119. * Disposes of the manager and pipelines
  85120. */
  85121. PostProcessRenderPipelineManager.prototype.dispose = function () {
  85122. for (var renderPipelineName in this._renderPipelines) {
  85123. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  85124. var pipeline = this._renderPipelines[renderPipelineName];
  85125. pipeline.dispose();
  85126. }
  85127. }
  85128. };
  85129. return PostProcessRenderPipelineManager;
  85130. }());
  85131. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  85132. })(BABYLON || (BABYLON = {}));
  85133. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  85134. var BABYLON;
  85135. (function (BABYLON) {
  85136. Object.defineProperty(BABYLON.Scene.prototype, "postProcessRenderPipelineManager", {
  85137. get: function () {
  85138. if (!this._postProcessRenderPipelineManager) {
  85139. // Register the G Buffer component to the scene.
  85140. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER);
  85141. if (!component) {
  85142. component = new PostProcessRenderPipelineManagerSceneComponent(this);
  85143. this._addComponent(component);
  85144. }
  85145. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  85146. }
  85147. return this._postProcessRenderPipelineManager;
  85148. },
  85149. enumerable: true,
  85150. configurable: true
  85151. });
  85152. /**
  85153. * Defines the Render Pipeline scene component responsible to rendering pipelines
  85154. */
  85155. var PostProcessRenderPipelineManagerSceneComponent = /** @class */ (function () {
  85156. /**
  85157. * Creates a new instance of the component for the given scene
  85158. * @param scene Defines the scene to register the component in
  85159. */
  85160. function PostProcessRenderPipelineManagerSceneComponent(scene) {
  85161. /**
  85162. * The component name helpfull to identify the component in the list of scene components.
  85163. */
  85164. this.name = BABYLON.SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER;
  85165. this.scene = scene;
  85166. }
  85167. /**
  85168. * Registers the component in a given scene
  85169. */
  85170. PostProcessRenderPipelineManagerSceneComponent.prototype.register = function () {
  85171. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER, this, this._gatherRenderTargets);
  85172. };
  85173. /**
  85174. * Rebuilds the elements related to this component in case of
  85175. * context lost for instance.
  85176. */
  85177. PostProcessRenderPipelineManagerSceneComponent.prototype.rebuild = function () {
  85178. if (this.scene._postProcessRenderPipelineManager) {
  85179. this.scene._postProcessRenderPipelineManager._rebuild();
  85180. }
  85181. };
  85182. /**
  85183. * Disposes the component and the associated ressources
  85184. */
  85185. PostProcessRenderPipelineManagerSceneComponent.prototype.dispose = function () {
  85186. if (this.scene._postProcessRenderPipelineManager) {
  85187. this.scene._postProcessRenderPipelineManager.dispose();
  85188. }
  85189. };
  85190. PostProcessRenderPipelineManagerSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  85191. if (this.scene._postProcessRenderPipelineManager) {
  85192. this.scene._postProcessRenderPipelineManager.update();
  85193. }
  85194. };
  85195. return PostProcessRenderPipelineManagerSceneComponent;
  85196. }());
  85197. BABYLON.PostProcessRenderPipelineManagerSceneComponent = PostProcessRenderPipelineManagerSceneComponent;
  85198. })(BABYLON || (BABYLON = {}));
  85199. //# sourceMappingURL=babylon.postProcessRenderPipelineManagerSceneComponent.js.map
  85200. var BABYLON;
  85201. (function (BABYLON) {
  85202. /**
  85203. * This represents a set of one or more post processes in Babylon.
  85204. * A post process can be used to apply a shader to a texture after it is rendered.
  85205. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  85206. */
  85207. var PostProcessRenderEffect = /** @class */ (function () {
  85208. /**
  85209. * Instantiates a post process render effect.
  85210. * A post process can be used to apply a shader to a texture after it is rendered.
  85211. * @param engine The engine the effect is tied to
  85212. * @param name The name of the effect
  85213. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  85214. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  85215. */
  85216. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  85217. this._name = name;
  85218. this._singleInstance = singleInstance || true;
  85219. this._getPostProcesses = getPostProcesses;
  85220. this._cameras = {};
  85221. this._indicesForCamera = {};
  85222. this._postProcesses = {};
  85223. }
  85224. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  85225. /**
  85226. * Checks if all the post processes in the effect are supported.
  85227. */
  85228. get: function () {
  85229. for (var index in this._postProcesses) {
  85230. if (this._postProcesses.hasOwnProperty(index)) {
  85231. var pps = this._postProcesses[index];
  85232. for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {
  85233. if (!pps[ppIndex].isSupported) {
  85234. return false;
  85235. }
  85236. }
  85237. }
  85238. }
  85239. return true;
  85240. },
  85241. enumerable: true,
  85242. configurable: true
  85243. });
  85244. /**
  85245. * Updates the current state of the effect
  85246. * @hidden
  85247. */
  85248. PostProcessRenderEffect.prototype._update = function () {
  85249. };
  85250. /**
  85251. * Attaches the effect on cameras
  85252. * @param cameras The camera to attach to.
  85253. * @hidden
  85254. */
  85255. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  85256. var _this = this;
  85257. var cameraKey;
  85258. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  85259. if (!cams) {
  85260. return;
  85261. }
  85262. for (var i = 0; i < cams.length; i++) {
  85263. var camera = cams[i];
  85264. var cameraName = camera.name;
  85265. if (this._singleInstance) {
  85266. cameraKey = 0;
  85267. }
  85268. else {
  85269. cameraKey = cameraName;
  85270. }
  85271. if (!this._postProcesses[cameraKey]) {
  85272. var postProcess = this._getPostProcesses();
  85273. if (postProcess) {
  85274. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  85275. }
  85276. }
  85277. if (!this._indicesForCamera[cameraName]) {
  85278. this._indicesForCamera[cameraName] = [];
  85279. }
  85280. this._postProcesses[cameraKey].forEach(function (postProcess) {
  85281. var index = camera.attachPostProcess(postProcess);
  85282. _this._indicesForCamera[cameraName].push(index);
  85283. });
  85284. if (!this._cameras[cameraName]) {
  85285. this._cameras[cameraName] = camera;
  85286. }
  85287. }
  85288. };
  85289. /**
  85290. * Detatches the effect on cameras
  85291. * @param cameras The camera to detatch from.
  85292. * @hidden
  85293. */
  85294. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  85295. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  85296. if (!cams) {
  85297. return;
  85298. }
  85299. for (var i = 0; i < cams.length; i++) {
  85300. var camera = cams[i];
  85301. var cameraName = camera.name;
  85302. var postProcesses = this._postProcesses[this._singleInstance ? 0 : cameraName];
  85303. if (postProcesses) {
  85304. postProcesses.forEach(function (postProcess) {
  85305. camera.detachPostProcess(postProcess);
  85306. });
  85307. }
  85308. if (this._cameras[cameraName]) {
  85309. this._cameras[cameraName] = null;
  85310. }
  85311. }
  85312. };
  85313. /**
  85314. * Enables the effect on given cameras
  85315. * @param cameras The camera to enable.
  85316. * @hidden
  85317. */
  85318. PostProcessRenderEffect.prototype._enable = function (cameras) {
  85319. var _this = this;
  85320. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  85321. if (!cams) {
  85322. return;
  85323. }
  85324. for (var i = 0; i < cams.length; i++) {
  85325. var camera = cams[i];
  85326. var cameraName = camera.name;
  85327. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  85328. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  85329. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  85330. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  85331. });
  85332. }
  85333. }
  85334. }
  85335. };
  85336. /**
  85337. * Disables the effect on the given cameras
  85338. * @param cameras The camera to disable.
  85339. * @hidden
  85340. */
  85341. PostProcessRenderEffect.prototype._disable = function (cameras) {
  85342. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  85343. if (!cams) {
  85344. return;
  85345. }
  85346. for (var i = 0; i < cams.length; i++) {
  85347. var camera = cams[i];
  85348. var cameraName = camera.name;
  85349. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  85350. camera.detachPostProcess(postProcess);
  85351. });
  85352. }
  85353. };
  85354. /**
  85355. * Gets a list of the post processes contained in the effect.
  85356. * @param camera The camera to get the post processes on.
  85357. * @returns The list of the post processes in the effect.
  85358. */
  85359. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  85360. if (this._singleInstance) {
  85361. return this._postProcesses[0];
  85362. }
  85363. else {
  85364. if (!camera) {
  85365. return null;
  85366. }
  85367. return this._postProcesses[camera.name];
  85368. }
  85369. };
  85370. return PostProcessRenderEffect;
  85371. }());
  85372. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  85373. })(BABYLON || (BABYLON = {}));
  85374. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  85375. var BABYLON;
  85376. (function (BABYLON) {
  85377. /**
  85378. * PostProcessRenderPipeline
  85379. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  85380. */
  85381. var PostProcessRenderPipeline = /** @class */ (function () {
  85382. /**
  85383. * Initializes a PostProcessRenderPipeline
  85384. * @param engine engine to add the pipeline to
  85385. * @param name name of the pipeline
  85386. */
  85387. function PostProcessRenderPipeline(engine, name) {
  85388. this.engine = engine;
  85389. this._name = name;
  85390. this._renderEffects = {};
  85391. this._renderEffectsForIsolatedPass = new Array();
  85392. this._cameras = [];
  85393. }
  85394. /**
  85395. * "PostProcessRenderPipeline"
  85396. * @returns "PostProcessRenderPipeline"
  85397. */
  85398. PostProcessRenderPipeline.prototype.getClassName = function () {
  85399. return "PostProcessRenderPipeline";
  85400. };
  85401. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  85402. /**
  85403. * If all the render effects in the pipeline are support
  85404. */
  85405. get: function () {
  85406. for (var renderEffectName in this._renderEffects) {
  85407. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  85408. if (!this._renderEffects[renderEffectName].isSupported) {
  85409. return false;
  85410. }
  85411. }
  85412. }
  85413. return true;
  85414. },
  85415. enumerable: true,
  85416. configurable: true
  85417. });
  85418. /**
  85419. * Adds an effect to the pipeline
  85420. * @param renderEffect the effect to add
  85421. */
  85422. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  85423. this._renderEffects[renderEffect._name] = renderEffect;
  85424. };
  85425. // private
  85426. /** @hidden */
  85427. PostProcessRenderPipeline.prototype._rebuild = function () {
  85428. };
  85429. /** @hidden */
  85430. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  85431. var renderEffects = this._renderEffects[renderEffectName];
  85432. if (!renderEffects) {
  85433. return;
  85434. }
  85435. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  85436. };
  85437. /** @hidden */
  85438. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  85439. var renderEffects = this._renderEffects[renderEffectName];
  85440. if (!renderEffects) {
  85441. return;
  85442. }
  85443. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  85444. };
  85445. /** @hidden */
  85446. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  85447. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  85448. if (!cams) {
  85449. return;
  85450. }
  85451. var indicesToDelete = [];
  85452. var i;
  85453. for (i = 0; i < cams.length; i++) {
  85454. var camera = cams[i];
  85455. var cameraName = camera.name;
  85456. if (this._cameras.indexOf(camera) === -1) {
  85457. this._cameras[cameraName] = camera;
  85458. }
  85459. else if (unique) {
  85460. indicesToDelete.push(i);
  85461. }
  85462. }
  85463. for (i = 0; i < indicesToDelete.length; i++) {
  85464. cameras.splice(indicesToDelete[i], 1);
  85465. }
  85466. for (var renderEffectName in this._renderEffects) {
  85467. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  85468. this._renderEffects[renderEffectName]._attachCameras(cams);
  85469. }
  85470. }
  85471. };
  85472. /** @hidden */
  85473. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  85474. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  85475. if (!cams) {
  85476. return;
  85477. }
  85478. for (var renderEffectName in this._renderEffects) {
  85479. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  85480. this._renderEffects[renderEffectName]._detachCameras(cams);
  85481. }
  85482. }
  85483. for (var i = 0; i < cams.length; i++) {
  85484. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  85485. }
  85486. };
  85487. /** @hidden */
  85488. PostProcessRenderPipeline.prototype._update = function () {
  85489. for (var renderEffectName in this._renderEffects) {
  85490. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  85491. this._renderEffects[renderEffectName]._update();
  85492. }
  85493. }
  85494. for (var i = 0; i < this._cameras.length; i++) {
  85495. var cameraName = this._cameras[i].name;
  85496. if (this._renderEffectsForIsolatedPass[cameraName]) {
  85497. this._renderEffectsForIsolatedPass[cameraName]._update();
  85498. }
  85499. }
  85500. };
  85501. /** @hidden */
  85502. PostProcessRenderPipeline.prototype._reset = function () {
  85503. this._renderEffects = {};
  85504. this._renderEffectsForIsolatedPass = new Array();
  85505. };
  85506. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  85507. // 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)
  85508. var effectKeys = Object.keys(this._renderEffects);
  85509. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  85510. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  85511. if (postProcesses) {
  85512. postProcesses[0].samples = sampleCount;
  85513. return true;
  85514. }
  85515. }
  85516. return false;
  85517. };
  85518. /**
  85519. * Disposes of the pipeline
  85520. */
  85521. PostProcessRenderPipeline.prototype.dispose = function () {
  85522. // Must be implemented by children
  85523. };
  85524. __decorate([
  85525. BABYLON.serialize()
  85526. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  85527. return PostProcessRenderPipeline;
  85528. }());
  85529. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  85530. })(BABYLON || (BABYLON = {}));
  85531. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  85532. var BABYLON;
  85533. (function (BABYLON) {
  85534. /**
  85535. * This represents a depth renderer in Babylon.
  85536. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  85537. */
  85538. var DepthRenderer = /** @class */ (function () {
  85539. /**
  85540. * Instantiates a depth renderer
  85541. * @param scene The scene the renderer belongs to
  85542. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  85543. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  85544. */
  85545. function DepthRenderer(scene, type, camera) {
  85546. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  85547. if (camera === void 0) { camera = null; }
  85548. var _this = this;
  85549. /**
  85550. * Specifiess that the depth renderer will only be used within
  85551. * the camera it is created for.
  85552. * This can help forcing its rendering during the camera processing.
  85553. */
  85554. this.useOnlyInActiveCamera = false;
  85555. this._scene = scene;
  85556. // Register the G Buffer component to the scene.
  85557. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_DEPTHRENDERER);
  85558. if (!component) {
  85559. component = new BABYLON.DepthRendererSceneComponent(scene);
  85560. scene._addComponent(component);
  85561. }
  85562. this._camera = camera;
  85563. var engine = scene.getEngine();
  85564. // Render target
  85565. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  85566. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85567. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85568. this._depthMap.refreshRate = 1;
  85569. this._depthMap.renderParticles = false;
  85570. this._depthMap.renderList = null;
  85571. // Camera to get depth map from to support multiple concurrent cameras
  85572. this._depthMap.activeCamera = this._camera;
  85573. this._depthMap.ignoreCameraViewport = true;
  85574. this._depthMap.useCameraPostProcesses = false;
  85575. // set default depth value to 1.0 (far away)
  85576. this._depthMap.onClearObservable.add(function (engine) {
  85577. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  85578. });
  85579. // Custom render function
  85580. var renderSubMesh = function (subMesh) {
  85581. var mesh = subMesh.getRenderingMesh();
  85582. var scene = _this._scene;
  85583. var engine = scene.getEngine();
  85584. var material = subMesh.getMaterial();
  85585. if (!material) {
  85586. return;
  85587. }
  85588. // Culling and reverse (right handed system)
  85589. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  85590. // Managing instances
  85591. var batch = mesh._getInstancesRenderList(subMesh._id);
  85592. if (batch.mustReturn) {
  85593. return;
  85594. }
  85595. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  85596. var camera = _this._camera || scene.activeCamera;
  85597. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  85598. engine.enableEffect(_this._effect);
  85599. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  85600. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  85601. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  85602. // Alpha test
  85603. if (material && material.needAlphaTesting()) {
  85604. var alphaTexture = material.getAlphaTestTexture();
  85605. if (alphaTexture) {
  85606. _this._effect.setTexture("diffuseSampler", alphaTexture);
  85607. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  85608. }
  85609. }
  85610. // Bones
  85611. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  85612. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  85613. }
  85614. // Draw
  85615. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  85616. }
  85617. };
  85618. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  85619. var index;
  85620. if (depthOnlySubMeshes.length) {
  85621. engine.setColorWrite(false);
  85622. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  85623. renderSubMesh(depthOnlySubMeshes.data[index]);
  85624. }
  85625. engine.setColorWrite(true);
  85626. }
  85627. for (index = 0; index < opaqueSubMeshes.length; index++) {
  85628. renderSubMesh(opaqueSubMeshes.data[index]);
  85629. }
  85630. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  85631. renderSubMesh(alphaTestSubMeshes.data[index]);
  85632. }
  85633. };
  85634. }
  85635. /**
  85636. * Creates the depth rendering effect and checks if the effect is ready.
  85637. * @param subMesh The submesh to be used to render the depth map of
  85638. * @param useInstances If multiple world instances should be used
  85639. * @returns if the depth renderer is ready to render the depth map
  85640. */
  85641. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  85642. var material = subMesh.getMaterial();
  85643. if (material.disableDepthWrite) {
  85644. return false;
  85645. }
  85646. var defines = [];
  85647. var attribs = [BABYLON.VertexBuffer.PositionKind];
  85648. var mesh = subMesh.getMesh();
  85649. // Alpha test
  85650. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  85651. defines.push("#define ALPHATEST");
  85652. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  85653. attribs.push(BABYLON.VertexBuffer.UVKind);
  85654. defines.push("#define UV1");
  85655. }
  85656. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  85657. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  85658. defines.push("#define UV2");
  85659. }
  85660. }
  85661. // Bones
  85662. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  85663. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  85664. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  85665. if (mesh.numBoneInfluencers > 4) {
  85666. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  85667. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  85668. }
  85669. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  85670. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  85671. }
  85672. else {
  85673. defines.push("#define NUM_BONE_INFLUENCERS 0");
  85674. }
  85675. // Instances
  85676. if (useInstances) {
  85677. defines.push("#define INSTANCES");
  85678. attribs.push("world0");
  85679. attribs.push("world1");
  85680. attribs.push("world2");
  85681. attribs.push("world3");
  85682. }
  85683. // Get correct effect
  85684. var join = defines.join("\n");
  85685. if (this._cachedDefines !== join) {
  85686. this._cachedDefines = join;
  85687. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  85688. }
  85689. return this._effect.isReady();
  85690. };
  85691. /**
  85692. * Gets the texture which the depth map will be written to.
  85693. * @returns The depth map texture
  85694. */
  85695. DepthRenderer.prototype.getDepthMap = function () {
  85696. return this._depthMap;
  85697. };
  85698. /**
  85699. * Disposes of the depth renderer.
  85700. */
  85701. DepthRenderer.prototype.dispose = function () {
  85702. this._depthMap.dispose();
  85703. };
  85704. return DepthRenderer;
  85705. }());
  85706. BABYLON.DepthRenderer = DepthRenderer;
  85707. })(BABYLON || (BABYLON = {}));
  85708. //# sourceMappingURL=babylon.depthRenderer.js.map
  85709. var BABYLON;
  85710. (function (BABYLON) {
  85711. BABYLON.Scene.prototype.enableDepthRenderer = function (camera) {
  85712. camera = camera || this.activeCamera;
  85713. if (!camera) {
  85714. throw "No camera available to enable depth renderer";
  85715. }
  85716. if (!this._depthRenderer) {
  85717. this._depthRenderer = {};
  85718. }
  85719. if (!this._depthRenderer[camera.id]) {
  85720. var textureType = 0;
  85721. if (this.getEngine().getCaps().textureHalfFloatRender) {
  85722. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  85723. }
  85724. else if (this.getEngine().getCaps().textureFloatRender) {
  85725. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  85726. }
  85727. else {
  85728. throw "Depth renderer does not support int texture type";
  85729. }
  85730. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  85731. }
  85732. return this._depthRenderer[camera.id];
  85733. };
  85734. BABYLON.Scene.prototype.disableDepthRenderer = function (camera) {
  85735. camera = camera || this.activeCamera;
  85736. if (!camera || !this._depthRenderer || !this._depthRenderer[camera.id]) {
  85737. return;
  85738. }
  85739. this._depthRenderer[camera.id].dispose();
  85740. delete this._depthRenderer[camera.id];
  85741. };
  85742. /**
  85743. * Defines the Depth Renderer scene component responsible to manage a depth buffer useful
  85744. * in several rendering techniques.
  85745. */
  85746. var DepthRendererSceneComponent = /** @class */ (function () {
  85747. /**
  85748. * Creates a new instance of the component for the given scene
  85749. * @param scene Defines the scene to register the component in
  85750. */
  85751. function DepthRendererSceneComponent(scene) {
  85752. /**
  85753. * The component name helpfull to identify the component in the list of scene components.
  85754. */
  85755. this.name = BABYLON.SceneComponentConstants.NAME_DEPTHRENDERER;
  85756. this.scene = scene;
  85757. }
  85758. /**
  85759. * Registers the component in a given scene
  85760. */
  85761. DepthRendererSceneComponent.prototype.register = function () {
  85762. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_DEPTHRENDERER, this, this._gatherRenderTargets);
  85763. this.scene._gatherActiveCameraRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER, this, this._gatherActiveCameraRenderTargets);
  85764. };
  85765. /**
  85766. * Rebuilds the elements related to this component in case of
  85767. * context lost for instance.
  85768. */
  85769. DepthRendererSceneComponent.prototype.rebuild = function () {
  85770. // Nothing to do for this component
  85771. };
  85772. /**
  85773. * Disposes the component and the associated ressources
  85774. */
  85775. DepthRendererSceneComponent.prototype.dispose = function () {
  85776. for (var key in this.scene._depthRenderer) {
  85777. this.scene._depthRenderer[key].dispose();
  85778. }
  85779. };
  85780. DepthRendererSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  85781. if (this.scene._depthRenderer) {
  85782. for (var key in this.scene._depthRenderer) {
  85783. var depthRenderer = this.scene._depthRenderer[key];
  85784. if (!depthRenderer.useOnlyInActiveCamera) {
  85785. renderTargets.push(depthRenderer.getDepthMap());
  85786. }
  85787. }
  85788. }
  85789. };
  85790. DepthRendererSceneComponent.prototype._gatherActiveCameraRenderTargets = function (renderTargets) {
  85791. if (this.scene._depthRenderer) {
  85792. for (var key in this.scene._depthRenderer) {
  85793. var depthRenderer = this.scene._depthRenderer[key];
  85794. if (depthRenderer.useOnlyInActiveCamera && this.scene.activeCamera.id === key) {
  85795. renderTargets.push(depthRenderer.getDepthMap());
  85796. }
  85797. }
  85798. }
  85799. };
  85800. return DepthRendererSceneComponent;
  85801. }());
  85802. BABYLON.DepthRendererSceneComponent = DepthRendererSceneComponent;
  85803. })(BABYLON || (BABYLON = {}));
  85804. //# sourceMappingURL=babylon.depthRendererSceneComponent.js.map
  85805. var BABYLON;
  85806. (function (BABYLON) {
  85807. /**
  85808. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  85809. */
  85810. var GeometryBufferRenderer = /** @class */ (function () {
  85811. /**
  85812. * Creates a new G Buffer for the scene
  85813. * @param scene The scene the buffer belongs to
  85814. * @param ratio How big is the buffer related to the main canvas.
  85815. */
  85816. function GeometryBufferRenderer(scene, ratio) {
  85817. if (ratio === void 0) { ratio = 1; }
  85818. /**
  85819. * Dictionary used to store the previous transformation matrices of each rendered mesh
  85820. * in order to compute objects velocities when enableVelocity is set to "true"
  85821. * @hidden
  85822. */
  85823. this._previousTransformationMatrices = {};
  85824. this._enablePosition = false;
  85825. this._enableVelocity = false;
  85826. this._positionIndex = -1;
  85827. this._velocityIndex = -1;
  85828. this._scene = scene;
  85829. this._ratio = ratio;
  85830. // Register the G Buffer component to the scene.
  85831. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER);
  85832. if (!component) {
  85833. component = new BABYLON.GeometryBufferRendererSceneComponent(scene);
  85834. scene._addComponent(component);
  85835. }
  85836. // Render target
  85837. this._createRenderTargets();
  85838. }
  85839. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  85840. /**
  85841. * Set the render list (meshes to be rendered) used in the G buffer.
  85842. */
  85843. set: function (meshes) {
  85844. this._multiRenderTarget.renderList = meshes;
  85845. },
  85846. enumerable: true,
  85847. configurable: true
  85848. });
  85849. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  85850. /**
  85851. * Gets wether or not G buffer are supported by the running hardware.
  85852. * This requires draw buffer supports
  85853. */
  85854. get: function () {
  85855. return this._multiRenderTarget.isSupported;
  85856. },
  85857. enumerable: true,
  85858. configurable: true
  85859. });
  85860. /**
  85861. * Returns the index of the given texture type in the G-Buffer textures array
  85862. * @param textureType The texture type constant. For example GeometryBufferRenderer.POSITION_TEXTURE_INDEX
  85863. * @returns the index of the given texture type in the G-Buffer textures array
  85864. */
  85865. GeometryBufferRenderer.prototype.getTextureIndex = function (textureType) {
  85866. switch (textureType) {
  85867. case GeometryBufferRenderer.POSITION_TEXTURE_TYPE: return this._positionIndex;
  85868. case GeometryBufferRenderer.VELOCITY_TEXTURE_TYPE: return this._velocityIndex;
  85869. default: return -1;
  85870. }
  85871. };
  85872. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  85873. /**
  85874. * Gets a boolean indicating if objects positions are enabled for the G buffer.
  85875. */
  85876. get: function () {
  85877. return this._enablePosition;
  85878. },
  85879. /**
  85880. * Sets whether or not objects positions are enabled for the G buffer.
  85881. */
  85882. set: function (enable) {
  85883. this._enablePosition = enable;
  85884. this.dispose();
  85885. this._createRenderTargets();
  85886. },
  85887. enumerable: true,
  85888. configurable: true
  85889. });
  85890. Object.defineProperty(GeometryBufferRenderer.prototype, "enableVelocity", {
  85891. /**
  85892. * Gets a boolean indicating if objects velocities are enabled for the G buffer.
  85893. */
  85894. get: function () {
  85895. return this._enableVelocity;
  85896. },
  85897. /**
  85898. * Sets wether or not objects velocities are enabled for the G buffer.
  85899. */
  85900. set: function (enable) {
  85901. this._enableVelocity = enable;
  85902. this.dispose();
  85903. this._createRenderTargets();
  85904. },
  85905. enumerable: true,
  85906. configurable: true
  85907. });
  85908. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  85909. /**
  85910. * Gets the scene associated with the buffer.
  85911. */
  85912. get: function () {
  85913. return this._scene;
  85914. },
  85915. enumerable: true,
  85916. configurable: true
  85917. });
  85918. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  85919. /**
  85920. * Gets the ratio used by the buffer during its creation.
  85921. * How big is the buffer related to the main canvas.
  85922. */
  85923. get: function () {
  85924. return this._ratio;
  85925. },
  85926. enumerable: true,
  85927. configurable: true
  85928. });
  85929. /**
  85930. * Checks wether everything is ready to render a submesh to the G buffer.
  85931. * @param subMesh the submesh to check readiness for
  85932. * @param useInstances is the mesh drawn using instance or not
  85933. * @returns true if ready otherwise false
  85934. */
  85935. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  85936. var material = subMesh.getMaterial();
  85937. if (material && material.disableDepthWrite) {
  85938. return false;
  85939. }
  85940. var defines = [];
  85941. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  85942. var mesh = subMesh.getMesh();
  85943. // Alpha test
  85944. if (material && material.needAlphaTesting()) {
  85945. defines.push("#define ALPHATEST");
  85946. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  85947. attribs.push(BABYLON.VertexBuffer.UVKind);
  85948. defines.push("#define UV1");
  85949. }
  85950. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  85951. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  85952. defines.push("#define UV2");
  85953. }
  85954. }
  85955. // Buffers
  85956. if (this._enablePosition) {
  85957. defines.push("#define POSITION");
  85958. defines.push("#define POSITION_INDEX " + this._positionIndex);
  85959. }
  85960. if (this._enableVelocity) {
  85961. defines.push("#define VELOCITY");
  85962. defines.push("#define VELOCITY_INDEX " + this._velocityIndex);
  85963. }
  85964. // Bones
  85965. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  85966. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  85967. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  85968. if (mesh.numBoneInfluencers > 4) {
  85969. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  85970. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  85971. }
  85972. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  85973. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  85974. }
  85975. else {
  85976. defines.push("#define NUM_BONE_INFLUENCERS 0");
  85977. }
  85978. // Instances
  85979. if (useInstances) {
  85980. defines.push("#define INSTANCES");
  85981. attribs.push("world0");
  85982. attribs.push("world1");
  85983. attribs.push("world2");
  85984. attribs.push("world3");
  85985. }
  85986. // Setup textures count
  85987. defines.push("#define RENDER_TARGET_COUNT " + this._multiRenderTarget.textures.length);
  85988. // Get correct effect
  85989. var join = defines.join("\n");
  85990. if (this._cachedDefines !== join) {
  85991. this._cachedDefines = join;
  85992. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view", "previousWorldViewProjection"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  85993. }
  85994. return this._effect.isReady();
  85995. };
  85996. /**
  85997. * Gets the current underlying G Buffer.
  85998. * @returns the buffer
  85999. */
  86000. GeometryBufferRenderer.prototype.getGBuffer = function () {
  86001. return this._multiRenderTarget;
  86002. };
  86003. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  86004. /**
  86005. * Gets the number of samples used to render the buffer (anti aliasing).
  86006. */
  86007. get: function () {
  86008. return this._multiRenderTarget.samples;
  86009. },
  86010. /**
  86011. * Sets the number of samples used to render the buffer (anti aliasing).
  86012. */
  86013. set: function (value) {
  86014. this._multiRenderTarget.samples = value;
  86015. },
  86016. enumerable: true,
  86017. configurable: true
  86018. });
  86019. /**
  86020. * Disposes the renderer and frees up associated resources.
  86021. */
  86022. GeometryBufferRenderer.prototype.dispose = function () {
  86023. this.getGBuffer().dispose();
  86024. };
  86025. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  86026. var _this = this;
  86027. var engine = this._scene.getEngine();
  86028. var count = 2;
  86029. if (this._enablePosition) {
  86030. this._positionIndex = count;
  86031. count++;
  86032. }
  86033. if (this._enableVelocity) {
  86034. this._velocityIndex = count;
  86035. count++;
  86036. }
  86037. 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 });
  86038. if (!this.isSupported) {
  86039. return;
  86040. }
  86041. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86042. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86043. this._multiRenderTarget.refreshRate = 1;
  86044. this._multiRenderTarget.renderParticles = false;
  86045. this._multiRenderTarget.renderList = null;
  86046. // set default depth value to 1.0 (far away)
  86047. this._multiRenderTarget.onClearObservable.add(function (engine) {
  86048. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  86049. });
  86050. // Custom render function
  86051. var renderSubMesh = function (subMesh) {
  86052. var mesh = subMesh.getRenderingMesh();
  86053. var scene = _this._scene;
  86054. var engine = scene.getEngine();
  86055. var material = subMesh.getMaterial();
  86056. if (!material) {
  86057. return;
  86058. }
  86059. // Velocity
  86060. if (!_this._previousTransformationMatrices[mesh.uniqueId]) {
  86061. _this._previousTransformationMatrices[mesh.uniqueId] = BABYLON.Matrix.Identity();
  86062. }
  86063. // Culling
  86064. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  86065. // Managing instances
  86066. var batch = mesh._getInstancesRenderList(subMesh._id);
  86067. if (batch.mustReturn) {
  86068. return;
  86069. }
  86070. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  86071. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  86072. engine.enableEffect(_this._effect);
  86073. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  86074. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  86075. _this._effect.setMatrix("view", scene.getViewMatrix());
  86076. // Alpha test
  86077. if (material && material.needAlphaTesting()) {
  86078. var alphaTexture = material.getAlphaTestTexture();
  86079. if (alphaTexture) {
  86080. _this._effect.setTexture("diffuseSampler", alphaTexture);
  86081. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  86082. }
  86083. }
  86084. // Bones
  86085. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  86086. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  86087. }
  86088. // Velocity
  86089. _this._effect.setMatrix("previousWorldViewProjection", _this._previousTransformationMatrices[mesh.uniqueId]);
  86090. // Draw
  86091. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  86092. }
  86093. // Velocity
  86094. _this._previousTransformationMatrices[mesh.uniqueId] = mesh.getWorldMatrix().multiply(_this._scene.getTransformMatrix());
  86095. };
  86096. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  86097. var index;
  86098. if (depthOnlySubMeshes.length) {
  86099. engine.setColorWrite(false);
  86100. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  86101. renderSubMesh(depthOnlySubMeshes.data[index]);
  86102. }
  86103. engine.setColorWrite(true);
  86104. }
  86105. for (index = 0; index < opaqueSubMeshes.length; index++) {
  86106. renderSubMesh(opaqueSubMeshes.data[index]);
  86107. }
  86108. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  86109. renderSubMesh(alphaTestSubMeshes.data[index]);
  86110. }
  86111. };
  86112. };
  86113. /**
  86114. * Constant used to retrieve the position texture index in the G-Buffer textures array
  86115. * using getIndex(GeometryBufferRenderer.POSITION_TEXTURE_INDEX)
  86116. */
  86117. GeometryBufferRenderer.POSITION_TEXTURE_TYPE = 1;
  86118. /**
  86119. * Constant used to retrieve the velocity texture index in the G-Buffer textures array
  86120. * using getIndex(GeometryBufferRenderer.VELOCITY_TEXTURE_INDEX)
  86121. */
  86122. GeometryBufferRenderer.VELOCITY_TEXTURE_TYPE = 2;
  86123. return GeometryBufferRenderer;
  86124. }());
  86125. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  86126. })(BABYLON || (BABYLON = {}));
  86127. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  86128. var BABYLON;
  86129. (function (BABYLON) {
  86130. Object.defineProperty(BABYLON.Scene.prototype, "geometryBufferRenderer", {
  86131. get: function () {
  86132. this._geometryBufferRenderer;
  86133. },
  86134. set: function (value) {
  86135. if (value && value.isSupported) {
  86136. this._geometryBufferRenderer = value;
  86137. }
  86138. },
  86139. enumerable: true,
  86140. configurable: true
  86141. });
  86142. BABYLON.Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  86143. if (ratio === void 0) { ratio = 1; }
  86144. if (this._geometryBufferRenderer) {
  86145. return this._geometryBufferRenderer;
  86146. }
  86147. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  86148. if (!this._geometryBufferRenderer.isSupported) {
  86149. this._geometryBufferRenderer = null;
  86150. }
  86151. return this._geometryBufferRenderer;
  86152. };
  86153. BABYLON.Scene.prototype.disableGeometryBufferRenderer = function () {
  86154. if (!this._geometryBufferRenderer) {
  86155. return;
  86156. }
  86157. this._geometryBufferRenderer.dispose();
  86158. this._geometryBufferRenderer = null;
  86159. };
  86160. /**
  86161. * Defines the Geometry Buffer scene component responsible to manage a G-Buffer useful
  86162. * in several rendering techniques.
  86163. */
  86164. var GeometryBufferRendererSceneComponent = /** @class */ (function () {
  86165. /**
  86166. * Creates a new instance of the component for the given scene
  86167. * @param scene Defines the scene to register the component in
  86168. */
  86169. function GeometryBufferRendererSceneComponent(scene) {
  86170. /**
  86171. * The component name helpful to identify the component in the list of scene components.
  86172. */
  86173. this.name = BABYLON.SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER;
  86174. this.scene = scene;
  86175. }
  86176. /**
  86177. * Registers the component in a given scene
  86178. */
  86179. GeometryBufferRendererSceneComponent.prototype.register = function () {
  86180. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER, this, this._gatherRenderTargets);
  86181. };
  86182. /**
  86183. * Rebuilds the elements related to this component in case of
  86184. * context lost for instance.
  86185. */
  86186. GeometryBufferRendererSceneComponent.prototype.rebuild = function () {
  86187. // Nothing to do for this component
  86188. };
  86189. /**
  86190. * Disposes the component and the associated ressources
  86191. */
  86192. GeometryBufferRendererSceneComponent.prototype.dispose = function () {
  86193. // Nothing to do for this component
  86194. };
  86195. GeometryBufferRendererSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  86196. if (this.scene._geometryBufferRenderer) {
  86197. renderTargets.push(this.scene._geometryBufferRenderer.getGBuffer());
  86198. }
  86199. };
  86200. return GeometryBufferRendererSceneComponent;
  86201. }());
  86202. BABYLON.GeometryBufferRendererSceneComponent = GeometryBufferRendererSceneComponent;
  86203. })(BABYLON || (BABYLON = {}));
  86204. //# sourceMappingURL=babylon.geometryBufferRendererSceneComponent.js.map
  86205. var BABYLON;
  86206. (function (BABYLON) {
  86207. /**
  86208. * Render pipeline to produce ssao effect
  86209. */
  86210. var SSAORenderingPipeline = /** @class */ (function (_super) {
  86211. __extends(SSAORenderingPipeline, _super);
  86212. /**
  86213. * @constructor
  86214. * @param name - The rendering pipeline name
  86215. * @param scene - The scene linked to this pipeline
  86216. * @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 }
  86217. * @param cameras - The array of cameras that the rendering pipeline will be attached to
  86218. */
  86219. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  86220. var _this = _super.call(this, scene.getEngine(), name) || this;
  86221. // Members
  86222. /**
  86223. * @ignore
  86224. * The PassPostProcess id in the pipeline that contains the original scene color
  86225. */
  86226. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  86227. /**
  86228. * @ignore
  86229. * The SSAO PostProcess id in the pipeline
  86230. */
  86231. _this.SSAORenderEffect = "SSAORenderEffect";
  86232. /**
  86233. * @ignore
  86234. * The horizontal blur PostProcess id in the pipeline
  86235. */
  86236. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  86237. /**
  86238. * @ignore
  86239. * The vertical blur PostProcess id in the pipeline
  86240. */
  86241. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  86242. /**
  86243. * @ignore
  86244. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  86245. */
  86246. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  86247. /**
  86248. * The output strength of the SSAO post-process. Default value is 1.0.
  86249. */
  86250. _this.totalStrength = 1.0;
  86251. /**
  86252. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  86253. */
  86254. _this.radius = 0.0001;
  86255. /**
  86256. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  86257. * Must not be equal to fallOff and superior to fallOff.
  86258. * Default value is 0.975
  86259. */
  86260. _this.area = 0.0075;
  86261. /**
  86262. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  86263. * Must not be equal to area and inferior to area.
  86264. * Default value is 0.0
  86265. */
  86266. _this.fallOff = 0.000001;
  86267. /**
  86268. * The base color of the SSAO post-process
  86269. * The final result is "base + ssao" between [0, 1]
  86270. */
  86271. _this.base = 0.5;
  86272. _this._firstUpdate = true;
  86273. _this._scene = scene;
  86274. // Set up assets
  86275. _this._createRandomTexture();
  86276. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  86277. var ssaoRatio = ratio.ssaoRatio || ratio;
  86278. var combineRatio = ratio.combineRatio || ratio;
  86279. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  86280. _this._createSSAOPostProcess(ssaoRatio);
  86281. _this._createBlurPostProcess(ssaoRatio);
  86282. _this._createSSAOCombinePostProcess(combineRatio);
  86283. // Set up pipeline
  86284. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  86285. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  86286. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  86287. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  86288. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  86289. // Finish
  86290. scene.postProcessRenderPipelineManager.addPipeline(_this);
  86291. if (cameras) {
  86292. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  86293. }
  86294. return _this;
  86295. }
  86296. // Public Methods
  86297. /**
  86298. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  86299. */
  86300. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  86301. if (disableDepthRender === void 0) { disableDepthRender = false; }
  86302. for (var i = 0; i < this._scene.cameras.length; i++) {
  86303. var camera = this._scene.cameras[i];
  86304. this._originalColorPostProcess.dispose(camera);
  86305. this._ssaoPostProcess.dispose(camera);
  86306. this._blurHPostProcess.dispose(camera);
  86307. this._blurVPostProcess.dispose(camera);
  86308. this._ssaoCombinePostProcess.dispose(camera);
  86309. }
  86310. this._randomTexture.dispose();
  86311. if (disableDepthRender) {
  86312. this._scene.disableDepthRenderer();
  86313. }
  86314. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  86315. _super.prototype.dispose.call(this);
  86316. };
  86317. // Private Methods
  86318. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  86319. var _this = this;
  86320. var size = 16;
  86321. 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);
  86322. 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);
  86323. this._blurHPostProcess.onActivateObservable.add(function () {
  86324. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  86325. _this._blurHPostProcess.kernel = size * dw;
  86326. });
  86327. this._blurVPostProcess.onActivateObservable.add(function () {
  86328. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  86329. _this._blurVPostProcess.kernel = size * dw;
  86330. });
  86331. };
  86332. /** @hidden */
  86333. SSAORenderingPipeline.prototype._rebuild = function () {
  86334. this._firstUpdate = true;
  86335. _super.prototype._rebuild.call(this);
  86336. };
  86337. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  86338. var _this = this;
  86339. var numSamples = 16;
  86340. var sampleSphere = [
  86341. 0.5381, 0.1856, -0.4319,
  86342. 0.1379, 0.2486, 0.4430,
  86343. 0.3371, 0.5679, -0.0057,
  86344. -0.6999, -0.0451, -0.0019,
  86345. 0.0689, -0.1598, -0.8547,
  86346. 0.0560, 0.0069, -0.1843,
  86347. -0.0146, 0.1402, 0.0762,
  86348. 0.0100, -0.1924, -0.0344,
  86349. -0.3577, -0.5301, -0.4358,
  86350. -0.3169, 0.1063, 0.0158,
  86351. 0.0103, -0.5869, 0.0046,
  86352. -0.0897, -0.4940, 0.3287,
  86353. 0.7119, -0.0154, -0.0918,
  86354. -0.0533, 0.0596, -0.5411,
  86355. 0.0352, -0.0631, 0.5460,
  86356. -0.4776, 0.2847, -0.0271
  86357. ];
  86358. var samplesFactor = 1.0 / numSamples;
  86359. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  86360. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  86361. "area", "fallOff", "base", "range", "viewport"
  86362. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  86363. this._ssaoPostProcess.onApply = function (effect) {
  86364. if (_this._firstUpdate) {
  86365. effect.setArray3("sampleSphere", sampleSphere);
  86366. effect.setFloat("samplesFactor", samplesFactor);
  86367. effect.setFloat("randTextureTiles", 4.0);
  86368. }
  86369. effect.setFloat("totalStrength", _this.totalStrength);
  86370. effect.setFloat("radius", _this.radius);
  86371. effect.setFloat("area", _this.area);
  86372. effect.setFloat("fallOff", _this.fallOff);
  86373. effect.setFloat("base", _this.base);
  86374. effect.setTexture("textureSampler", _this._depthTexture);
  86375. effect.setTexture("randomSampler", _this._randomTexture);
  86376. };
  86377. };
  86378. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  86379. var _this = this;
  86380. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  86381. this._ssaoCombinePostProcess.onApply = function (effect) {
  86382. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(0, 0, 1.0, 1.0));
  86383. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  86384. };
  86385. };
  86386. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  86387. var size = 512;
  86388. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  86389. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  86390. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  86391. var context = this._randomTexture.getContext();
  86392. var rand = function (min, max) {
  86393. return Math.random() * (max - min) + min;
  86394. };
  86395. var randVector = BABYLON.Vector3.Zero();
  86396. for (var x = 0; x < size; x++) {
  86397. for (var y = 0; y < size; y++) {
  86398. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  86399. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  86400. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  86401. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  86402. context.fillRect(x, y, 1, 1);
  86403. }
  86404. }
  86405. this._randomTexture.update(false);
  86406. };
  86407. __decorate([
  86408. BABYLON.serialize()
  86409. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  86410. __decorate([
  86411. BABYLON.serialize()
  86412. ], SSAORenderingPipeline.prototype, "radius", void 0);
  86413. __decorate([
  86414. BABYLON.serialize()
  86415. ], SSAORenderingPipeline.prototype, "area", void 0);
  86416. __decorate([
  86417. BABYLON.serialize()
  86418. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  86419. __decorate([
  86420. BABYLON.serialize()
  86421. ], SSAORenderingPipeline.prototype, "base", void 0);
  86422. return SSAORenderingPipeline;
  86423. }(BABYLON.PostProcessRenderPipeline));
  86424. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  86425. })(BABYLON || (BABYLON = {}));
  86426. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  86427. var BABYLON;
  86428. (function (BABYLON) {
  86429. /**
  86430. * Render pipeline to produce ssao effect
  86431. */
  86432. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  86433. __extends(SSAO2RenderingPipeline, _super);
  86434. /**
  86435. * @constructor
  86436. * @param name The rendering pipeline name
  86437. * @param scene The scene linked to this pipeline
  86438. * @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 }
  86439. * @param cameras The array of cameras that the rendering pipeline will be attached to
  86440. */
  86441. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  86442. var _this = _super.call(this, scene.getEngine(), name) || this;
  86443. // Members
  86444. /**
  86445. * @ignore
  86446. * The PassPostProcess id in the pipeline that contains the original scene color
  86447. */
  86448. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  86449. /**
  86450. * @ignore
  86451. * The SSAO PostProcess id in the pipeline
  86452. */
  86453. _this.SSAORenderEffect = "SSAORenderEffect";
  86454. /**
  86455. * @ignore
  86456. * The horizontal blur PostProcess id in the pipeline
  86457. */
  86458. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  86459. /**
  86460. * @ignore
  86461. * The vertical blur PostProcess id in the pipeline
  86462. */
  86463. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  86464. /**
  86465. * @ignore
  86466. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  86467. */
  86468. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  86469. /**
  86470. * The output strength of the SSAO post-process. Default value is 1.0.
  86471. */
  86472. _this.totalStrength = 1.0;
  86473. /**
  86474. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  86475. */
  86476. _this.maxZ = 100.0;
  86477. /**
  86478. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  86479. */
  86480. _this.minZAspect = 0.2;
  86481. _this._samples = 8;
  86482. _this._textureSamples = 1;
  86483. _this._expensiveBlur = true;
  86484. /**
  86485. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  86486. */
  86487. _this.radius = 2.0;
  86488. /**
  86489. * The base color of the SSAO post-process
  86490. * The final result is "base + ssao" between [0, 1]
  86491. */
  86492. _this.base = 0;
  86493. _this._firstUpdate = true;
  86494. _this._bits = new Uint32Array(1);
  86495. _this._scene = scene;
  86496. _this._ratio = ratio;
  86497. if (!_this.isSupported) {
  86498. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  86499. return _this;
  86500. }
  86501. var ssaoRatio = _this._ratio.ssaoRatio || ratio;
  86502. var blurRatio = _this._ratio.blurRatio || ratio;
  86503. // Set up assets
  86504. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  86505. _this._createRandomTexture();
  86506. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  86507. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  86508. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  86509. _this._originalColorPostProcess.samples = _this.textureSamples;
  86510. _this._createSSAOPostProcess(1.0);
  86511. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  86512. _this._createSSAOCombinePostProcess(blurRatio);
  86513. // Set up pipeline
  86514. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  86515. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  86516. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  86517. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  86518. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  86519. // Finish
  86520. scene.postProcessRenderPipelineManager.addPipeline(_this);
  86521. if (cameras) {
  86522. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  86523. }
  86524. return _this;
  86525. }
  86526. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  86527. get: function () {
  86528. return this._samples;
  86529. },
  86530. /**
  86531. * Number of samples used for the SSAO calculations. Default value is 8
  86532. */
  86533. set: function (n) {
  86534. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  86535. this._samples = n;
  86536. this._sampleSphere = this._generateHemisphere();
  86537. this._firstUpdate = true;
  86538. },
  86539. enumerable: true,
  86540. configurable: true
  86541. });
  86542. Object.defineProperty(SSAO2RenderingPipeline.prototype, "textureSamples", {
  86543. get: function () {
  86544. return this._textureSamples;
  86545. },
  86546. /**
  86547. * Number of samples to use for antialiasing
  86548. */
  86549. set: function (n) {
  86550. this._textureSamples = n;
  86551. this._originalColorPostProcess.samples = n;
  86552. this._blurHPostProcess.samples = n;
  86553. this._blurVPostProcess.samples = n;
  86554. this._ssaoPostProcess.samples = n;
  86555. this._ssaoCombinePostProcess.samples = n;
  86556. },
  86557. enumerable: true,
  86558. configurable: true
  86559. });
  86560. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  86561. get: function () {
  86562. return this._expensiveBlur;
  86563. },
  86564. /**
  86565. * If bilateral blur should be used
  86566. */
  86567. set: function (b) {
  86568. 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"]);
  86569. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  86570. this._expensiveBlur = b;
  86571. this._firstUpdate = true;
  86572. },
  86573. enumerable: true,
  86574. configurable: true
  86575. });
  86576. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  86577. /**
  86578. * Support test.
  86579. */
  86580. get: function () {
  86581. var engine = BABYLON.Engine.LastCreatedEngine;
  86582. if (!engine) {
  86583. return false;
  86584. }
  86585. return engine.getCaps().drawBuffersExtension;
  86586. },
  86587. enumerable: true,
  86588. configurable: true
  86589. });
  86590. // Public Methods
  86591. /**
  86592. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  86593. */
  86594. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  86595. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  86596. for (var i = 0; i < this._scene.cameras.length; i++) {
  86597. var camera = this._scene.cameras[i];
  86598. this._originalColorPostProcess.dispose(camera);
  86599. this._ssaoPostProcess.dispose(camera);
  86600. this._blurHPostProcess.dispose(camera);
  86601. this._blurVPostProcess.dispose(camera);
  86602. this._ssaoCombinePostProcess.dispose(camera);
  86603. }
  86604. this._randomTexture.dispose();
  86605. if (disableGeometryBufferRenderer) {
  86606. this._scene.disableGeometryBufferRenderer();
  86607. }
  86608. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  86609. _super.prototype.dispose.call(this);
  86610. };
  86611. // Private Methods
  86612. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  86613. var _this = this;
  86614. this._samplerOffsets = [];
  86615. var expensive = this.expensiveBlur;
  86616. for (var i = -8; i < 8; i++) {
  86617. this._samplerOffsets.push(i * 2 + 0.5);
  86618. }
  86619. 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");
  86620. this._blurHPostProcess.onApply = function (effect) {
  86621. if (!_this._scene.activeCamera) {
  86622. return;
  86623. }
  86624. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  86625. effect.setFloat("near", _this._scene.activeCamera.minZ);
  86626. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  86627. effect.setFloat("radius", _this.radius);
  86628. effect.setTexture("depthSampler", _this._depthTexture);
  86629. if (_this._firstUpdate) {
  86630. effect.setArray("samplerOffsets", _this._samplerOffsets);
  86631. }
  86632. };
  86633. 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");
  86634. this._blurVPostProcess.onApply = function (effect) {
  86635. if (!_this._scene.activeCamera) {
  86636. return;
  86637. }
  86638. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  86639. effect.setFloat("near", _this._scene.activeCamera.minZ);
  86640. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  86641. effect.setFloat("radius", _this.radius);
  86642. effect.setTexture("depthSampler", _this._depthTexture);
  86643. if (_this._firstUpdate) {
  86644. effect.setArray("samplerOffsets", _this._samplerOffsets);
  86645. _this._firstUpdate = false;
  86646. }
  86647. };
  86648. this._blurHPostProcess.samples = this.textureSamples;
  86649. this._blurVPostProcess.samples = this.textureSamples;
  86650. };
  86651. /** @hidden */
  86652. SSAO2RenderingPipeline.prototype._rebuild = function () {
  86653. this._firstUpdate = true;
  86654. _super.prototype._rebuild.call(this);
  86655. };
  86656. //Van der Corput radical inverse
  86657. SSAO2RenderingPipeline.prototype._radicalInverse_VdC = function (i) {
  86658. this._bits[0] = i;
  86659. this._bits[0] = ((this._bits[0] << 16) | (this._bits[0] >> 16)) >>> 0;
  86660. this._bits[0] = ((this._bits[0] & 0x55555555) << 1) | ((this._bits[0] & 0xAAAAAAAA) >>> 1) >>> 0;
  86661. this._bits[0] = ((this._bits[0] & 0x33333333) << 2) | ((this._bits[0] & 0xCCCCCCCC) >>> 2) >>> 0;
  86662. this._bits[0] = ((this._bits[0] & 0x0F0F0F0F) << 4) | ((this._bits[0] & 0xF0F0F0F0) >>> 4) >>> 0;
  86663. this._bits[0] = ((this._bits[0] & 0x00FF00FF) << 8) | ((this._bits[0] & 0xFF00FF00) >>> 8) >>> 0;
  86664. return this._bits[0] * 2.3283064365386963e-10; // / 0x100000000 or / 4294967296
  86665. };
  86666. SSAO2RenderingPipeline.prototype._hammersley = function (i, n) {
  86667. return [i / n, this._radicalInverse_VdC(i)];
  86668. };
  86669. SSAO2RenderingPipeline.prototype._hemisphereSample_uniform = function (u, v) {
  86670. var phi = v * 2.0 * Math.PI;
  86671. // rejecting samples that are close to tangent plane to avoid z-fighting artifacts
  86672. var cosTheta = 1.0 - (u * 0.85 + 0.15);
  86673. var sinTheta = Math.sqrt(1.0 - cosTheta * cosTheta);
  86674. return new BABYLON.Vector3(Math.cos(phi) * sinTheta, Math.sin(phi) * sinTheta, cosTheta);
  86675. };
  86676. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  86677. var numSamples = this.samples;
  86678. var result = [];
  86679. var vector;
  86680. var i = 0;
  86681. while (i < numSamples) {
  86682. if (numSamples < 16) {
  86683. vector = this._hemisphereSample_uniform(Math.random(), Math.random());
  86684. }
  86685. else {
  86686. var rand = this._hammersley(i, numSamples);
  86687. vector = this._hemisphereSample_uniform(rand[0], rand[1]);
  86688. }
  86689. result.push(vector.x, vector.y, vector.z);
  86690. i++;
  86691. }
  86692. return result;
  86693. };
  86694. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  86695. var _this = this;
  86696. var numSamples = this.samples;
  86697. this._sampleSphere = this._generateHemisphere();
  86698. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  86699. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  86700. "base", "range", "projection", "near", "far", "texelSize",
  86701. "xViewport", "yViewport", "maxZ", "minZAspect"
  86702. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  86703. this._ssaoPostProcess.onApply = function (effect) {
  86704. if (_this._firstUpdate) {
  86705. effect.setArray3("sampleSphere", _this._sampleSphere);
  86706. effect.setFloat("randTextureTiles", 32.0);
  86707. }
  86708. if (!_this._scene.activeCamera) {
  86709. return;
  86710. }
  86711. effect.setFloat("samplesFactor", 1 / _this.samples);
  86712. effect.setFloat("totalStrength", _this.totalStrength);
  86713. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  86714. effect.setFloat("radius", _this.radius);
  86715. effect.setFloat("maxZ", _this.maxZ);
  86716. effect.setFloat("minZAspect", _this.minZAspect);
  86717. effect.setFloat("base", _this.base);
  86718. effect.setFloat("near", _this._scene.activeCamera.minZ);
  86719. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  86720. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  86721. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  86722. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  86723. effect.setTexture("textureSampler", _this._depthTexture);
  86724. effect.setTexture("normalSampler", _this._normalTexture);
  86725. effect.setTexture("randomSampler", _this._randomTexture);
  86726. };
  86727. this._ssaoPostProcess.samples = this.textureSamples;
  86728. };
  86729. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  86730. var _this = this;
  86731. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  86732. this._ssaoCombinePostProcess.onApply = function (effect) {
  86733. var viewport = _this._scene.activeCamera.viewport;
  86734. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(viewport.x, viewport.y, viewport.width, viewport.height));
  86735. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  86736. };
  86737. this._ssaoCombinePostProcess.samples = this.textureSamples;
  86738. };
  86739. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  86740. var size = 128;
  86741. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  86742. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  86743. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  86744. var context = this._randomTexture.getContext();
  86745. var rand = function (min, max) {
  86746. return Math.random() * (max - min) + min;
  86747. };
  86748. var randVector = BABYLON.Vector3.Zero();
  86749. for (var x = 0; x < size; x++) {
  86750. for (var y = 0; y < size; y++) {
  86751. randVector.x = rand(0.0, 1.0);
  86752. randVector.y = rand(0.0, 1.0);
  86753. randVector.z = 0.0;
  86754. randVector.normalize();
  86755. randVector.scaleInPlace(255);
  86756. randVector.x = Math.floor(randVector.x);
  86757. randVector.y = Math.floor(randVector.y);
  86758. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  86759. context.fillRect(x, y, 1, 1);
  86760. }
  86761. }
  86762. this._randomTexture.update(false);
  86763. };
  86764. /**
  86765. * Serialize the rendering pipeline (Used when exporting)
  86766. * @returns the serialized object
  86767. */
  86768. SSAO2RenderingPipeline.prototype.serialize = function () {
  86769. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  86770. serializationObject.customType = "SSAO2RenderingPipeline";
  86771. return serializationObject;
  86772. };
  86773. /**
  86774. * Parse the serialized pipeline
  86775. * @param source Source pipeline.
  86776. * @param scene The scene to load the pipeline to.
  86777. * @param rootUrl The URL of the serialized pipeline.
  86778. * @returns An instantiated pipeline from the serialized object.
  86779. */
  86780. SSAO2RenderingPipeline.Parse = function (source, scene, rootUrl) {
  86781. return BABYLON.SerializationHelper.Parse(function () { return new SSAO2RenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  86782. };
  86783. __decorate([
  86784. BABYLON.serialize()
  86785. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  86786. __decorate([
  86787. BABYLON.serialize()
  86788. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  86789. __decorate([
  86790. BABYLON.serialize()
  86791. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  86792. __decorate([
  86793. BABYLON.serialize("samples")
  86794. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  86795. __decorate([
  86796. BABYLON.serialize("textureSamples")
  86797. ], SSAO2RenderingPipeline.prototype, "_textureSamples", void 0);
  86798. __decorate([
  86799. BABYLON.serialize()
  86800. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  86801. __decorate([
  86802. BABYLON.serialize("expensiveBlur")
  86803. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  86804. __decorate([
  86805. BABYLON.serialize()
  86806. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  86807. __decorate([
  86808. BABYLON.serialize()
  86809. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  86810. return SSAO2RenderingPipeline;
  86811. }(BABYLON.PostProcessRenderPipeline));
  86812. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  86813. })(BABYLON || (BABYLON = {}));
  86814. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  86815. var BABYLON;
  86816. (function (BABYLON) {
  86817. /**
  86818. * BABYLON.JS Chromatic Aberration GLSL Shader
  86819. * Author: Olivier Guyot
  86820. * Separates very slightly R, G and B colors on the edges of the screen
  86821. * Inspired by Francois Tarlier & Martins Upitis
  86822. */
  86823. var LensRenderingPipeline = /** @class */ (function (_super) {
  86824. __extends(LensRenderingPipeline, _super);
  86825. /**
  86826. * @constructor
  86827. *
  86828. * Effect parameters are as follow:
  86829. * {
  86830. * chromatic_aberration: number; // from 0 to x (1 for realism)
  86831. * edge_blur: number; // from 0 to x (1 for realism)
  86832. * distortion: number; // from 0 to x (1 for realism)
  86833. * grain_amount: number; // from 0 to 1
  86834. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  86835. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  86836. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  86837. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  86838. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  86839. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  86840. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  86841. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  86842. * }
  86843. * Note: if an effect parameter is unset, effect is disabled
  86844. *
  86845. * @param name The rendering pipeline name
  86846. * @param parameters - An object containing all parameters (see above)
  86847. * @param scene The scene linked to this pipeline
  86848. * @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)
  86849. * @param cameras The array of cameras that the rendering pipeline will be attached to
  86850. */
  86851. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  86852. if (ratio === void 0) { ratio = 1.0; }
  86853. var _this = _super.call(this, scene.getEngine(), name) || this;
  86854. // Lens effects can be of the following:
  86855. // - chromatic aberration (slight shift of RGB colors)
  86856. // - blur on the edge of the lens
  86857. // - lens distortion
  86858. // - depth-of-field blur & highlights enhancing
  86859. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  86860. // - grain effect (noise or custom texture)
  86861. // Two additional texture samplers are needed:
  86862. // - depth map (for depth-of-field)
  86863. // - grain texture
  86864. /**
  86865. * @ignore
  86866. * The chromatic aberration PostProcess id in the pipeline
  86867. */
  86868. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  86869. /**
  86870. * @ignore
  86871. * The highlights enhancing PostProcess id in the pipeline
  86872. */
  86873. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  86874. /**
  86875. * @ignore
  86876. * The depth-of-field PostProcess id in the pipeline
  86877. */
  86878. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  86879. _this._scene = scene;
  86880. // Fetch texture samplers
  86881. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  86882. if (parameters.grain_texture) {
  86883. _this._grainTexture = parameters.grain_texture;
  86884. }
  86885. else {
  86886. _this._createGrainTexture();
  86887. }
  86888. // save parameters
  86889. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  86890. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  86891. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  86892. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  86893. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  86894. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  86895. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  86896. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  86897. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  86898. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  86899. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  86900. // Create effects
  86901. _this._createChromaticAberrationPostProcess(ratio);
  86902. _this._createHighlightsPostProcess(ratio);
  86903. _this._createDepthOfFieldPostProcess(ratio / 4);
  86904. // Set up pipeline
  86905. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  86906. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  86907. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  86908. if (_this._highlightsGain === -1) {
  86909. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  86910. }
  86911. // Finish
  86912. scene.postProcessRenderPipelineManager.addPipeline(_this);
  86913. if (cameras) {
  86914. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  86915. }
  86916. return _this;
  86917. }
  86918. // public methods (self explanatory)
  86919. /**
  86920. * Sets the amount of blur at the edges
  86921. * @param amount blur amount
  86922. */
  86923. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  86924. /**
  86925. * Sets edge blur to 0
  86926. */
  86927. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  86928. /**
  86929. * Sets the amout of grain
  86930. * @param amount Amount of grain
  86931. */
  86932. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  86933. /**
  86934. * Set grain amount to 0
  86935. */
  86936. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  86937. /**
  86938. * Sets the chromatic aberration amount
  86939. * @param amount amount of chromatic aberration
  86940. */
  86941. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  86942. /**
  86943. * Sets chromatic aberration amount to 0
  86944. */
  86945. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  86946. /**
  86947. * Sets the EdgeDistortion amount
  86948. * @param amount amount of EdgeDistortion
  86949. */
  86950. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  86951. /**
  86952. * Sets edge distortion to 0
  86953. */
  86954. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  86955. /**
  86956. * Sets the FocusDistance amount
  86957. * @param amount amount of FocusDistance
  86958. */
  86959. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  86960. /**
  86961. * Disables depth of field
  86962. */
  86963. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  86964. /**
  86965. * Sets the Aperture amount
  86966. * @param amount amount of Aperture
  86967. */
  86968. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  86969. /**
  86970. * Sets the DarkenOutOfFocus amount
  86971. * @param amount amount of DarkenOutOfFocus
  86972. */
  86973. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  86974. /**
  86975. * Creates a pentagon bokeh effect
  86976. */
  86977. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  86978. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  86979. };
  86980. /**
  86981. * Disables the pentagon bokeh effect
  86982. */
  86983. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  86984. this._highlightsPostProcess.updateEffect();
  86985. };
  86986. /**
  86987. * Enables noise blur
  86988. */
  86989. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  86990. /**
  86991. * Disables noise blur
  86992. */
  86993. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  86994. /**
  86995. * Sets the HighlightsGain amount
  86996. * @param amount amount of HighlightsGain
  86997. */
  86998. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  86999. this._highlightsGain = amount;
  87000. };
  87001. /**
  87002. * Sets the HighlightsThreshold amount
  87003. * @param amount amount of HighlightsThreshold
  87004. */
  87005. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  87006. if (this._highlightsGain === -1) {
  87007. this._highlightsGain = 1.0;
  87008. }
  87009. this._highlightsThreshold = amount;
  87010. };
  87011. /**
  87012. * Disables highlights
  87013. */
  87014. LensRenderingPipeline.prototype.disableHighlights = function () {
  87015. this._highlightsGain = -1;
  87016. };
  87017. /**
  87018. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  87019. * @param disableDepthRender If the scens depth rendering should be disabled (default: false)
  87020. */
  87021. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  87022. if (disableDepthRender === void 0) { disableDepthRender = false; }
  87023. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  87024. this._chromaticAberrationPostProcess = null;
  87025. this._highlightsPostProcess = null;
  87026. this._depthOfFieldPostProcess = null;
  87027. this._grainTexture.dispose();
  87028. if (disableDepthRender) {
  87029. this._scene.disableDepthRenderer();
  87030. }
  87031. };
  87032. // colors shifting and distortion
  87033. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  87034. var _this = this;
  87035. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  87036. [], // samplers
  87037. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  87038. this._chromaticAberrationPostProcess.onApply = function (effect) {
  87039. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  87040. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  87041. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  87042. effect.setFloat('radialIntensity', 1);
  87043. effect.setFloat2('direction', 17, 17);
  87044. effect.setFloat2('centerPosition', 0.5, 0.5);
  87045. };
  87046. };
  87047. // highlights enhancing
  87048. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  87049. var _this = this;
  87050. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  87051. [], // samplers
  87052. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  87053. this._highlightsPostProcess.onApply = function (effect) {
  87054. effect.setFloat('gain', _this._highlightsGain);
  87055. effect.setFloat('threshold', _this._highlightsThreshold);
  87056. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  87057. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  87058. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  87059. };
  87060. };
  87061. // colors shifting and distortion
  87062. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  87063. var _this = this;
  87064. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  87065. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  87066. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  87067. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  87068. this._depthOfFieldPostProcess.onApply = function (effect) {
  87069. effect.setTexture("depthSampler", _this._depthTexture);
  87070. effect.setTexture("grainSampler", _this._grainTexture);
  87071. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  87072. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  87073. effect.setFloat('grain_amount', _this._grainAmount);
  87074. effect.setBool('blur_noise', _this._blurNoise);
  87075. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  87076. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  87077. effect.setFloat('distortion', _this._distortion);
  87078. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  87079. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  87080. effect.setFloat('aperture', _this._dofAperture);
  87081. effect.setFloat('darken', _this._dofDarken);
  87082. effect.setFloat('edge_blur', _this._edgeBlur);
  87083. effect.setBool('highlights', (_this._highlightsGain !== -1));
  87084. if (_this._scene.activeCamera) {
  87085. effect.setFloat('near', _this._scene.activeCamera.minZ);
  87086. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  87087. }
  87088. };
  87089. };
  87090. // creates a black and white random noise texture, 512x512
  87091. LensRenderingPipeline.prototype._createGrainTexture = function () {
  87092. var size = 512;
  87093. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  87094. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  87095. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  87096. var context = this._grainTexture.getContext();
  87097. var rand = function (min, max) {
  87098. return Math.random() * (max - min) + min;
  87099. };
  87100. var value;
  87101. for (var x = 0; x < size; x++) {
  87102. for (var y = 0; y < size; y++) {
  87103. value = Math.floor(rand(0.42, 0.58) * 255);
  87104. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  87105. context.fillRect(x, y, 1, 1);
  87106. }
  87107. }
  87108. this._grainTexture.update(false);
  87109. };
  87110. return LensRenderingPipeline;
  87111. }(BABYLON.PostProcessRenderPipeline));
  87112. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  87113. })(BABYLON || (BABYLON = {}));
  87114. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  87115. var BABYLON;
  87116. (function (BABYLON) {
  87117. /**
  87118. * Standard rendering pipeline
  87119. * Default pipeline should be used going forward but the standard pipeline will be kept for backwards compatibility.
  87120. * @see https://doc.babylonjs.com/how_to/using_standard_rendering_pipeline
  87121. */
  87122. var StandardRenderingPipeline = /** @class */ (function (_super) {
  87123. __extends(StandardRenderingPipeline, _super);
  87124. /**
  87125. * Default pipeline should be used going forward but the standard pipeline will be kept for backwards compatibility.
  87126. * @constructor
  87127. * @param name The rendering pipeline name
  87128. * @param scene The scene linked to this pipeline
  87129. * @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)
  87130. * @param originalPostProcess the custom original color post-process. Must be "reusable". Can be null.
  87131. * @param cameras The array of cameras that the rendering pipeline will be attached to
  87132. */
  87133. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  87134. if (originalPostProcess === void 0) { originalPostProcess = null; }
  87135. var _this = _super.call(this, scene.getEngine(), name) || this;
  87136. /**
  87137. * Post-process used to down scale an image x4
  87138. */
  87139. _this.downSampleX4PostProcess = null;
  87140. /**
  87141. * Post-process used to calculate the illuminated surfaces controlled by a threshold
  87142. */
  87143. _this.brightPassPostProcess = null;
  87144. /**
  87145. * Post-process array storing all the horizontal blur post-processes used by the pipeline
  87146. */
  87147. _this.blurHPostProcesses = [];
  87148. /**
  87149. * Post-process array storing all the vertical blur post-processes used by the pipeline
  87150. */
  87151. _this.blurVPostProcesses = [];
  87152. /**
  87153. * Post-process used to add colors of 2 textures (typically brightness + real scene color)
  87154. */
  87155. _this.textureAdderPostProcess = null;
  87156. /**
  87157. * Post-process used to create volumetric lighting effect
  87158. */
  87159. _this.volumetricLightPostProcess = null;
  87160. /**
  87161. * Post-process used to smooth the previous volumetric light post-process on the X axis
  87162. */
  87163. _this.volumetricLightSmoothXPostProcess = null;
  87164. /**
  87165. * Post-process used to smooth the previous volumetric light post-process on the Y axis
  87166. */
  87167. _this.volumetricLightSmoothYPostProcess = null;
  87168. /**
  87169. * Post-process used to merge the volumetric light effect and the real scene color
  87170. */
  87171. _this.volumetricLightMergePostProces = null;
  87172. /**
  87173. * Post-process used to store the final volumetric light post-process (attach/detach for debug purpose)
  87174. */
  87175. _this.volumetricLightFinalPostProcess = null;
  87176. /**
  87177. * Base post-process used to calculate the average luminance of the final image for HDR
  87178. */
  87179. _this.luminancePostProcess = null;
  87180. /**
  87181. * Post-processes used to create down sample post-processes in order to get
  87182. * the average luminance of the final image for HDR
  87183. * Array of length "StandardRenderingPipeline.LuminanceSteps"
  87184. */
  87185. _this.luminanceDownSamplePostProcesses = [];
  87186. /**
  87187. * Post-process used to create a HDR effect (light adaptation)
  87188. */
  87189. _this.hdrPostProcess = null;
  87190. /**
  87191. * Post-process used to store the final texture adder post-process (attach/detach for debug purpose)
  87192. */
  87193. _this.textureAdderFinalPostProcess = null;
  87194. /**
  87195. * Post-process used to store the final lens flare post-process (attach/detach for debug purpose)
  87196. */
  87197. _this.lensFlareFinalPostProcess = null;
  87198. /**
  87199. * Post-process used to merge the final HDR post-process and the real scene color
  87200. */
  87201. _this.hdrFinalPostProcess = null;
  87202. /**
  87203. * Post-process used to create a lens flare effect
  87204. */
  87205. _this.lensFlarePostProcess = null;
  87206. /**
  87207. * Post-process that merges the result of the lens flare post-process and the real scene color
  87208. */
  87209. _this.lensFlareComposePostProcess = null;
  87210. /**
  87211. * Post-process used to create a motion blur effect
  87212. */
  87213. _this.motionBlurPostProcess = null;
  87214. /**
  87215. * Post-process used to create a depth of field effect
  87216. */
  87217. _this.depthOfFieldPostProcess = null;
  87218. /**
  87219. * The Fast Approximate Anti-Aliasing post process which attemps to remove aliasing from an image.
  87220. */
  87221. _this.fxaaPostProcess = null;
  87222. // Values
  87223. /**
  87224. * Represents the brightness threshold in order to configure the illuminated surfaces
  87225. */
  87226. _this.brightThreshold = 1.0;
  87227. /**
  87228. * Configures the blur intensity used for surexposed surfaces are highlighted surfaces (light halo)
  87229. */
  87230. _this.blurWidth = 512.0;
  87231. /**
  87232. * Sets if the blur for highlighted surfaces must be only horizontal
  87233. */
  87234. _this.horizontalBlur = false;
  87235. /**
  87236. * Sets the overall exposure used by the pipeline
  87237. */
  87238. _this.exposure = 1.0;
  87239. /**
  87240. * Texture used typically to simulate "dirty" on camera lens
  87241. */
  87242. _this.lensTexture = null;
  87243. /**
  87244. * Represents the offset coefficient based on Rayleigh principle. Typically in interval [-0.2, 0.2]
  87245. */
  87246. _this.volumetricLightCoefficient = 0.2;
  87247. /**
  87248. * The overall power of volumetric lights, typically in interval [0, 10] maximum
  87249. */
  87250. _this.volumetricLightPower = 4.0;
  87251. /**
  87252. * Used the set the blur intensity to smooth the volumetric lights
  87253. */
  87254. _this.volumetricLightBlurScale = 64.0;
  87255. /**
  87256. * Light (spot or directional) used to generate the volumetric lights rays
  87257. * The source light must have a shadow generate so the pipeline can get its
  87258. * depth map
  87259. */
  87260. _this.sourceLight = null;
  87261. /**
  87262. * For eye adaptation, represents the minimum luminance the eye can see
  87263. */
  87264. _this.hdrMinimumLuminance = 1.0;
  87265. /**
  87266. * For eye adaptation, represents the decrease luminance speed
  87267. */
  87268. _this.hdrDecreaseRate = 0.5;
  87269. /**
  87270. * For eye adaptation, represents the increase luminance speed
  87271. */
  87272. _this.hdrIncreaseRate = 0.5;
  87273. /**
  87274. * Lens color texture used by the lens flare effect. Mandatory if lens flare effect enabled
  87275. */
  87276. _this.lensColorTexture = null;
  87277. /**
  87278. * The overall strengh for the lens flare effect
  87279. */
  87280. _this.lensFlareStrength = 20.0;
  87281. /**
  87282. * Dispersion coefficient for lens flare ghosts
  87283. */
  87284. _this.lensFlareGhostDispersal = 1.4;
  87285. /**
  87286. * Main lens flare halo width
  87287. */
  87288. _this.lensFlareHaloWidth = 0.7;
  87289. /**
  87290. * Based on the lens distortion effect, defines how much the lens flare result
  87291. * is distorted
  87292. */
  87293. _this.lensFlareDistortionStrength = 16.0;
  87294. /**
  87295. * Lens star texture must be used to simulate rays on the flares and is available
  87296. * in the documentation
  87297. */
  87298. _this.lensStarTexture = null;
  87299. /**
  87300. * As the "lensTexture" (can be the same texture or different), it is used to apply the lens
  87301. * flare effect by taking account of the dirt texture
  87302. */
  87303. _this.lensFlareDirtTexture = null;
  87304. /**
  87305. * Represents the focal length for the depth of field effect
  87306. */
  87307. _this.depthOfFieldDistance = 10.0;
  87308. /**
  87309. * Represents the blur intensity for the blurred part of the depth of field effect
  87310. */
  87311. _this.depthOfFieldBlurWidth = 64.0;
  87312. /**
  87313. * For motion blur, defines how much the image is blurred by the movement
  87314. */
  87315. _this.motionStrength = 1.0;
  87316. /**
  87317. * List of animations for the pipeline (IAnimatable implementation)
  87318. */
  87319. _this.animations = [];
  87320. _this._currentDepthOfFieldSource = null;
  87321. _this._hdrCurrentLuminance = 1.0;
  87322. // Getters and setters
  87323. _this._bloomEnabled = false;
  87324. _this._depthOfFieldEnabled = false;
  87325. _this._vlsEnabled = false;
  87326. _this._lensFlareEnabled = false;
  87327. _this._hdrEnabled = false;
  87328. _this._motionBlurEnabled = false;
  87329. _this._fxaaEnabled = false;
  87330. _this._motionBlurSamples = 64.0;
  87331. _this._volumetricLightStepsCount = 50.0;
  87332. _this._samples = 1;
  87333. _this._cameras = cameras || [];
  87334. // Initialize
  87335. _this._scene = scene;
  87336. _this._basePostProcess = originalPostProcess;
  87337. _this._ratio = ratio;
  87338. // Misc
  87339. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  87340. // Finish
  87341. scene.postProcessRenderPipelineManager.addPipeline(_this);
  87342. _this._buildPipeline();
  87343. return _this;
  87344. }
  87345. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  87346. /**
  87347. * @ignore
  87348. * Specifies if the bloom pipeline is enabled
  87349. */
  87350. get: function () {
  87351. return this._bloomEnabled;
  87352. },
  87353. set: function (enabled) {
  87354. if (this._bloomEnabled === enabled) {
  87355. return;
  87356. }
  87357. this._bloomEnabled = enabled;
  87358. this._buildPipeline();
  87359. },
  87360. enumerable: true,
  87361. configurable: true
  87362. });
  87363. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  87364. /**
  87365. * @ignore
  87366. * Specifies if the depth of field pipeline is enabed
  87367. */
  87368. get: function () {
  87369. return this._depthOfFieldEnabled;
  87370. },
  87371. set: function (enabled) {
  87372. if (this._depthOfFieldEnabled === enabled) {
  87373. return;
  87374. }
  87375. this._depthOfFieldEnabled = enabled;
  87376. this._buildPipeline();
  87377. },
  87378. enumerable: true,
  87379. configurable: true
  87380. });
  87381. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  87382. /**
  87383. * @ignore
  87384. * Specifies if the lens flare pipeline is enabed
  87385. */
  87386. get: function () {
  87387. return this._lensFlareEnabled;
  87388. },
  87389. set: function (enabled) {
  87390. if (this._lensFlareEnabled === enabled) {
  87391. return;
  87392. }
  87393. this._lensFlareEnabled = enabled;
  87394. this._buildPipeline();
  87395. },
  87396. enumerable: true,
  87397. configurable: true
  87398. });
  87399. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  87400. /**
  87401. * @ignore
  87402. * Specifies if the HDR pipeline is enabled
  87403. */
  87404. get: function () {
  87405. return this._hdrEnabled;
  87406. },
  87407. set: function (enabled) {
  87408. if (this._hdrEnabled === enabled) {
  87409. return;
  87410. }
  87411. this._hdrEnabled = enabled;
  87412. this._buildPipeline();
  87413. },
  87414. enumerable: true,
  87415. configurable: true
  87416. });
  87417. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  87418. /**
  87419. * @ignore
  87420. * Specifies if the volumetric lights scattering effect is enabled
  87421. */
  87422. get: function () {
  87423. return this._vlsEnabled;
  87424. },
  87425. set: function (enabled) {
  87426. if (this._vlsEnabled === enabled) {
  87427. return;
  87428. }
  87429. if (enabled) {
  87430. var geometry = this._scene.enableGeometryBufferRenderer();
  87431. if (!geometry) {
  87432. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  87433. return;
  87434. }
  87435. }
  87436. this._vlsEnabled = enabled;
  87437. this._buildPipeline();
  87438. },
  87439. enumerable: true,
  87440. configurable: true
  87441. });
  87442. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  87443. /**
  87444. * @ignore
  87445. * Specifies if the motion blur effect is enabled
  87446. */
  87447. get: function () {
  87448. return this._motionBlurEnabled;
  87449. },
  87450. set: function (enabled) {
  87451. if (this._motionBlurEnabled === enabled) {
  87452. return;
  87453. }
  87454. this._motionBlurEnabled = enabled;
  87455. this._buildPipeline();
  87456. },
  87457. enumerable: true,
  87458. configurable: true
  87459. });
  87460. Object.defineProperty(StandardRenderingPipeline.prototype, "fxaaEnabled", {
  87461. /**
  87462. * Specifies if anti-aliasing is enabled
  87463. */
  87464. get: function () {
  87465. return this._fxaaEnabled;
  87466. },
  87467. set: function (enabled) {
  87468. if (this._fxaaEnabled === enabled) {
  87469. return;
  87470. }
  87471. this._fxaaEnabled = enabled;
  87472. this._buildPipeline();
  87473. },
  87474. enumerable: true,
  87475. configurable: true
  87476. });
  87477. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  87478. /**
  87479. * Specifies the number of steps used to calculate the volumetric lights
  87480. * Typically in interval [50, 200]
  87481. */
  87482. get: function () {
  87483. return this._volumetricLightStepsCount;
  87484. },
  87485. set: function (count) {
  87486. if (this.volumetricLightPostProcess) {
  87487. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  87488. }
  87489. this._volumetricLightStepsCount = count;
  87490. },
  87491. enumerable: true,
  87492. configurable: true
  87493. });
  87494. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  87495. /**
  87496. * Specifies the number of samples used for the motion blur effect
  87497. * Typically in interval [16, 64]
  87498. */
  87499. get: function () {
  87500. return this._motionBlurSamples;
  87501. },
  87502. set: function (samples) {
  87503. if (this.motionBlurPostProcess) {
  87504. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  87505. }
  87506. this._motionBlurSamples = samples;
  87507. },
  87508. enumerable: true,
  87509. configurable: true
  87510. });
  87511. Object.defineProperty(StandardRenderingPipeline.prototype, "samples", {
  87512. /**
  87513. * Specifies MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  87514. */
  87515. get: function () {
  87516. return this._samples;
  87517. },
  87518. set: function (sampleCount) {
  87519. if (this._samples === sampleCount) {
  87520. return;
  87521. }
  87522. this._samples = sampleCount;
  87523. this._buildPipeline();
  87524. },
  87525. enumerable: true,
  87526. configurable: true
  87527. });
  87528. StandardRenderingPipeline.prototype._buildPipeline = function () {
  87529. var _this = this;
  87530. var ratio = this._ratio;
  87531. var scene = this._scene;
  87532. this._disposePostProcesses();
  87533. this._reset();
  87534. // Create pass post-process
  87535. if (!this._basePostProcess) {
  87536. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  87537. this.originalPostProcess.onApply = function (effect) {
  87538. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  87539. };
  87540. }
  87541. else {
  87542. this.originalPostProcess = this._basePostProcess;
  87543. }
  87544. if (this._bloomEnabled || this._vlsEnabled || this._lensFlareEnabled || this._depthOfFieldEnabled || this._motionBlurEnabled) {
  87545. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  87546. }
  87547. this._currentDepthOfFieldSource = this.originalPostProcess;
  87548. if (this._bloomEnabled) {
  87549. // Create down sample X4 post-process
  87550. this._createDownSampleX4PostProcess(scene, ratio / 2);
  87551. // Create bright pass post-process
  87552. this._createBrightPassPostProcess(scene, ratio / 2);
  87553. // Create gaussian blur post-processes (down sampling blurs)
  87554. this._createBlurPostProcesses(scene, ratio / 4, 1);
  87555. // Create texture adder post-process
  87556. this._createTextureAdderPostProcess(scene, ratio);
  87557. // Create depth-of-field source post-process
  87558. 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);
  87559. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  87560. }
  87561. if (this._vlsEnabled) {
  87562. // Create volumetric light
  87563. this._createVolumetricLightPostProcess(scene, ratio);
  87564. // Create volumetric light final post-process
  87565. 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);
  87566. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  87567. }
  87568. if (this._lensFlareEnabled) {
  87569. // Create lens flare post-process
  87570. this._createLensFlarePostProcess(scene, ratio);
  87571. // Create depth-of-field source post-process post lens-flare and disable it now
  87572. 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);
  87573. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  87574. }
  87575. if (this._hdrEnabled) {
  87576. // Create luminance
  87577. this._createLuminancePostProcesses(scene, this._floatTextureType);
  87578. // Create HDR
  87579. this._createHdrPostProcess(scene, ratio);
  87580. // Create depth-of-field source post-process post hdr and disable it now
  87581. 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);
  87582. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  87583. }
  87584. if (this._depthOfFieldEnabled) {
  87585. // Create gaussian blur used by depth-of-field
  87586. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  87587. // Create depth-of-field post-process
  87588. this._createDepthOfFieldPostProcess(scene, ratio);
  87589. }
  87590. if (this._motionBlurEnabled) {
  87591. // Create motion blur post-process
  87592. this._createMotionBlurPostProcess(scene, ratio);
  87593. }
  87594. if (this._fxaaEnabled) {
  87595. // Create fxaa post-process
  87596. this.fxaaPostProcess = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  87597. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRFxaa", function () { return _this.fxaaPostProcess; }, true));
  87598. }
  87599. if (this._cameras !== null) {
  87600. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  87601. }
  87602. if (!this._enableMSAAOnFirstPostProcess(this._samples) && this._samples > 1) {
  87603. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  87604. }
  87605. };
  87606. // Down Sample X4 Post-Processs
  87607. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  87608. var _this = this;
  87609. var downSampleX4Offsets = new Array(32);
  87610. 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);
  87611. this.downSampleX4PostProcess.onApply = function (effect) {
  87612. var id = 0;
  87613. var width = _this.downSampleX4PostProcess.width;
  87614. var height = _this.downSampleX4PostProcess.height;
  87615. for (var i = -2; i < 2; i++) {
  87616. for (var j = -2; j < 2; j++) {
  87617. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  87618. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  87619. id += 2;
  87620. }
  87621. }
  87622. effect.setArray2("dsOffsets", downSampleX4Offsets);
  87623. };
  87624. // Add to pipeline
  87625. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  87626. };
  87627. // Brightpass Post-Process
  87628. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  87629. var _this = this;
  87630. var brightOffsets = new Array(8);
  87631. 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);
  87632. this.brightPassPostProcess.onApply = function (effect) {
  87633. var sU = (1.0 / _this.brightPassPostProcess.width);
  87634. var sV = (1.0 / _this.brightPassPostProcess.height);
  87635. brightOffsets[0] = -0.5 * sU;
  87636. brightOffsets[1] = 0.5 * sV;
  87637. brightOffsets[2] = 0.5 * sU;
  87638. brightOffsets[3] = 0.5 * sV;
  87639. brightOffsets[4] = -0.5 * sU;
  87640. brightOffsets[5] = -0.5 * sV;
  87641. brightOffsets[6] = 0.5 * sU;
  87642. brightOffsets[7] = -0.5 * sV;
  87643. effect.setArray2("dsOffsets", brightOffsets);
  87644. effect.setFloat("brightThreshold", _this.brightThreshold);
  87645. };
  87646. // Add to pipeline
  87647. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  87648. };
  87649. // Create blur H&V post-processes
  87650. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  87651. var _this = this;
  87652. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  87653. var engine = scene.getEngine();
  87654. 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);
  87655. 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);
  87656. blurX.onActivateObservable.add(function () {
  87657. var dw = blurX.width / engine.getRenderWidth();
  87658. blurX.kernel = _this[blurWidthKey] * dw;
  87659. });
  87660. blurY.onActivateObservable.add(function () {
  87661. var dw = blurY.height / engine.getRenderHeight();
  87662. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  87663. });
  87664. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  87665. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  87666. this.blurHPostProcesses.push(blurX);
  87667. this.blurVPostProcesses.push(blurY);
  87668. };
  87669. // Create texture adder post-process
  87670. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  87671. var _this = this;
  87672. 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);
  87673. this.textureAdderPostProcess.onApply = function (effect) {
  87674. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  87675. effect.setTexture("lensSampler", _this.lensTexture);
  87676. effect.setFloat("exposure", _this.exposure);
  87677. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  87678. };
  87679. // Add to pipeline
  87680. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  87681. };
  87682. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  87683. var _this = this;
  87684. var geometryRenderer = scene.enableGeometryBufferRenderer();
  87685. geometryRenderer.enablePosition = true;
  87686. var geometry = geometryRenderer.getGBuffer();
  87687. // Base post-process
  87688. 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));
  87689. var depthValues = BABYLON.Vector2.Zero();
  87690. this.volumetricLightPostProcess.onApply = function (effect) {
  87691. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  87692. var generator = _this.sourceLight.getShadowGenerator();
  87693. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  87694. effect.setTexture("positionSampler", geometry.textures[2]);
  87695. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  87696. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  87697. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  87698. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  87699. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  87700. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  87701. depthValues.x = _this.sourceLight.getDepthMinZ(_this._scene.activeCamera);
  87702. depthValues.y = _this.sourceLight.getDepthMaxZ(_this._scene.activeCamera);
  87703. effect.setVector2("depthValues", depthValues);
  87704. }
  87705. };
  87706. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  87707. // Smooth
  87708. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  87709. // Merge
  87710. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  87711. this.volumetricLightMergePostProces.onApply = function (effect) {
  87712. effect.setTextureFromPostProcess("originalSampler", _this._bloomEnabled ? _this.textureAdderFinalPostProcess : _this.originalPostProcess);
  87713. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  87714. };
  87715. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  87716. };
  87717. // Create luminance
  87718. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  87719. var _this = this;
  87720. // Create luminance
  87721. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  87722. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  87723. var offsets = [];
  87724. this.luminancePostProcess.onApply = function (effect) {
  87725. var sU = (1.0 / _this.luminancePostProcess.width);
  87726. var sV = (1.0 / _this.luminancePostProcess.height);
  87727. offsets[0] = -0.5 * sU;
  87728. offsets[1] = 0.5 * sV;
  87729. offsets[2] = 0.5 * sU;
  87730. offsets[3] = 0.5 * sV;
  87731. offsets[4] = -0.5 * sU;
  87732. offsets[5] = -0.5 * sV;
  87733. offsets[6] = 0.5 * sU;
  87734. offsets[7] = -0.5 * sV;
  87735. effect.setArray2("lumOffsets", offsets);
  87736. };
  87737. // Add to pipeline
  87738. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  87739. // Create down sample luminance
  87740. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  87741. var size = Math.pow(3, i);
  87742. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  87743. if (i === 0) {
  87744. defines += "#define FINAL_DOWN_SAMPLER";
  87745. }
  87746. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  87747. this.luminanceDownSamplePostProcesses.push(postProcess);
  87748. }
  87749. // Create callbacks and add effects
  87750. var lastLuminance = this.luminancePostProcess;
  87751. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  87752. var downSampleOffsets = new Array(18);
  87753. pp.onApply = function (effect) {
  87754. if (!lastLuminance) {
  87755. return;
  87756. }
  87757. var id = 0;
  87758. for (var x = -1; x < 2; x++) {
  87759. for (var y = -1; y < 2; y++) {
  87760. downSampleOffsets[id] = x / lastLuminance.width;
  87761. downSampleOffsets[id + 1] = y / lastLuminance.height;
  87762. id += 2;
  87763. }
  87764. }
  87765. effect.setArray2("dsOffsets", downSampleOffsets);
  87766. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  87767. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  87768. lastLuminance = _this.luminancePostProcess;
  87769. }
  87770. else {
  87771. lastLuminance = pp;
  87772. }
  87773. };
  87774. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  87775. pp.onAfterRender = function (effect) {
  87776. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  87777. 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);
  87778. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  87779. };
  87780. }
  87781. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  87782. });
  87783. };
  87784. // Create HDR post-process
  87785. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  87786. var _this = this;
  87787. 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);
  87788. var outputLiminance = 1;
  87789. var time = 0;
  87790. var lastTime = 0;
  87791. this.hdrPostProcess.onApply = function (effect) {
  87792. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  87793. time += scene.getEngine().getDeltaTime();
  87794. if (outputLiminance < 0) {
  87795. outputLiminance = _this._hdrCurrentLuminance;
  87796. }
  87797. else {
  87798. var dt = (lastTime - time) / 1000.0;
  87799. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  87800. outputLiminance += _this.hdrDecreaseRate * dt;
  87801. }
  87802. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  87803. outputLiminance -= _this.hdrIncreaseRate * dt;
  87804. }
  87805. else {
  87806. outputLiminance = _this._hdrCurrentLuminance;
  87807. }
  87808. }
  87809. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  87810. effect.setFloat("averageLuminance", outputLiminance);
  87811. lastTime = time;
  87812. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  87813. };
  87814. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  87815. };
  87816. // Create lens flare post-process
  87817. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  87818. var _this = this;
  87819. 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);
  87820. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  87821. this._createBlurPostProcesses(scene, ratio / 4, 2);
  87822. 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);
  87823. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  87824. var resolution = new BABYLON.Vector2(0, 0);
  87825. // Lens flare
  87826. this.lensFlarePostProcess.onApply = function (effect) {
  87827. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  87828. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  87829. effect.setFloat("strength", _this.lensFlareStrength);
  87830. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  87831. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  87832. // Shift
  87833. resolution.x = _this.lensFlarePostProcess.width;
  87834. resolution.y = _this.lensFlarePostProcess.height;
  87835. effect.setVector2("resolution", resolution);
  87836. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  87837. };
  87838. // Compose
  87839. 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);
  87840. 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);
  87841. this.lensFlareComposePostProcess.onApply = function (effect) {
  87842. if (!_this._scene.activeCamera) {
  87843. return;
  87844. }
  87845. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  87846. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  87847. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  87848. // Lens start rotation matrix
  87849. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  87850. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  87851. 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));
  87852. camRot *= 4.0;
  87853. 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);
  87854. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  87855. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  87856. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  87857. };
  87858. };
  87859. // Create depth-of-field post-process
  87860. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  87861. var _this = this;
  87862. 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);
  87863. this.depthOfFieldPostProcess.onApply = function (effect) {
  87864. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  87865. effect.setTexture("depthSampler", _this._getDepthTexture());
  87866. effect.setFloat("distance", _this.depthOfFieldDistance);
  87867. };
  87868. // Add to pipeline
  87869. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  87870. };
  87871. // Create motion blur post-process
  87872. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  87873. var _this = this;
  87874. 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);
  87875. var motionScale = 0;
  87876. var prevViewProjection = BABYLON.Matrix.Identity();
  87877. var invViewProjection = BABYLON.Matrix.Identity();
  87878. var viewProjection = BABYLON.Matrix.Identity();
  87879. var screenSize = BABYLON.Vector2.Zero();
  87880. this.motionBlurPostProcess.onApply = function (effect) {
  87881. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  87882. viewProjection.invertToRef(invViewProjection);
  87883. effect.setMatrix("inverseViewProjection", invViewProjection);
  87884. effect.setMatrix("prevViewProjection", prevViewProjection);
  87885. prevViewProjection = viewProjection;
  87886. screenSize.x = _this.motionBlurPostProcess.width;
  87887. screenSize.y = _this.motionBlurPostProcess.height;
  87888. effect.setVector2("screenSize", screenSize);
  87889. motionScale = scene.getEngine().getFps() / 60.0;
  87890. effect.setFloat("motionScale", motionScale);
  87891. effect.setFloat("motionStrength", _this.motionStrength);
  87892. effect.setTexture("depthSampler", _this._getDepthTexture());
  87893. };
  87894. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  87895. };
  87896. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  87897. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  87898. var renderer = this._scene.enableGeometryBufferRenderer();
  87899. return renderer.getGBuffer().textures[0];
  87900. }
  87901. return this._scene.enableDepthRenderer().getDepthMap();
  87902. };
  87903. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  87904. for (var i = 0; i < this._cameras.length; i++) {
  87905. var camera = this._cameras[i];
  87906. if (this.originalPostProcess) {
  87907. this.originalPostProcess.dispose(camera);
  87908. }
  87909. if (this.downSampleX4PostProcess) {
  87910. this.downSampleX4PostProcess.dispose(camera);
  87911. }
  87912. if (this.brightPassPostProcess) {
  87913. this.brightPassPostProcess.dispose(camera);
  87914. }
  87915. if (this.textureAdderPostProcess) {
  87916. this.textureAdderPostProcess.dispose(camera);
  87917. }
  87918. if (this.textureAdderFinalPostProcess) {
  87919. this.textureAdderFinalPostProcess.dispose(camera);
  87920. }
  87921. if (this.volumetricLightPostProcess) {
  87922. this.volumetricLightPostProcess.dispose(camera);
  87923. }
  87924. if (this.volumetricLightSmoothXPostProcess) {
  87925. this.volumetricLightSmoothXPostProcess.dispose(camera);
  87926. }
  87927. if (this.volumetricLightSmoothYPostProcess) {
  87928. this.volumetricLightSmoothYPostProcess.dispose(camera);
  87929. }
  87930. if (this.volumetricLightMergePostProces) {
  87931. this.volumetricLightMergePostProces.dispose(camera);
  87932. }
  87933. if (this.volumetricLightFinalPostProcess) {
  87934. this.volumetricLightFinalPostProcess.dispose(camera);
  87935. }
  87936. if (this.lensFlarePostProcess) {
  87937. this.lensFlarePostProcess.dispose(camera);
  87938. }
  87939. if (this.lensFlareComposePostProcess) {
  87940. this.lensFlareComposePostProcess.dispose(camera);
  87941. }
  87942. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  87943. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  87944. }
  87945. if (this.luminancePostProcess) {
  87946. this.luminancePostProcess.dispose(camera);
  87947. }
  87948. if (this.hdrPostProcess) {
  87949. this.hdrPostProcess.dispose(camera);
  87950. }
  87951. if (this.hdrFinalPostProcess) {
  87952. this.hdrFinalPostProcess.dispose(camera);
  87953. }
  87954. if (this.depthOfFieldPostProcess) {
  87955. this.depthOfFieldPostProcess.dispose(camera);
  87956. }
  87957. if (this.motionBlurPostProcess) {
  87958. this.motionBlurPostProcess.dispose(camera);
  87959. }
  87960. if (this.fxaaPostProcess) {
  87961. this.fxaaPostProcess.dispose(camera);
  87962. }
  87963. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  87964. this.blurHPostProcesses[j].dispose(camera);
  87965. }
  87966. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  87967. this.blurVPostProcesses[j].dispose(camera);
  87968. }
  87969. }
  87970. this.originalPostProcess = null;
  87971. this.downSampleX4PostProcess = null;
  87972. this.brightPassPostProcess = null;
  87973. this.textureAdderPostProcess = null;
  87974. this.textureAdderFinalPostProcess = null;
  87975. this.volumetricLightPostProcess = null;
  87976. this.volumetricLightSmoothXPostProcess = null;
  87977. this.volumetricLightSmoothYPostProcess = null;
  87978. this.volumetricLightMergePostProces = null;
  87979. this.volumetricLightFinalPostProcess = null;
  87980. this.lensFlarePostProcess = null;
  87981. this.lensFlareComposePostProcess = null;
  87982. this.luminancePostProcess = null;
  87983. this.hdrPostProcess = null;
  87984. this.hdrFinalPostProcess = null;
  87985. this.depthOfFieldPostProcess = null;
  87986. this.motionBlurPostProcess = null;
  87987. this.fxaaPostProcess = null;
  87988. this.luminanceDownSamplePostProcesses = [];
  87989. this.blurHPostProcesses = [];
  87990. this.blurVPostProcesses = [];
  87991. };
  87992. /**
  87993. * Dispose of the pipeline and stop all post processes
  87994. */
  87995. StandardRenderingPipeline.prototype.dispose = function () {
  87996. this._disposePostProcesses();
  87997. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  87998. _super.prototype.dispose.call(this);
  87999. };
  88000. /**
  88001. * Serialize the rendering pipeline (Used when exporting)
  88002. * @returns the serialized object
  88003. */
  88004. StandardRenderingPipeline.prototype.serialize = function () {
  88005. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  88006. if (this.sourceLight) {
  88007. serializationObject.sourceLightId = this.sourceLight.id;
  88008. }
  88009. serializationObject.customType = "StandardRenderingPipeline";
  88010. return serializationObject;
  88011. };
  88012. /**
  88013. * Parse the serialized pipeline
  88014. * @param source Source pipeline.
  88015. * @param scene The scene to load the pipeline to.
  88016. * @param rootUrl The URL of the serialized pipeline.
  88017. * @returns An instantiated pipeline from the serialized object.
  88018. */
  88019. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  88020. var p = BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  88021. if (source.sourceLightId) {
  88022. p.sourceLight = scene.getLightByID(source.sourceLightId);
  88023. }
  88024. return p;
  88025. };
  88026. /**
  88027. * Luminance steps
  88028. */
  88029. StandardRenderingPipeline.LuminanceSteps = 6;
  88030. __decorate([
  88031. BABYLON.serialize()
  88032. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  88033. __decorate([
  88034. BABYLON.serialize()
  88035. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  88036. __decorate([
  88037. BABYLON.serialize()
  88038. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  88039. __decorate([
  88040. BABYLON.serialize()
  88041. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  88042. __decorate([
  88043. BABYLON.serializeAsTexture("lensTexture")
  88044. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  88045. __decorate([
  88046. BABYLON.serialize()
  88047. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  88048. __decorate([
  88049. BABYLON.serialize()
  88050. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  88051. __decorate([
  88052. BABYLON.serialize()
  88053. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  88054. __decorate([
  88055. BABYLON.serialize()
  88056. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  88057. __decorate([
  88058. BABYLON.serialize()
  88059. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  88060. __decorate([
  88061. BABYLON.serialize()
  88062. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  88063. __decorate([
  88064. BABYLON.serializeAsTexture("lensColorTexture")
  88065. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  88066. __decorate([
  88067. BABYLON.serialize()
  88068. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  88069. __decorate([
  88070. BABYLON.serialize()
  88071. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  88072. __decorate([
  88073. BABYLON.serialize()
  88074. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  88075. __decorate([
  88076. BABYLON.serialize()
  88077. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  88078. __decorate([
  88079. BABYLON.serializeAsTexture("lensStarTexture")
  88080. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  88081. __decorate([
  88082. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  88083. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  88084. __decorate([
  88085. BABYLON.serialize()
  88086. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  88087. __decorate([
  88088. BABYLON.serialize()
  88089. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  88090. __decorate([
  88091. BABYLON.serialize()
  88092. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  88093. __decorate([
  88094. BABYLON.serialize()
  88095. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  88096. __decorate([
  88097. BABYLON.serialize()
  88098. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  88099. __decorate([
  88100. BABYLON.serialize()
  88101. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  88102. __decorate([
  88103. BABYLON.serialize()
  88104. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  88105. __decorate([
  88106. BABYLON.serialize()
  88107. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  88108. __decorate([
  88109. BABYLON.serialize()
  88110. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  88111. __decorate([
  88112. BABYLON.serialize()
  88113. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  88114. __decorate([
  88115. BABYLON.serialize()
  88116. ], StandardRenderingPipeline.prototype, "fxaaEnabled", null);
  88117. __decorate([
  88118. BABYLON.serialize()
  88119. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  88120. __decorate([
  88121. BABYLON.serialize()
  88122. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  88123. __decorate([
  88124. BABYLON.serialize()
  88125. ], StandardRenderingPipeline.prototype, "samples", null);
  88126. return StandardRenderingPipeline;
  88127. }(BABYLON.PostProcessRenderPipeline));
  88128. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  88129. })(BABYLON || (BABYLON = {}));
  88130. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  88131. var BABYLON;
  88132. (function (BABYLON) {
  88133. /**
  88134. * Fxaa post process
  88135. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses#fxaa
  88136. */
  88137. var FxaaPostProcess = /** @class */ (function (_super) {
  88138. __extends(FxaaPostProcess, _super);
  88139. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  88140. if (camera === void 0) { camera = null; }
  88141. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  88142. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa", undefined, true) || this;
  88143. var defines = _this._getDefines();
  88144. _this.updateEffect(defines);
  88145. _this.onApplyObservable.add(function (effect) {
  88146. var texelSize = _this.texelSize;
  88147. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  88148. });
  88149. return _this;
  88150. }
  88151. FxaaPostProcess.prototype._getDefines = function () {
  88152. var engine = this.getEngine();
  88153. if (!engine) {
  88154. return null;
  88155. }
  88156. var glInfo = engine.getGlInfo();
  88157. if (glInfo && glInfo.renderer && glInfo.renderer.toLowerCase().indexOf("mali") > -1) {
  88158. return "#define MALI 1\n";
  88159. }
  88160. return null;
  88161. };
  88162. return FxaaPostProcess;
  88163. }(BABYLON.PostProcess));
  88164. BABYLON.FxaaPostProcess = FxaaPostProcess;
  88165. })(BABYLON || (BABYLON = {}));
  88166. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  88167. var BABYLON;
  88168. (function (BABYLON) {
  88169. /**
  88170. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  88171. */
  88172. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  88173. __extends(ChromaticAberrationPostProcess, _super);
  88174. /**
  88175. * Creates a new instance ChromaticAberrationPostProcess
  88176. * @param name The name of the effect.
  88177. * @param screenWidth The width of the screen to apply the effect on.
  88178. * @param screenHeight The height of the screen to apply the effect on.
  88179. * @param options The required width/height ratio to downsize to before computing the render pass.
  88180. * @param camera The camera to apply the render pass to.
  88181. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  88182. * @param engine The engine which the post process will be applied. (default: current engine)
  88183. * @param reusable If the post process can be reused on the same frame. (default: false)
  88184. * @param textureType Type of textures used when performing the post process. (default: 0)
  88185. * @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)
  88186. */
  88187. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  88188. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  88189. if (blockCompilation === void 0) { blockCompilation = false; }
  88190. 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;
  88191. /**
  88192. * The amount of seperation of rgb channels (default: 30)
  88193. */
  88194. _this.aberrationAmount = 30;
  88195. /**
  88196. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  88197. */
  88198. _this.radialIntensity = 0;
  88199. /**
  88200. * 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))
  88201. */
  88202. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  88203. /**
  88204. * 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))
  88205. */
  88206. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  88207. _this.onApplyObservable.add(function (effect) {
  88208. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  88209. effect.setFloat('screen_width', screenWidth);
  88210. effect.setFloat('screen_height', screenHeight);
  88211. effect.setFloat('radialIntensity', _this.radialIntensity);
  88212. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  88213. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  88214. });
  88215. return _this;
  88216. }
  88217. return ChromaticAberrationPostProcess;
  88218. }(BABYLON.PostProcess));
  88219. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  88220. })(BABYLON || (BABYLON = {}));
  88221. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  88222. var BABYLON;
  88223. (function (BABYLON) {
  88224. /**
  88225. * The GrainPostProcess adds noise to the image at mid luminance levels
  88226. */
  88227. var GrainPostProcess = /** @class */ (function (_super) {
  88228. __extends(GrainPostProcess, _super);
  88229. /**
  88230. * Creates a new instance of @see GrainPostProcess
  88231. * @param name The name of the effect.
  88232. * @param options The required width/height ratio to downsize to before computing the render pass.
  88233. * @param camera The camera to apply the render pass to.
  88234. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  88235. * @param engine The engine which the post process will be applied. (default: current engine)
  88236. * @param reusable If the post process can be reused on the same frame. (default: false)
  88237. * @param textureType Type of textures used when performing the post process. (default: 0)
  88238. * @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)
  88239. */
  88240. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  88241. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  88242. if (blockCompilation === void 0) { blockCompilation = false; }
  88243. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  88244. /**
  88245. * The intensity of the grain added (default: 30)
  88246. */
  88247. _this.intensity = 30;
  88248. /**
  88249. * If the grain should be randomized on every frame
  88250. */
  88251. _this.animated = false;
  88252. _this.onApplyObservable.add(function (effect) {
  88253. effect.setFloat('intensity', _this.intensity);
  88254. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  88255. });
  88256. return _this;
  88257. }
  88258. return GrainPostProcess;
  88259. }(BABYLON.PostProcess));
  88260. BABYLON.GrainPostProcess = GrainPostProcess;
  88261. })(BABYLON || (BABYLON = {}));
  88262. //# sourceMappingURL=babylon.grainPostProcess.js.map
  88263. var BABYLON;
  88264. (function (BABYLON) {
  88265. /**
  88266. * The SharpenPostProcess applies a sharpen kernel to every pixel
  88267. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  88268. */
  88269. var SharpenPostProcess = /** @class */ (function (_super) {
  88270. __extends(SharpenPostProcess, _super);
  88271. /**
  88272. * Creates a new instance ConvolutionPostProcess
  88273. * @param name The name of the effect.
  88274. * @param options The required width/height ratio to downsize to before computing the render pass.
  88275. * @param camera The camera to apply the render pass to.
  88276. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  88277. * @param engine The engine which the post process will be applied. (default: current engine)
  88278. * @param reusable If the post process can be reused on the same frame. (default: false)
  88279. * @param textureType Type of textures used when performing the post process. (default: 0)
  88280. * @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)
  88281. */
  88282. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  88283. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  88284. if (blockCompilation === void 0) { blockCompilation = false; }
  88285. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  88286. /**
  88287. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  88288. */
  88289. _this.colorAmount = 1.0;
  88290. /**
  88291. * How much sharpness should be applied (default: 0.3)
  88292. */
  88293. _this.edgeAmount = 0.3;
  88294. _this.onApply = function (effect) {
  88295. effect.setFloat2("screenSize", _this.width, _this.height);
  88296. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  88297. };
  88298. return _this;
  88299. }
  88300. return SharpenPostProcess;
  88301. }(BABYLON.PostProcess));
  88302. BABYLON.SharpenPostProcess = SharpenPostProcess;
  88303. })(BABYLON || (BABYLON = {}));
  88304. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  88305. var BABYLON;
  88306. (function (BABYLON) {
  88307. /**
  88308. * The Blur Post Process which blurs an image based on a kernel and direction.
  88309. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  88310. */
  88311. var BlurPostProcess = /** @class */ (function (_super) {
  88312. __extends(BlurPostProcess, _super);
  88313. /**
  88314. * Creates a new instance BlurPostProcess
  88315. * @param name The name of the effect.
  88316. * @param direction The direction in which to blur the image.
  88317. * @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.
  88318. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  88319. * @param camera The camera to apply the render pass to.
  88320. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  88321. * @param engine The engine which the post process will be applied. (default: current engine)
  88322. * @param reusable If the post process can be reused on the same frame. (default: false)
  88323. * @param textureType Type of textures used when performing the post process. (default: 0)
  88324. * @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)
  88325. */
  88326. function BlurPostProcess(name,
  88327. /** The direction in which to blur the image. */
  88328. direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  88329. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  88330. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  88331. if (defines === void 0) { defines = ""; }
  88332. if (blockCompilation === void 0) { blockCompilation = false; }
  88333. 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;
  88334. _this.direction = direction;
  88335. _this.blockCompilation = blockCompilation;
  88336. _this._packedFloat = false;
  88337. _this._staticDefines = "";
  88338. _this._staticDefines = defines;
  88339. _this.onApplyObservable.add(function (effect) {
  88340. if (_this._outputTexture) {
  88341. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  88342. }
  88343. else {
  88344. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  88345. }
  88346. });
  88347. _this.kernel = kernel;
  88348. return _this;
  88349. }
  88350. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  88351. /**
  88352. * Gets the length in pixels of the blur sample region
  88353. */
  88354. get: function () {
  88355. return this._idealKernel;
  88356. },
  88357. /**
  88358. * Sets the length in pixels of the blur sample region
  88359. */
  88360. set: function (v) {
  88361. if (this._idealKernel === v) {
  88362. return;
  88363. }
  88364. v = Math.max(v, 1);
  88365. this._idealKernel = v;
  88366. this._kernel = this._nearestBestKernel(v);
  88367. if (!this.blockCompilation) {
  88368. this._updateParameters();
  88369. }
  88370. },
  88371. enumerable: true,
  88372. configurable: true
  88373. });
  88374. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  88375. /**
  88376. * Gets wether or not the blur is unpacking/repacking floats
  88377. */
  88378. get: function () {
  88379. return this._packedFloat;
  88380. },
  88381. /**
  88382. * Sets wether or not the blur needs to unpack/repack floats
  88383. */
  88384. set: function (v) {
  88385. if (this._packedFloat === v) {
  88386. return;
  88387. }
  88388. this._packedFloat = v;
  88389. if (!this.blockCompilation) {
  88390. this._updateParameters();
  88391. }
  88392. },
  88393. enumerable: true,
  88394. configurable: true
  88395. });
  88396. /**
  88397. * Updates the effect with the current post process compile time values and recompiles the shader.
  88398. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  88399. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  88400. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  88401. * @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
  88402. * @param onCompiled Called when the shader has been compiled.
  88403. * @param onError Called if there is an error when compiling a shader.
  88404. */
  88405. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  88406. if (defines === void 0) { defines = null; }
  88407. if (uniforms === void 0) { uniforms = null; }
  88408. if (samplers === void 0) { samplers = null; }
  88409. this._updateParameters(onCompiled, onError);
  88410. };
  88411. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  88412. // Generate sampling offsets and weights
  88413. var N = this._kernel;
  88414. var centerIndex = (N - 1) / 2;
  88415. // Generate Gaussian sampling weights over kernel
  88416. var offsets = [];
  88417. var weights = [];
  88418. var totalWeight = 0;
  88419. for (var i = 0; i < N; i++) {
  88420. var u = i / (N - 1);
  88421. var w = this._gaussianWeight(u * 2.0 - 1);
  88422. offsets[i] = (i - centerIndex);
  88423. weights[i] = w;
  88424. totalWeight += w;
  88425. }
  88426. // Normalize weights
  88427. for (var i = 0; i < weights.length; i++) {
  88428. weights[i] /= totalWeight;
  88429. }
  88430. // Optimize: combine samples to take advantage of hardware linear sampling
  88431. // Walk from left to center, combining pairs (symmetrically)
  88432. var linearSamplingWeights = [];
  88433. var linearSamplingOffsets = [];
  88434. var linearSamplingMap = [];
  88435. for (var i = 0; i <= centerIndex; i += 2) {
  88436. var j = Math.min(i + 1, Math.floor(centerIndex));
  88437. var singleCenterSample = i === j;
  88438. if (singleCenterSample) {
  88439. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  88440. }
  88441. else {
  88442. var sharedCell = j === centerIndex;
  88443. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  88444. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  88445. if (offsetLinear === 0) {
  88446. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  88447. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  88448. }
  88449. else {
  88450. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  88451. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  88452. }
  88453. }
  88454. }
  88455. for (var i = 0; i < linearSamplingMap.length; i++) {
  88456. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  88457. linearSamplingWeights[i] = linearSamplingMap[i].w;
  88458. }
  88459. // Replace with optimized
  88460. offsets = linearSamplingOffsets;
  88461. weights = linearSamplingWeights;
  88462. // Generate shaders
  88463. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  88464. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  88465. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  88466. var defines = "";
  88467. defines += this._staticDefines;
  88468. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  88469. if (this._staticDefines.indexOf("DOF") != -1) {
  88470. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  88471. varyingCount--;
  88472. }
  88473. for (var i = 0; i < varyingCount; i++) {
  88474. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  88475. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  88476. }
  88477. var depCount = 0;
  88478. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  88479. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  88480. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  88481. depCount++;
  88482. }
  88483. if (this.packedFloat) {
  88484. defines += "#define PACKEDFLOAT 1";
  88485. }
  88486. this.blockCompilation = false;
  88487. _super.prototype.updateEffect.call(this, defines, null, null, {
  88488. varyingCount: varyingCount,
  88489. depCount: depCount
  88490. }, onCompiled, onError);
  88491. };
  88492. /**
  88493. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  88494. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  88495. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  88496. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  88497. * The gaps between physical kernels are compensated for in the weighting of the samples
  88498. * @param idealKernel Ideal blur kernel.
  88499. * @return Nearest best kernel.
  88500. */
  88501. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  88502. var v = Math.round(idealKernel);
  88503. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  88504. var k = _a[_i];
  88505. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  88506. return Math.max(k, 3);
  88507. }
  88508. }
  88509. return Math.max(v, 3);
  88510. };
  88511. /**
  88512. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  88513. * @param x The point on the Gaussian distribution to sample.
  88514. * @return the value of the Gaussian function at x.
  88515. */
  88516. BlurPostProcess.prototype._gaussianWeight = function (x) {
  88517. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  88518. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  88519. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  88520. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  88521. // truncated at around 1.3% of peak strength.
  88522. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  88523. var sigma = (1 / 3);
  88524. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  88525. var exponent = -((x * x) / (2.0 * sigma * sigma));
  88526. var weight = (1.0 / denominator) * Math.exp(exponent);
  88527. return weight;
  88528. };
  88529. /**
  88530. * Generates a string that can be used as a floating point number in GLSL.
  88531. * @param x Value to print.
  88532. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  88533. * @return GLSL float string.
  88534. */
  88535. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  88536. if (decimalFigures === void 0) { decimalFigures = 8; }
  88537. return x.toFixed(decimalFigures).replace(/0+$/, '');
  88538. };
  88539. return BlurPostProcess;
  88540. }(BABYLON.PostProcess));
  88541. BABYLON.BlurPostProcess = BlurPostProcess;
  88542. })(BABYLON || (BABYLON = {}));
  88543. //# sourceMappingURL=babylon.blurPostProcess.js.map
  88544. var BABYLON;
  88545. (function (BABYLON) {
  88546. /**
  88547. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  88548. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  88549. * based on samples that have a large difference in distance than the center pixel.
  88550. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  88551. */
  88552. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  88553. __extends(DepthOfFieldBlurPostProcess, _super);
  88554. /**
  88555. * Creates a new instance CircleOfConfusionPostProcess
  88556. * @param name The name of the effect.
  88557. * @param scene The scene the effect belongs to.
  88558. * @param direction The direction the blur should be applied.
  88559. * @param kernel The size of the kernel used to blur.
  88560. * @param options The required width/height ratio to downsize to before computing the render pass.
  88561. * @param camera The camera to apply the render pass to.
  88562. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  88563. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  88564. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  88565. * @param engine The engine which the post process will be applied. (default: current engine)
  88566. * @param reusable If the post process can be reused on the same frame. (default: false)
  88567. * @param textureType Type of textures used when performing the post process. (default: 0)
  88568. * @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)
  88569. */
  88570. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  88571. if (imageToBlur === void 0) { imageToBlur = null; }
  88572. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  88573. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  88574. if (blockCompilation === void 0) { blockCompilation = false; }
  88575. 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;
  88576. _this.direction = direction;
  88577. _this.onApplyObservable.add(function (effect) {
  88578. if (imageToBlur != null) {
  88579. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  88580. }
  88581. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  88582. if (scene.activeCamera) {
  88583. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  88584. }
  88585. });
  88586. return _this;
  88587. }
  88588. return DepthOfFieldBlurPostProcess;
  88589. }(BABYLON.BlurPostProcess));
  88590. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  88591. })(BABYLON || (BABYLON = {}));
  88592. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  88593. var BABYLON;
  88594. (function (BABYLON) {
  88595. /**
  88596. * Options to be set when merging outputs from the default pipeline.
  88597. */
  88598. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  88599. function DepthOfFieldMergePostProcessOptions() {
  88600. }
  88601. return DepthOfFieldMergePostProcessOptions;
  88602. }());
  88603. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  88604. /**
  88605. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  88606. */
  88607. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  88608. __extends(DepthOfFieldMergePostProcess, _super);
  88609. /**
  88610. * Creates a new instance of DepthOfFieldMergePostProcess
  88611. * @param name The name of the effect.
  88612. * @param originalFromInput Post process which's input will be used for the merge.
  88613. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  88614. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  88615. * @param options The required width/height ratio to downsize to before computing the render pass.
  88616. * @param camera The camera to apply the render pass to.
  88617. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  88618. * @param engine The engine which the post process will be applied. (default: current engine)
  88619. * @param reusable If the post process can be reused on the same frame. (default: false)
  88620. * @param textureType Type of textures used when performing the post process. (default: 0)
  88621. * @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)
  88622. */
  88623. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  88624. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  88625. if (blockCompilation === void 0) { blockCompilation = false; }
  88626. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  88627. _this.blurSteps = blurSteps;
  88628. _this.onApplyObservable.add(function (effect) {
  88629. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  88630. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  88631. blurSteps.forEach(function (step, index) {
  88632. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  88633. });
  88634. });
  88635. if (!blockCompilation) {
  88636. _this.updateEffect();
  88637. }
  88638. return _this;
  88639. }
  88640. /**
  88641. * Updates the effect with the current post process compile time values and recompiles the shader.
  88642. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  88643. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  88644. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  88645. * @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
  88646. * @param onCompiled Called when the shader has been compiled.
  88647. * @param onError Called if there is an error when compiling a shader.
  88648. */
  88649. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  88650. if (defines === void 0) { defines = null; }
  88651. if (uniforms === void 0) { uniforms = null; }
  88652. if (samplers === void 0) { samplers = null; }
  88653. if (!defines) {
  88654. defines = "";
  88655. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  88656. }
  88657. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  88658. };
  88659. return DepthOfFieldMergePostProcess;
  88660. }(BABYLON.PostProcess));
  88661. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  88662. })(BABYLON || (BABYLON = {}));
  88663. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  88664. var BABYLON;
  88665. (function (BABYLON) {
  88666. /**
  88667. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  88668. */
  88669. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  88670. __extends(CircleOfConfusionPostProcess, _super);
  88671. /**
  88672. * Creates a new instance CircleOfConfusionPostProcess
  88673. * @param name The name of the effect.
  88674. * @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.
  88675. * @param options The required width/height ratio to downsize to before computing the render pass.
  88676. * @param camera The camera to apply the render pass to.
  88677. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  88678. * @param engine The engine which the post process will be applied. (default: current engine)
  88679. * @param reusable If the post process can be reused on the same frame. (default: false)
  88680. * @param textureType Type of textures used when performing the post process. (default: 0)
  88681. * @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)
  88682. */
  88683. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  88684. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  88685. if (blockCompilation === void 0) { blockCompilation = false; }
  88686. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  88687. /**
  88688. * 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.
  88689. */
  88690. _this.lensSize = 50;
  88691. /**
  88692. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  88693. */
  88694. _this.fStop = 1.4;
  88695. /**
  88696. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  88697. */
  88698. _this.focusDistance = 2000;
  88699. /**
  88700. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  88701. */
  88702. _this.focalLength = 50;
  88703. _this._depthTexture = null;
  88704. _this._depthTexture = depthTexture;
  88705. _this.onApplyObservable.add(function (effect) {
  88706. if (!_this._depthTexture) {
  88707. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  88708. return;
  88709. }
  88710. effect.setTexture("depthSampler", _this._depthTexture);
  88711. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  88712. var aperture = _this.lensSize / _this.fStop;
  88713. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  88714. effect.setFloat('focusDistance', _this.focusDistance);
  88715. effect.setFloat('cocPrecalculation', cocPrecalculation);
  88716. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  88717. });
  88718. return _this;
  88719. }
  88720. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  88721. /**
  88722. * 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.
  88723. */
  88724. set: function (value) {
  88725. this._depthTexture = value;
  88726. },
  88727. enumerable: true,
  88728. configurable: true
  88729. });
  88730. return CircleOfConfusionPostProcess;
  88731. }(BABYLON.PostProcess));
  88732. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  88733. })(BABYLON || (BABYLON = {}));
  88734. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  88735. var BABYLON;
  88736. (function (BABYLON) {
  88737. /**
  88738. * Specifies the level of max blur that should be applied when using the depth of field effect
  88739. */
  88740. var DepthOfFieldEffectBlurLevel;
  88741. (function (DepthOfFieldEffectBlurLevel) {
  88742. /**
  88743. * Subtle blur
  88744. */
  88745. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  88746. /**
  88747. * Medium blur
  88748. */
  88749. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  88750. /**
  88751. * Large blur
  88752. */
  88753. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  88754. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  88755. /**
  88756. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  88757. */
  88758. var DepthOfFieldEffect = /** @class */ (function (_super) {
  88759. __extends(DepthOfFieldEffect, _super);
  88760. /**
  88761. * Creates a new instance DepthOfFieldEffect
  88762. * @param scene The scene the effect belongs to.
  88763. * @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.
  88764. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  88765. * @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)
  88766. */
  88767. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  88768. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  88769. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  88770. if (blockCompilation === void 0) { blockCompilation = false; }
  88771. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  88772. return _this._effects;
  88773. }, true) || this;
  88774. /**
  88775. * @hidden Internal post processes in depth of field effect
  88776. */
  88777. _this._effects = [];
  88778. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  88779. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  88780. // 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)
  88781. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  88782. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  88783. _this._depthOfFieldBlurY = [];
  88784. _this._depthOfFieldBlurX = [];
  88785. var blurCount = 1;
  88786. var kernelSize = 15;
  88787. switch (blurLevel) {
  88788. case DepthOfFieldEffectBlurLevel.High: {
  88789. blurCount = 3;
  88790. kernelSize = 51;
  88791. break;
  88792. }
  88793. case DepthOfFieldEffectBlurLevel.Medium: {
  88794. blurCount = 2;
  88795. kernelSize = 31;
  88796. break;
  88797. }
  88798. default: {
  88799. kernelSize = 15;
  88800. blurCount = 1;
  88801. break;
  88802. }
  88803. }
  88804. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  88805. var ratio = 1.0;
  88806. for (var i = 0; i < blurCount; i++) {
  88807. 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);
  88808. blurY.autoClear = false;
  88809. ratio = 0.75 / Math.pow(2, i);
  88810. 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);
  88811. blurX.autoClear = false;
  88812. _this._depthOfFieldBlurY.push(blurY);
  88813. _this._depthOfFieldBlurX.push(blurX);
  88814. }
  88815. // Set all post processes on the effect.
  88816. _this._effects = [_this._circleOfConfusion];
  88817. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  88818. _this._effects.push(_this._depthOfFieldBlurY[i]);
  88819. _this._effects.push(_this._depthOfFieldBlurX[i]);
  88820. }
  88821. // Merge blurred images with original image based on circleOfConfusion
  88822. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  88823. _this._dofMerge.autoClear = false;
  88824. _this._effects.push(_this._dofMerge);
  88825. return _this;
  88826. }
  88827. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  88828. get: function () {
  88829. return this._circleOfConfusion.focalLength;
  88830. },
  88831. /**
  88832. * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
  88833. */
  88834. set: function (value) {
  88835. this._circleOfConfusion.focalLength = value;
  88836. },
  88837. enumerable: true,
  88838. configurable: true
  88839. });
  88840. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  88841. get: function () {
  88842. return this._circleOfConfusion.fStop;
  88843. },
  88844. /**
  88845. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  88846. */
  88847. set: function (value) {
  88848. this._circleOfConfusion.fStop = value;
  88849. },
  88850. enumerable: true,
  88851. configurable: true
  88852. });
  88853. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  88854. get: function () {
  88855. return this._circleOfConfusion.focusDistance;
  88856. },
  88857. /**
  88858. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  88859. */
  88860. set: function (value) {
  88861. this._circleOfConfusion.focusDistance = value;
  88862. },
  88863. enumerable: true,
  88864. configurable: true
  88865. });
  88866. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  88867. get: function () {
  88868. return this._circleOfConfusion.lensSize;
  88869. },
  88870. /**
  88871. * 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.
  88872. */
  88873. set: function (value) {
  88874. this._circleOfConfusion.lensSize = value;
  88875. },
  88876. enumerable: true,
  88877. configurable: true
  88878. });
  88879. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  88880. /**
  88881. * 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.
  88882. */
  88883. set: function (value) {
  88884. this._circleOfConfusion.depthTexture = value;
  88885. },
  88886. enumerable: true,
  88887. configurable: true
  88888. });
  88889. /**
  88890. * Disposes each of the internal effects for a given camera.
  88891. * @param camera The camera to dispose the effect on.
  88892. */
  88893. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  88894. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  88895. this._effects[effectIndex].dispose(camera);
  88896. }
  88897. };
  88898. /**
  88899. * @hidden Internal
  88900. */
  88901. DepthOfFieldEffect.prototype._updateEffects = function () {
  88902. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  88903. this._effects[effectIndex].updateEffect();
  88904. }
  88905. };
  88906. /**
  88907. * Internal
  88908. * @returns if all the contained post processes are ready.
  88909. * @hidden
  88910. */
  88911. DepthOfFieldEffect.prototype._isReady = function () {
  88912. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  88913. if (!this._effects[effectIndex].isReady()) {
  88914. return false;
  88915. }
  88916. }
  88917. return true;
  88918. };
  88919. return DepthOfFieldEffect;
  88920. }(BABYLON.PostProcessRenderEffect));
  88921. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  88922. })(BABYLON || (BABYLON = {}));
  88923. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  88924. var BABYLON;
  88925. (function (BABYLON) {
  88926. /**
  88927. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  88928. */
  88929. var BloomMergePostProcess = /** @class */ (function (_super) {
  88930. __extends(BloomMergePostProcess, _super);
  88931. /**
  88932. * Creates a new instance of @see BloomMergePostProcess
  88933. * @param name The name of the effect.
  88934. * @param originalFromInput Post process which's input will be used for the merge.
  88935. * @param blurred Blurred highlights post process which's output will be used.
  88936. * @param weight Weight of the bloom to be added to the original input.
  88937. * @param options The required width/height ratio to downsize to before computing the render pass.
  88938. * @param camera The camera to apply the render pass to.
  88939. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  88940. * @param engine The engine which the post process will be applied. (default: current engine)
  88941. * @param reusable If the post process can be reused on the same frame. (default: false)
  88942. * @param textureType Type of textures used when performing the post process. (default: 0)
  88943. * @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)
  88944. */
  88945. function BloomMergePostProcess(name, originalFromInput, blurred,
  88946. /** Weight of the bloom to be added to the original input. */
  88947. weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  88948. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  88949. if (blockCompilation === void 0) { blockCompilation = false; }
  88950. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  88951. _this.weight = weight;
  88952. _this.onApplyObservable.add(function (effect) {
  88953. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  88954. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  88955. effect.setFloat("bloomWeight", _this.weight);
  88956. });
  88957. if (!blockCompilation) {
  88958. _this.updateEffect();
  88959. }
  88960. return _this;
  88961. }
  88962. return BloomMergePostProcess;
  88963. }(BABYLON.PostProcess));
  88964. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  88965. })(BABYLON || (BABYLON = {}));
  88966. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  88967. var BABYLON;
  88968. (function (BABYLON) {
  88969. /**
  88970. * 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.
  88971. */
  88972. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  88973. __extends(ExtractHighlightsPostProcess, _super);
  88974. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  88975. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  88976. if (blockCompilation === void 0) { blockCompilation = false; }
  88977. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  88978. /**
  88979. * The luminance threshold, pixels below this value will be set to black.
  88980. */
  88981. _this.threshold = 0.9;
  88982. /** @hidden */
  88983. _this._exposure = 1;
  88984. /**
  88985. * Post process which has the input texture to be used when performing highlight extraction
  88986. * @hidden
  88987. */
  88988. _this._inputPostProcess = null;
  88989. _this.onApplyObservable.add(function (effect) {
  88990. if (_this._inputPostProcess) {
  88991. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  88992. }
  88993. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  88994. effect.setFloat('exposure', _this._exposure);
  88995. });
  88996. return _this;
  88997. }
  88998. return ExtractHighlightsPostProcess;
  88999. }(BABYLON.PostProcess));
  89000. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  89001. })(BABYLON || (BABYLON = {}));
  89002. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  89003. var BABYLON;
  89004. (function (BABYLON) {
  89005. /**
  89006. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  89007. */
  89008. var BloomEffect = /** @class */ (function (_super) {
  89009. __extends(BloomEffect, _super);
  89010. /**
  89011. * Creates a new instance of @see BloomEffect
  89012. * @param scene The scene the effect belongs to.
  89013. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  89014. * @param bloomKernel The size of the kernel to be used when applying the blur.
  89015. * @param bloomWeight The the strength of bloom.
  89016. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  89017. * @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)
  89018. */
  89019. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  89020. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  89021. if (blockCompilation === void 0) { blockCompilation = false; }
  89022. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  89023. return _this._effects;
  89024. }, true) || this;
  89025. _this.bloomScale = bloomScale;
  89026. /**
  89027. * @hidden Internal
  89028. */
  89029. _this._effects = [];
  89030. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  89031. _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);
  89032. _this._blurX.alwaysForcePOT = true;
  89033. _this._blurX.autoClear = false;
  89034. _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);
  89035. _this._blurY.alwaysForcePOT = true;
  89036. _this._blurY.autoClear = false;
  89037. _this.kernel = bloomKernel;
  89038. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  89039. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  89040. _this._merge.autoClear = false;
  89041. _this._effects.push(_this._merge);
  89042. return _this;
  89043. }
  89044. Object.defineProperty(BloomEffect.prototype, "threshold", {
  89045. /**
  89046. * The luminance threshold to find bright areas of the image to bloom.
  89047. */
  89048. get: function () {
  89049. return this._downscale.threshold;
  89050. },
  89051. set: function (value) {
  89052. this._downscale.threshold = value;
  89053. },
  89054. enumerable: true,
  89055. configurable: true
  89056. });
  89057. Object.defineProperty(BloomEffect.prototype, "weight", {
  89058. /**
  89059. * The strength of the bloom.
  89060. */
  89061. get: function () {
  89062. return this._merge.weight;
  89063. },
  89064. set: function (value) {
  89065. this._merge.weight = value;
  89066. },
  89067. enumerable: true,
  89068. configurable: true
  89069. });
  89070. Object.defineProperty(BloomEffect.prototype, "kernel", {
  89071. /**
  89072. * Specifies the size of the bloom blur kernel, relative to the final output size
  89073. */
  89074. get: function () {
  89075. return this._blurX.kernel / this.bloomScale;
  89076. },
  89077. set: function (value) {
  89078. this._blurX.kernel = value * this.bloomScale;
  89079. this._blurY.kernel = value * this.bloomScale;
  89080. },
  89081. enumerable: true,
  89082. configurable: true
  89083. });
  89084. /**
  89085. * Disposes each of the internal effects for a given camera.
  89086. * @param camera The camera to dispose the effect on.
  89087. */
  89088. BloomEffect.prototype.disposeEffects = function (camera) {
  89089. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  89090. this._effects[effectIndex].dispose(camera);
  89091. }
  89092. };
  89093. /**
  89094. * @hidden Internal
  89095. */
  89096. BloomEffect.prototype._updateEffects = function () {
  89097. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  89098. this._effects[effectIndex].updateEffect();
  89099. }
  89100. };
  89101. /**
  89102. * Internal
  89103. * @returns if all the contained post processes are ready.
  89104. * @hidden
  89105. */
  89106. BloomEffect.prototype._isReady = function () {
  89107. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  89108. if (!this._effects[effectIndex].isReady()) {
  89109. return false;
  89110. }
  89111. }
  89112. return true;
  89113. };
  89114. return BloomEffect;
  89115. }(BABYLON.PostProcessRenderEffect));
  89116. BABYLON.BloomEffect = BloomEffect;
  89117. })(BABYLON || (BABYLON = {}));
  89118. //# sourceMappingURL=babylon.bloomEffect.js.map
  89119. var BABYLON;
  89120. (function (BABYLON) {
  89121. /**
  89122. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  89123. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  89124. */
  89125. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  89126. __extends(DefaultRenderingPipeline, _super);
  89127. /**
  89128. * @constructor
  89129. * @param name - The rendering pipeline name (default: "")
  89130. * @param hdr - If high dynamic range textures should be used (default: true)
  89131. * @param scene - The scene linked to this pipeline (default: the last created scene)
  89132. * @param cameras - The array of cameras that the rendering pipeline will be attached to (default: scene.cameras)
  89133. * @param automaticBuild - if false, you will have to manually call prepare() to update the pipeline (default: true)
  89134. */
  89135. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  89136. if (name === void 0) { name = ""; }
  89137. if (hdr === void 0) { hdr = true; }
  89138. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  89139. if (automaticBuild === void 0) { automaticBuild = true; }
  89140. var _this = _super.call(this, scene.getEngine(), name) || this;
  89141. _this._camerasToBeAttached = [];
  89142. /**
  89143. * ID of the sharpen post process,
  89144. */
  89145. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  89146. /**
  89147. * @ignore
  89148. * ID of the image processing post process;
  89149. */
  89150. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  89151. /**
  89152. * @ignore
  89153. * ID of the Fast Approximate Anti-Aliasing post process;
  89154. */
  89155. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  89156. /**
  89157. * ID of the chromatic aberration post process,
  89158. */
  89159. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  89160. /**
  89161. * ID of the grain post process
  89162. */
  89163. _this.GrainPostProcessId = "GrainPostProcessEffect";
  89164. /**
  89165. * Glow post process which adds a glow to emmisive areas of the image
  89166. */
  89167. _this._glowLayer = null;
  89168. /**
  89169. * Animations which can be used to tweak settings over a period of time
  89170. */
  89171. _this.animations = [];
  89172. _this._imageProcessingConfigurationObserver = null;
  89173. // Values
  89174. _this._sharpenEnabled = false;
  89175. _this._bloomEnabled = false;
  89176. _this._depthOfFieldEnabled = false;
  89177. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  89178. _this._fxaaEnabled = false;
  89179. _this._imageProcessingEnabled = true;
  89180. _this._bloomScale = 0.5;
  89181. _this._chromaticAberrationEnabled = false;
  89182. _this._grainEnabled = false;
  89183. _this._buildAllowed = true;
  89184. _this._resizeObserver = null;
  89185. _this._hardwareScaleLevel = 1.0;
  89186. _this._bloomKernel = 64;
  89187. /**
  89188. * Specifies the weight of the bloom in the final rendering
  89189. */
  89190. _this._bloomWeight = 0.15;
  89191. /**
  89192. * Specifies the luma threshold for the area that will be blurred by the bloom
  89193. */
  89194. _this._bloomThreshold = 0.9;
  89195. _this._samples = 1;
  89196. _this._hasCleared = false;
  89197. _this._prevPostProcess = null;
  89198. _this._prevPrevPostProcess = null;
  89199. _this._depthOfFieldSceneObserver = null;
  89200. _this._cameras = cameras || scene.cameras;
  89201. _this._cameras = _this._cameras.slice();
  89202. _this._camerasToBeAttached = _this._cameras.slice();
  89203. _this._buildAllowed = automaticBuild;
  89204. // Initialize
  89205. _this._scene = scene;
  89206. var caps = _this._scene.getEngine().getCaps();
  89207. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  89208. // Misc
  89209. if (_this._hdr) {
  89210. if (caps.textureHalfFloatRender) {
  89211. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  89212. }
  89213. else if (caps.textureFloatRender) {
  89214. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  89215. }
  89216. }
  89217. else {
  89218. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  89219. }
  89220. // Attach
  89221. scene.postProcessRenderPipelineManager.addPipeline(_this);
  89222. var engine = _this._scene.getEngine();
  89223. // Create post processes before hand so they can be modified before enabled.
  89224. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  89225. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  89226. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  89227. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  89228. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  89229. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  89230. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  89231. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  89232. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  89233. _this._resizeObserver = engine.onResizeObservable.add(function () {
  89234. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  89235. _this.bloomKernel = _this.bloomKernel;
  89236. });
  89237. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  89238. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  89239. });
  89240. _this._buildPipeline();
  89241. return _this;
  89242. }
  89243. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  89244. get: function () {
  89245. return this._sharpenEnabled;
  89246. },
  89247. /**
  89248. * Enable or disable the sharpen process from the pipeline
  89249. */
  89250. set: function (enabled) {
  89251. if (this._sharpenEnabled === enabled) {
  89252. return;
  89253. }
  89254. this._sharpenEnabled = enabled;
  89255. this._buildPipeline();
  89256. },
  89257. enumerable: true,
  89258. configurable: true
  89259. });
  89260. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  89261. /**
  89262. * Specifies the size of the bloom blur kernel, relative to the final output size
  89263. */
  89264. get: function () {
  89265. return this._bloomKernel;
  89266. },
  89267. set: function (value) {
  89268. this._bloomKernel = value;
  89269. this.bloom.kernel = value / this._hardwareScaleLevel;
  89270. },
  89271. enumerable: true,
  89272. configurable: true
  89273. });
  89274. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  89275. get: function () {
  89276. return this._bloomWeight;
  89277. },
  89278. /**
  89279. * The strength of the bloom.
  89280. */
  89281. set: function (value) {
  89282. if (this._bloomWeight === value) {
  89283. return;
  89284. }
  89285. this.bloom.weight = value;
  89286. this._bloomWeight = value;
  89287. },
  89288. enumerable: true,
  89289. configurable: true
  89290. });
  89291. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  89292. get: function () {
  89293. return this._bloomThreshold;
  89294. },
  89295. /**
  89296. * The strength of the bloom.
  89297. */
  89298. set: function (value) {
  89299. if (this._bloomThreshold === value) {
  89300. return;
  89301. }
  89302. this.bloom.threshold = value;
  89303. this._bloomThreshold = value;
  89304. },
  89305. enumerable: true,
  89306. configurable: true
  89307. });
  89308. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  89309. get: function () {
  89310. return this._bloomScale;
  89311. },
  89312. /**
  89313. * The scale of the bloom, lower value will provide better performance.
  89314. */
  89315. set: function (value) {
  89316. if (this._bloomScale === value) {
  89317. return;
  89318. }
  89319. this._bloomScale = value;
  89320. // recreate bloom and dispose old as this setting is not dynamic
  89321. this._rebuildBloom();
  89322. this._buildPipeline();
  89323. },
  89324. enumerable: true,
  89325. configurable: true
  89326. });
  89327. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  89328. get: function () {
  89329. return this._bloomEnabled;
  89330. },
  89331. /**
  89332. * Enable or disable the bloom from the pipeline
  89333. */
  89334. set: function (enabled) {
  89335. if (this._bloomEnabled === enabled) {
  89336. return;
  89337. }
  89338. this._bloomEnabled = enabled;
  89339. this._buildPipeline();
  89340. },
  89341. enumerable: true,
  89342. configurable: true
  89343. });
  89344. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  89345. // recreate bloom and dispose old as this setting is not dynamic
  89346. var oldBloom = this.bloom;
  89347. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  89348. this.bloom.threshold = oldBloom.threshold;
  89349. for (var i = 0; i < this._cameras.length; i++) {
  89350. oldBloom.disposeEffects(this._cameras[i]);
  89351. }
  89352. };
  89353. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  89354. /**
  89355. * If the depth of field is enabled.
  89356. */
  89357. get: function () {
  89358. return this._depthOfFieldEnabled;
  89359. },
  89360. set: function (enabled) {
  89361. if (this._depthOfFieldEnabled === enabled) {
  89362. return;
  89363. }
  89364. this._depthOfFieldEnabled = enabled;
  89365. this._buildPipeline();
  89366. },
  89367. enumerable: true,
  89368. configurable: true
  89369. });
  89370. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  89371. /**
  89372. * Blur level of the depth of field effect. (Higher blur will effect performance)
  89373. */
  89374. get: function () {
  89375. return this._depthOfFieldBlurLevel;
  89376. },
  89377. set: function (value) {
  89378. if (this._depthOfFieldBlurLevel === value) {
  89379. return;
  89380. }
  89381. this._depthOfFieldBlurLevel = value;
  89382. // recreate dof and dispose old as this setting is not dynamic
  89383. var oldDof = this.depthOfField;
  89384. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  89385. this.depthOfField.focalLength = oldDof.focalLength;
  89386. this.depthOfField.focusDistance = oldDof.focusDistance;
  89387. this.depthOfField.fStop = oldDof.fStop;
  89388. this.depthOfField.lensSize = oldDof.lensSize;
  89389. for (var i = 0; i < this._cameras.length; i++) {
  89390. oldDof.disposeEffects(this._cameras[i]);
  89391. }
  89392. this._buildPipeline();
  89393. },
  89394. enumerable: true,
  89395. configurable: true
  89396. });
  89397. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  89398. get: function () {
  89399. return this._fxaaEnabled;
  89400. },
  89401. /**
  89402. * If the anti aliasing is enabled.
  89403. */
  89404. set: function (enabled) {
  89405. if (this._fxaaEnabled === enabled) {
  89406. return;
  89407. }
  89408. this._fxaaEnabled = enabled;
  89409. this._buildPipeline();
  89410. },
  89411. enumerable: true,
  89412. configurable: true
  89413. });
  89414. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  89415. get: function () {
  89416. return this._samples;
  89417. },
  89418. /**
  89419. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  89420. */
  89421. set: function (sampleCount) {
  89422. if (this._samples === sampleCount) {
  89423. return;
  89424. }
  89425. this._samples = sampleCount;
  89426. this._buildPipeline();
  89427. },
  89428. enumerable: true,
  89429. configurable: true
  89430. });
  89431. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  89432. get: function () {
  89433. return this._imageProcessingEnabled;
  89434. },
  89435. /**
  89436. * If image processing is enabled.
  89437. */
  89438. set: function (enabled) {
  89439. if (this._imageProcessingEnabled === enabled) {
  89440. return;
  89441. }
  89442. this._imageProcessingEnabled = enabled;
  89443. this._buildPipeline();
  89444. },
  89445. enumerable: true,
  89446. configurable: true
  89447. });
  89448. Object.defineProperty(DefaultRenderingPipeline.prototype, "glowLayerEnabled", {
  89449. get: function () {
  89450. return this._glowLayer == null;
  89451. },
  89452. /**
  89453. * If glow layer is enabled. (Adds a glow effect to emmissive materials)
  89454. */
  89455. set: function (enabled) {
  89456. if (enabled && !this._glowLayer) {
  89457. this._glowLayer = new BABYLON.GlowLayer("", this._scene);
  89458. }
  89459. else if (!enabled && this._glowLayer) {
  89460. this._glowLayer.dispose();
  89461. this._glowLayer = null;
  89462. }
  89463. },
  89464. enumerable: true,
  89465. configurable: true
  89466. });
  89467. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  89468. get: function () {
  89469. return this._chromaticAberrationEnabled;
  89470. },
  89471. /**
  89472. * Enable or disable the chromaticAberration process from the pipeline
  89473. */
  89474. set: function (enabled) {
  89475. if (this._chromaticAberrationEnabled === enabled) {
  89476. return;
  89477. }
  89478. this._chromaticAberrationEnabled = enabled;
  89479. this._buildPipeline();
  89480. },
  89481. enumerable: true,
  89482. configurable: true
  89483. });
  89484. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  89485. get: function () {
  89486. return this._grainEnabled;
  89487. },
  89488. /**
  89489. * Enable or disable the grain process from the pipeline
  89490. */
  89491. set: function (enabled) {
  89492. if (this._grainEnabled === enabled) {
  89493. return;
  89494. }
  89495. this._grainEnabled = enabled;
  89496. this._buildPipeline();
  89497. },
  89498. enumerable: true,
  89499. configurable: true
  89500. });
  89501. /**
  89502. * Force the compilation of the entire pipeline.
  89503. */
  89504. DefaultRenderingPipeline.prototype.prepare = function () {
  89505. var previousState = this._buildAllowed;
  89506. this._buildAllowed = true;
  89507. this._buildPipeline();
  89508. this._buildAllowed = previousState;
  89509. };
  89510. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  89511. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  89512. if (this._hasCleared) {
  89513. postProcess.autoClear = false;
  89514. }
  89515. else {
  89516. postProcess.autoClear = true;
  89517. this._scene.autoClear = false;
  89518. this._hasCleared = true;
  89519. }
  89520. if (!skipTextureSharing) {
  89521. if (this._prevPrevPostProcess) {
  89522. postProcess.shareOutputWith(this._prevPrevPostProcess);
  89523. }
  89524. else {
  89525. postProcess.useOwnOutput();
  89526. }
  89527. if (this._prevPostProcess) {
  89528. this._prevPrevPostProcess = this._prevPostProcess;
  89529. }
  89530. this._prevPostProcess = postProcess;
  89531. }
  89532. };
  89533. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  89534. var _this = this;
  89535. if (!this._buildAllowed) {
  89536. return;
  89537. }
  89538. this._scene.autoClear = true;
  89539. var engine = this._scene.getEngine();
  89540. this._disposePostProcesses();
  89541. if (this._cameras !== null) {
  89542. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  89543. // get back cameras to be used to reattach pipeline
  89544. this._cameras = this._camerasToBeAttached.slice();
  89545. }
  89546. this._reset();
  89547. this._prevPostProcess = null;
  89548. this._prevPrevPostProcess = null;
  89549. this._hasCleared = false;
  89550. if (this.depthOfFieldEnabled) {
  89551. // Multi camera suport
  89552. if (this._cameras.length > 1) {
  89553. for (var _i = 0, _a = this._cameras; _i < _a.length; _i++) {
  89554. var camera = _a[_i];
  89555. var depthRenderer = this._scene.enableDepthRenderer(camera);
  89556. depthRenderer.useOnlyInActiveCamera = true;
  89557. }
  89558. this._depthOfFieldSceneObserver = this._scene.onAfterRenderTargetsRenderObservable.add(function (scene) {
  89559. if (_this._cameras.indexOf(scene.activeCamera) > -1) {
  89560. _this.depthOfField.depthTexture = scene.enableDepthRenderer(scene.activeCamera).getDepthMap();
  89561. }
  89562. });
  89563. }
  89564. else {
  89565. this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);
  89566. var depthRenderer = this._scene.enableDepthRenderer(this._cameras[0]);
  89567. this.depthOfField.depthTexture = depthRenderer.getDepthMap();
  89568. }
  89569. if (!this.depthOfField._isReady()) {
  89570. this.depthOfField._updateEffects();
  89571. }
  89572. this.addEffect(this.depthOfField);
  89573. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  89574. }
  89575. else {
  89576. this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);
  89577. }
  89578. if (this.bloomEnabled) {
  89579. if (!this.bloom._isReady()) {
  89580. this.bloom._updateEffects();
  89581. }
  89582. this.addEffect(this.bloom);
  89583. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  89584. }
  89585. if (this._imageProcessingEnabled) {
  89586. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  89587. if (this._hdr) {
  89588. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  89589. this._setAutoClearAndTextureSharing(this.imageProcessing);
  89590. }
  89591. else {
  89592. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  89593. }
  89594. }
  89595. if (this.sharpenEnabled) {
  89596. if (!this.sharpen.isReady()) {
  89597. this.sharpen.updateEffect();
  89598. }
  89599. this.addEffect(this._sharpenEffect);
  89600. this._setAutoClearAndTextureSharing(this.sharpen);
  89601. }
  89602. if (this.grainEnabled) {
  89603. if (!this.grain.isReady()) {
  89604. this.grain.updateEffect();
  89605. }
  89606. this.addEffect(this._grainEffect);
  89607. this._setAutoClearAndTextureSharing(this.grain);
  89608. }
  89609. if (this.chromaticAberrationEnabled) {
  89610. if (!this.chromaticAberration.isReady()) {
  89611. this.chromaticAberration.updateEffect();
  89612. }
  89613. this.addEffect(this._chromaticAberrationEffect);
  89614. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  89615. }
  89616. if (this.fxaaEnabled) {
  89617. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  89618. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  89619. this._setAutoClearAndTextureSharing(this.fxaa, true);
  89620. }
  89621. if (this._cameras !== null) {
  89622. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  89623. }
  89624. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  89625. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  89626. }
  89627. };
  89628. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  89629. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  89630. for (var i = 0; i < this._cameras.length; i++) {
  89631. var camera = this._cameras[i];
  89632. if (this.imageProcessing) {
  89633. this.imageProcessing.dispose(camera);
  89634. }
  89635. if (this.fxaa) {
  89636. this.fxaa.dispose(camera);
  89637. }
  89638. // These are created in the constructor and should not be disposed on every pipeline change
  89639. if (disposeNonRecreated) {
  89640. if (this.sharpen) {
  89641. this.sharpen.dispose(camera);
  89642. }
  89643. if (this.depthOfField) {
  89644. this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);
  89645. this.depthOfField.disposeEffects(camera);
  89646. }
  89647. if (this.bloom) {
  89648. this.bloom.disposeEffects(camera);
  89649. }
  89650. if (this.chromaticAberration) {
  89651. this.chromaticAberration.dispose(camera);
  89652. }
  89653. if (this.grain) {
  89654. this.grain.dispose(camera);
  89655. }
  89656. if (this._glowLayer) {
  89657. this._glowLayer.dispose();
  89658. }
  89659. }
  89660. }
  89661. this.imageProcessing = null;
  89662. this.fxaa = null;
  89663. if (disposeNonRecreated) {
  89664. this.sharpen = null;
  89665. this._sharpenEffect = null;
  89666. this.depthOfField = null;
  89667. this.bloom = null;
  89668. this.chromaticAberration = null;
  89669. this._chromaticAberrationEffect = null;
  89670. this.grain = null;
  89671. this._grainEffect = null;
  89672. this._glowLayer = null;
  89673. }
  89674. };
  89675. /**
  89676. * Adds a camera to the pipeline
  89677. * @param camera the camera to be added
  89678. */
  89679. DefaultRenderingPipeline.prototype.addCamera = function (camera) {
  89680. this._camerasToBeAttached.push(camera);
  89681. this._buildPipeline();
  89682. };
  89683. /**
  89684. * Removes a camera from the pipeline
  89685. * @param camera the camera to remove
  89686. */
  89687. DefaultRenderingPipeline.prototype.removeCamera = function (camera) {
  89688. var index = this._camerasToBeAttached.indexOf(camera);
  89689. this._camerasToBeAttached.splice(index, 1);
  89690. this._buildPipeline();
  89691. };
  89692. /**
  89693. * Dispose of the pipeline and stop all post processes
  89694. */
  89695. DefaultRenderingPipeline.prototype.dispose = function () {
  89696. this._disposePostProcesses(true);
  89697. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  89698. this._scene.autoClear = true;
  89699. if (this._resizeObserver) {
  89700. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  89701. this._resizeObserver = null;
  89702. }
  89703. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  89704. _super.prototype.dispose.call(this);
  89705. };
  89706. /**
  89707. * Serialize the rendering pipeline (Used when exporting)
  89708. * @returns the serialized object
  89709. */
  89710. DefaultRenderingPipeline.prototype.serialize = function () {
  89711. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  89712. serializationObject.customType = "DefaultRenderingPipeline";
  89713. return serializationObject;
  89714. };
  89715. /**
  89716. * Parse the serialized pipeline
  89717. * @param source Source pipeline.
  89718. * @param scene The scene to load the pipeline to.
  89719. * @param rootUrl The URL of the serialized pipeline.
  89720. * @returns An instantiated pipeline from the serialized object.
  89721. */
  89722. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  89723. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  89724. };
  89725. __decorate([
  89726. BABYLON.serialize()
  89727. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  89728. __decorate([
  89729. BABYLON.serialize()
  89730. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  89731. __decorate([
  89732. BABYLON.serialize()
  89733. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  89734. __decorate([
  89735. BABYLON.serialize()
  89736. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  89737. __decorate([
  89738. BABYLON.serialize()
  89739. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  89740. __decorate([
  89741. BABYLON.serialize()
  89742. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  89743. __decorate([
  89744. BABYLON.serialize()
  89745. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  89746. __decorate([
  89747. BABYLON.serialize()
  89748. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  89749. __decorate([
  89750. BABYLON.serialize()
  89751. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  89752. __decorate([
  89753. BABYLON.serialize()
  89754. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  89755. __decorate([
  89756. BABYLON.serialize()
  89757. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  89758. __decorate([
  89759. BABYLON.serialize()
  89760. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  89761. __decorate([
  89762. BABYLON.serialize()
  89763. ], DefaultRenderingPipeline.prototype, "samples", null);
  89764. __decorate([
  89765. BABYLON.serialize()
  89766. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  89767. __decorate([
  89768. BABYLON.serialize()
  89769. ], DefaultRenderingPipeline.prototype, "glowLayerEnabled", null);
  89770. __decorate([
  89771. BABYLON.serialize()
  89772. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  89773. __decorate([
  89774. BABYLON.serialize()
  89775. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  89776. return DefaultRenderingPipeline;
  89777. }(BABYLON.PostProcessRenderPipeline));
  89778. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  89779. })(BABYLON || (BABYLON = {}));
  89780. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  89781. var BABYLON;
  89782. (function (BABYLON) {
  89783. /**
  89784. * @hidden
  89785. */
  89786. var ImageProcessingConfigurationDefines = /** @class */ (function (_super) {
  89787. __extends(ImageProcessingConfigurationDefines, _super);
  89788. function ImageProcessingConfigurationDefines() {
  89789. var _this = _super.call(this) || this;
  89790. _this.IMAGEPROCESSING = false;
  89791. _this.VIGNETTE = false;
  89792. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  89793. _this.VIGNETTEBLENDMODEOPAQUE = false;
  89794. _this.TONEMAPPING = false;
  89795. _this.TONEMAPPING_ACES = false;
  89796. _this.CONTRAST = false;
  89797. _this.COLORCURVES = false;
  89798. _this.COLORGRADING = false;
  89799. _this.COLORGRADING3D = false;
  89800. _this.SAMPLER3DGREENDEPTH = false;
  89801. _this.SAMPLER3DBGRMAP = false;
  89802. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  89803. _this.EXPOSURE = false;
  89804. _this.rebuild();
  89805. return _this;
  89806. }
  89807. return ImageProcessingConfigurationDefines;
  89808. }(BABYLON.MaterialDefines));
  89809. BABYLON.ImageProcessingConfigurationDefines = ImageProcessingConfigurationDefines;
  89810. /**
  89811. * This groups together the common properties used for image processing either in direct forward pass
  89812. * or through post processing effect depending on the use of the image processing pipeline in your scene
  89813. * or not.
  89814. */
  89815. var ImageProcessingConfiguration = /** @class */ (function () {
  89816. function ImageProcessingConfiguration() {
  89817. /**
  89818. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  89819. */
  89820. this.colorCurves = new BABYLON.ColorCurves();
  89821. this._colorCurvesEnabled = false;
  89822. this._colorGradingEnabled = false;
  89823. this._colorGradingWithGreenDepth = true;
  89824. this._colorGradingBGR = true;
  89825. /** @hidden */
  89826. this._exposure = 1.0;
  89827. this._toneMappingEnabled = false;
  89828. this._toneMappingType = ImageProcessingConfiguration.TONEMAPPING_STANDARD;
  89829. this._contrast = 1.0;
  89830. /**
  89831. * Vignette stretch size.
  89832. */
  89833. this.vignetteStretch = 0;
  89834. /**
  89835. * Vignette centre X Offset.
  89836. */
  89837. this.vignetteCentreX = 0;
  89838. /**
  89839. * Vignette centre Y Offset.
  89840. */
  89841. this.vignetteCentreY = 0;
  89842. /**
  89843. * Vignette weight or intensity of the vignette effect.
  89844. */
  89845. this.vignetteWeight = 1.5;
  89846. /**
  89847. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  89848. * if vignetteEnabled is set to true.
  89849. */
  89850. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  89851. /**
  89852. * Camera field of view used by the Vignette effect.
  89853. */
  89854. this.vignetteCameraFov = 0.5;
  89855. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  89856. this._vignetteEnabled = false;
  89857. this._applyByPostProcess = false;
  89858. this._isEnabled = true;
  89859. /**
  89860. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  89861. */
  89862. this.onUpdateParameters = new BABYLON.Observable();
  89863. }
  89864. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  89865. /**
  89866. * Gets wether the color curves effect is enabled.
  89867. */
  89868. get: function () {
  89869. return this._colorCurvesEnabled;
  89870. },
  89871. /**
  89872. * Sets wether the color curves effect is enabled.
  89873. */
  89874. set: function (value) {
  89875. if (this._colorCurvesEnabled === value) {
  89876. return;
  89877. }
  89878. this._colorCurvesEnabled = value;
  89879. this._updateParameters();
  89880. },
  89881. enumerable: true,
  89882. configurable: true
  89883. });
  89884. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingTexture", {
  89885. /**
  89886. * Color grading LUT texture used in the effect if colorGradingEnabled is set to true
  89887. */
  89888. get: function () {
  89889. return this._colorGradingTexture;
  89890. },
  89891. /**
  89892. * Color grading LUT texture used in the effect if colorGradingEnabled is set to true
  89893. */
  89894. set: function (value) {
  89895. if (this._colorGradingTexture === value) {
  89896. return;
  89897. }
  89898. this._colorGradingTexture = value;
  89899. this._updateParameters();
  89900. },
  89901. enumerable: true,
  89902. configurable: true
  89903. });
  89904. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  89905. /**
  89906. * Gets wether the color grading effect is enabled.
  89907. */
  89908. get: function () {
  89909. return this._colorGradingEnabled;
  89910. },
  89911. /**
  89912. * Sets wether the color grading effect is enabled.
  89913. */
  89914. set: function (value) {
  89915. if (this._colorGradingEnabled === value) {
  89916. return;
  89917. }
  89918. this._colorGradingEnabled = value;
  89919. this._updateParameters();
  89920. },
  89921. enumerable: true,
  89922. configurable: true
  89923. });
  89924. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  89925. /**
  89926. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  89927. */
  89928. get: function () {
  89929. return this._colorGradingWithGreenDepth;
  89930. },
  89931. /**
  89932. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  89933. */
  89934. set: function (value) {
  89935. if (this._colorGradingWithGreenDepth === value) {
  89936. return;
  89937. }
  89938. this._colorGradingWithGreenDepth = value;
  89939. this._updateParameters();
  89940. },
  89941. enumerable: true,
  89942. configurable: true
  89943. });
  89944. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  89945. /**
  89946. * Gets wether the color grading texture contains BGR values.
  89947. */
  89948. get: function () {
  89949. return this._colorGradingBGR;
  89950. },
  89951. /**
  89952. * Sets wether the color grading texture contains BGR values.
  89953. */
  89954. set: function (value) {
  89955. if (this._colorGradingBGR === value) {
  89956. return;
  89957. }
  89958. this._colorGradingBGR = value;
  89959. this._updateParameters();
  89960. },
  89961. enumerable: true,
  89962. configurable: true
  89963. });
  89964. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  89965. /**
  89966. * Gets the Exposure used in the effect.
  89967. */
  89968. get: function () {
  89969. return this._exposure;
  89970. },
  89971. /**
  89972. * Sets the Exposure used in the effect.
  89973. */
  89974. set: function (value) {
  89975. if (this._exposure === value) {
  89976. return;
  89977. }
  89978. this._exposure = value;
  89979. this._updateParameters();
  89980. },
  89981. enumerable: true,
  89982. configurable: true
  89983. });
  89984. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  89985. /**
  89986. * Gets wether the tone mapping effect is enabled.
  89987. */
  89988. get: function () {
  89989. return this._toneMappingEnabled;
  89990. },
  89991. /**
  89992. * Sets wether the tone mapping effect is enabled.
  89993. */
  89994. set: function (value) {
  89995. if (this._toneMappingEnabled === value) {
  89996. return;
  89997. }
  89998. this._toneMappingEnabled = value;
  89999. this._updateParameters();
  90000. },
  90001. enumerable: true,
  90002. configurable: true
  90003. });
  90004. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingType", {
  90005. /**
  90006. * Gets the type of tone mapping effect.
  90007. */
  90008. get: function () {
  90009. return this._toneMappingType;
  90010. },
  90011. /**
  90012. * Sets the type of tone mapping effect used in BabylonJS.
  90013. */
  90014. set: function (value) {
  90015. if (this._toneMappingType === value) {
  90016. return;
  90017. }
  90018. this._toneMappingType = value;
  90019. this._updateParameters();
  90020. },
  90021. enumerable: true,
  90022. configurable: true
  90023. });
  90024. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  90025. /**
  90026. * Gets the contrast used in the effect.
  90027. */
  90028. get: function () {
  90029. return this._contrast;
  90030. },
  90031. /**
  90032. * Sets the contrast used in the effect.
  90033. */
  90034. set: function (value) {
  90035. if (this._contrast === value) {
  90036. return;
  90037. }
  90038. this._contrast = value;
  90039. this._updateParameters();
  90040. },
  90041. enumerable: true,
  90042. configurable: true
  90043. });
  90044. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  90045. /**
  90046. * Gets the vignette blend mode allowing different kind of effect.
  90047. */
  90048. get: function () {
  90049. return this._vignetteBlendMode;
  90050. },
  90051. /**
  90052. * Sets the vignette blend mode allowing different kind of effect.
  90053. */
  90054. set: function (value) {
  90055. if (this._vignetteBlendMode === value) {
  90056. return;
  90057. }
  90058. this._vignetteBlendMode = value;
  90059. this._updateParameters();
  90060. },
  90061. enumerable: true,
  90062. configurable: true
  90063. });
  90064. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  90065. /**
  90066. * Gets wether the vignette effect is enabled.
  90067. */
  90068. get: function () {
  90069. return this._vignetteEnabled;
  90070. },
  90071. /**
  90072. * Sets wether the vignette effect is enabled.
  90073. */
  90074. set: function (value) {
  90075. if (this._vignetteEnabled === value) {
  90076. return;
  90077. }
  90078. this._vignetteEnabled = value;
  90079. this._updateParameters();
  90080. },
  90081. enumerable: true,
  90082. configurable: true
  90083. });
  90084. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  90085. /**
  90086. * Gets wether the image processing is applied through a post process or not.
  90087. */
  90088. get: function () {
  90089. return this._applyByPostProcess;
  90090. },
  90091. /**
  90092. * Sets wether the image processing is applied through a post process or not.
  90093. */
  90094. set: function (value) {
  90095. if (this._applyByPostProcess === value) {
  90096. return;
  90097. }
  90098. this._applyByPostProcess = value;
  90099. this._updateParameters();
  90100. },
  90101. enumerable: true,
  90102. configurable: true
  90103. });
  90104. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  90105. /**
  90106. * Gets wether the image processing is enabled or not.
  90107. */
  90108. get: function () {
  90109. return this._isEnabled;
  90110. },
  90111. /**
  90112. * Sets wether the image processing is enabled or not.
  90113. */
  90114. set: function (value) {
  90115. if (this._isEnabled === value) {
  90116. return;
  90117. }
  90118. this._isEnabled = value;
  90119. this._updateParameters();
  90120. },
  90121. enumerable: true,
  90122. configurable: true
  90123. });
  90124. /**
  90125. * Method called each time the image processing information changes requires to recompile the effect.
  90126. */
  90127. ImageProcessingConfiguration.prototype._updateParameters = function () {
  90128. this.onUpdateParameters.notifyObservers(this);
  90129. };
  90130. /**
  90131. * Gets the current class name.
  90132. * @return "ImageProcessingConfiguration"
  90133. */
  90134. ImageProcessingConfiguration.prototype.getClassName = function () {
  90135. return "ImageProcessingConfiguration";
  90136. };
  90137. /**
  90138. * Prepare the list of uniforms associated with the Image Processing effects.
  90139. * @param uniforms The list of uniforms used in the effect
  90140. * @param defines the list of defines currently in use
  90141. */
  90142. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  90143. if (defines.EXPOSURE) {
  90144. uniforms.push("exposureLinear");
  90145. }
  90146. if (defines.CONTRAST) {
  90147. uniforms.push("contrast");
  90148. }
  90149. if (defines.COLORGRADING) {
  90150. uniforms.push("colorTransformSettings");
  90151. }
  90152. if (defines.VIGNETTE) {
  90153. uniforms.push("vInverseScreenSize");
  90154. uniforms.push("vignetteSettings1");
  90155. uniforms.push("vignetteSettings2");
  90156. }
  90157. if (defines.COLORCURVES) {
  90158. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  90159. }
  90160. };
  90161. /**
  90162. * Prepare the list of samplers associated with the Image Processing effects.
  90163. * @param samplersList The list of uniforms used in the effect
  90164. * @param defines the list of defines currently in use
  90165. */
  90166. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  90167. if (defines.COLORGRADING) {
  90168. samplersList.push("txColorTransform");
  90169. }
  90170. };
  90171. /**
  90172. * Prepare the list of defines associated to the shader.
  90173. * @param defines the list of defines to complete
  90174. * @param forPostProcess Define if we are currently in post process mode or not
  90175. */
  90176. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  90177. if (forPostProcess === void 0) { forPostProcess = false; }
  90178. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  90179. defines.VIGNETTE = false;
  90180. defines.TONEMAPPING = false;
  90181. defines.TONEMAPPING_ACES = false;
  90182. defines.CONTRAST = false;
  90183. defines.EXPOSURE = false;
  90184. defines.COLORCURVES = false;
  90185. defines.COLORGRADING = false;
  90186. defines.COLORGRADING3D = false;
  90187. defines.IMAGEPROCESSING = false;
  90188. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  90189. return;
  90190. }
  90191. defines.VIGNETTE = this.vignetteEnabled;
  90192. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  90193. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  90194. defines.TONEMAPPING = this.toneMappingEnabled;
  90195. switch (this._toneMappingType) {
  90196. case ImageProcessingConfiguration.TONEMAPPING_ACES:
  90197. defines.TONEMAPPING_ACES = true;
  90198. break;
  90199. default:
  90200. defines.TONEMAPPING_ACES = false;
  90201. break;
  90202. }
  90203. defines.CONTRAST = (this.contrast !== 1.0);
  90204. defines.EXPOSURE = (this.exposure !== 1.0);
  90205. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  90206. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  90207. if (defines.COLORGRADING) {
  90208. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  90209. }
  90210. else {
  90211. defines.COLORGRADING3D = false;
  90212. }
  90213. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  90214. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  90215. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  90216. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  90217. };
  90218. /**
  90219. * Returns true if all the image processing information are ready.
  90220. * @returns True if ready, otherwise, false
  90221. */
  90222. ImageProcessingConfiguration.prototype.isReady = function () {
  90223. // Color Grading texure can not be none blocking.
  90224. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  90225. };
  90226. /**
  90227. * Binds the image processing to the shader.
  90228. * @param effect The effect to bind to
  90229. * @param aspectRatio Define the current aspect ratio of the effect
  90230. */
  90231. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  90232. if (aspectRatio === void 0) { aspectRatio = 1; }
  90233. // Color Curves
  90234. if (this._colorCurvesEnabled && this.colorCurves) {
  90235. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  90236. }
  90237. // Vignette
  90238. if (this._vignetteEnabled) {
  90239. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  90240. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  90241. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  90242. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  90243. var vignetteScaleX = vignetteScaleY * aspectRatio;
  90244. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  90245. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  90246. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  90247. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  90248. var vignettePower = -2.0 * this.vignetteWeight;
  90249. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  90250. }
  90251. // Exposure
  90252. effect.setFloat("exposureLinear", this.exposure);
  90253. // Contrast
  90254. effect.setFloat("contrast", this.contrast);
  90255. // Color transform settings
  90256. if (this.colorGradingTexture) {
  90257. effect.setTexture("txColorTransform", this.colorGradingTexture);
  90258. var textureSize = this.colorGradingTexture.getSize().height;
  90259. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  90260. 0.5 / textureSize, // textureOffset
  90261. textureSize, // textureSize
  90262. this.colorGradingTexture.level // weight
  90263. );
  90264. }
  90265. };
  90266. /**
  90267. * Clones the current image processing instance.
  90268. * @return The cloned image processing
  90269. */
  90270. ImageProcessingConfiguration.prototype.clone = function () {
  90271. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  90272. };
  90273. /**
  90274. * Serializes the current image processing instance to a json representation.
  90275. * @return a JSON representation
  90276. */
  90277. ImageProcessingConfiguration.prototype.serialize = function () {
  90278. return BABYLON.SerializationHelper.Serialize(this);
  90279. };
  90280. /**
  90281. * Parses the image processing from a json representation.
  90282. * @param source the JSON source to parse
  90283. * @return The parsed image processing
  90284. */
  90285. ImageProcessingConfiguration.Parse = function (source) {
  90286. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  90287. };
  90288. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  90289. /**
  90290. * Used to apply the vignette as a mix with the pixel color.
  90291. */
  90292. get: function () {
  90293. return this._VIGNETTEMODE_MULTIPLY;
  90294. },
  90295. enumerable: true,
  90296. configurable: true
  90297. });
  90298. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  90299. /**
  90300. * Used to apply the vignette as a replacement of the pixel color.
  90301. */
  90302. get: function () {
  90303. return this._VIGNETTEMODE_OPAQUE;
  90304. },
  90305. enumerable: true,
  90306. configurable: true
  90307. });
  90308. /**
  90309. * Default tone mapping applied in BabylonJS.
  90310. */
  90311. ImageProcessingConfiguration.TONEMAPPING_STANDARD = 0;
  90312. /**
  90313. * ACES Tone mapping (used by default in unreal and unity). This can help getting closer
  90314. * to other engines rendering to increase portability.
  90315. */
  90316. ImageProcessingConfiguration.TONEMAPPING_ACES = 1;
  90317. // Static constants associated to the image processing.
  90318. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  90319. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  90320. __decorate([
  90321. BABYLON.serializeAsColorCurves()
  90322. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  90323. __decorate([
  90324. BABYLON.serialize()
  90325. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  90326. __decorate([
  90327. BABYLON.serializeAsTexture("colorGradingTexture")
  90328. ], ImageProcessingConfiguration.prototype, "_colorGradingTexture", void 0);
  90329. __decorate([
  90330. BABYLON.serialize()
  90331. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  90332. __decorate([
  90333. BABYLON.serialize()
  90334. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  90335. __decorate([
  90336. BABYLON.serialize()
  90337. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  90338. __decorate([
  90339. BABYLON.serialize()
  90340. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  90341. __decorate([
  90342. BABYLON.serialize()
  90343. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  90344. __decorate([
  90345. BABYLON.serialize()
  90346. ], ImageProcessingConfiguration.prototype, "_toneMappingType", void 0);
  90347. __decorate([
  90348. BABYLON.serialize()
  90349. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  90350. __decorate([
  90351. BABYLON.serialize()
  90352. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  90353. __decorate([
  90354. BABYLON.serialize()
  90355. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  90356. __decorate([
  90357. BABYLON.serialize()
  90358. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  90359. __decorate([
  90360. BABYLON.serialize()
  90361. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  90362. __decorate([
  90363. BABYLON.serializeAsColor4()
  90364. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  90365. __decorate([
  90366. BABYLON.serialize()
  90367. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  90368. __decorate([
  90369. BABYLON.serialize()
  90370. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  90371. __decorate([
  90372. BABYLON.serialize()
  90373. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  90374. __decorate([
  90375. BABYLON.serialize()
  90376. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  90377. __decorate([
  90378. BABYLON.serialize()
  90379. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  90380. return ImageProcessingConfiguration;
  90381. }());
  90382. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  90383. })(BABYLON || (BABYLON = {}));
  90384. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  90385. var BABYLON;
  90386. (function (BABYLON) {
  90387. /**
  90388. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  90389. * It can help converting any input color in a desired output one. This can then be used to create effects
  90390. * from sepia, black and white to sixties or futuristic rendering...
  90391. *
  90392. * The only supported format is currently 3dl.
  90393. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table
  90394. */
  90395. var ColorGradingTexture = /** @class */ (function (_super) {
  90396. __extends(ColorGradingTexture, _super);
  90397. /**
  90398. * Instantiates a ColorGradingTexture from the following parameters.
  90399. *
  90400. * @param url The location of the color gradind data (currently only supporting 3dl)
  90401. * @param scene The scene the texture will be used in
  90402. */
  90403. function ColorGradingTexture(url, scene) {
  90404. var _this = _super.call(this, scene) || this;
  90405. if (!url) {
  90406. return _this;
  90407. }
  90408. _this._engine = scene.getEngine();
  90409. _this._textureMatrix = BABYLON.Matrix.Identity();
  90410. _this.name = url;
  90411. _this.url = url;
  90412. _this.hasAlpha = false;
  90413. _this.isCube = false;
  90414. _this.is3D = _this._engine.webGLVersion > 1;
  90415. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  90416. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  90417. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  90418. _this.anisotropicFilteringLevel = 1;
  90419. _this._texture = _this._getFromCache(url, true);
  90420. if (!_this._texture) {
  90421. if (!scene.useDelayedTextureLoading) {
  90422. _this.loadTexture();
  90423. }
  90424. else {
  90425. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  90426. }
  90427. }
  90428. return _this;
  90429. }
  90430. /**
  90431. * Returns the texture matrix used in most of the material.
  90432. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  90433. */
  90434. ColorGradingTexture.prototype.getTextureMatrix = function () {
  90435. return this._textureMatrix;
  90436. };
  90437. /**
  90438. * Occurs when the file being loaded is a .3dl LUT file.
  90439. */
  90440. ColorGradingTexture.prototype.load3dlTexture = function () {
  90441. var engine = this._engine;
  90442. var texture;
  90443. if (engine.webGLVersion === 1) {
  90444. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  90445. }
  90446. else {
  90447. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  90448. }
  90449. this._texture = texture;
  90450. var callback = function (text) {
  90451. if (typeof text !== "string") {
  90452. return;
  90453. }
  90454. var data = null;
  90455. var tempData = null;
  90456. var line;
  90457. var lines = text.split('\n');
  90458. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  90459. var maxColor = 0;
  90460. for (var i = 0; i < lines.length; i++) {
  90461. line = lines[i];
  90462. if (!ColorGradingTexture._noneEmptyLineRegex.test(line)) {
  90463. continue;
  90464. }
  90465. if (line.indexOf('#') === 0) {
  90466. continue;
  90467. }
  90468. var words = line.split(" ");
  90469. if (size === 0) {
  90470. // Number of space + one
  90471. size = words.length;
  90472. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  90473. tempData = new Float32Array(size * size * size * 4);
  90474. continue;
  90475. }
  90476. if (size != 0) {
  90477. var r = Math.max(parseInt(words[0]), 0);
  90478. var g = Math.max(parseInt(words[1]), 0);
  90479. var b = Math.max(parseInt(words[2]), 0);
  90480. maxColor = Math.max(r, maxColor);
  90481. maxColor = Math.max(g, maxColor);
  90482. maxColor = Math.max(b, maxColor);
  90483. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  90484. if (tempData) {
  90485. tempData[pixelStorageIndex + 0] = r;
  90486. tempData[pixelStorageIndex + 1] = g;
  90487. tempData[pixelStorageIndex + 2] = b;
  90488. }
  90489. // Keep for reference in case of back compat problems.
  90490. // pixelIndexSlice++;
  90491. // if (pixelIndexSlice % size == 0) {
  90492. // pixelIndexH++;
  90493. // pixelIndexSlice = 0;
  90494. // if (pixelIndexH % size == 0) {
  90495. // pixelIndexW++;
  90496. // pixelIndexH = 0;
  90497. // }
  90498. // }
  90499. pixelIndexH++;
  90500. if (pixelIndexH % size == 0) {
  90501. pixelIndexSlice++;
  90502. pixelIndexH = 0;
  90503. if (pixelIndexSlice % size == 0) {
  90504. pixelIndexW++;
  90505. pixelIndexSlice = 0;
  90506. }
  90507. }
  90508. }
  90509. }
  90510. if (tempData && data) {
  90511. for (var i = 0; i < tempData.length; i++) {
  90512. if (i > 0 && (i + 1) % 4 === 0) {
  90513. data[i] = 255;
  90514. }
  90515. else {
  90516. var value = tempData[i];
  90517. data[i] = (value / maxColor * 255);
  90518. }
  90519. }
  90520. }
  90521. if (texture.is3D) {
  90522. texture.updateSize(size, size, size);
  90523. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  90524. }
  90525. else {
  90526. texture.updateSize(size * size, size);
  90527. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  90528. }
  90529. };
  90530. var scene = this.getScene();
  90531. if (scene) {
  90532. scene._loadFile(this.url, callback);
  90533. }
  90534. else {
  90535. this._engine._loadFile(this.url, callback);
  90536. }
  90537. return this._texture;
  90538. };
  90539. /**
  90540. * Starts the loading process of the texture.
  90541. */
  90542. ColorGradingTexture.prototype.loadTexture = function () {
  90543. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  90544. this.load3dlTexture();
  90545. }
  90546. };
  90547. /**
  90548. * Clones the color gradind texture.
  90549. */
  90550. ColorGradingTexture.prototype.clone = function () {
  90551. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  90552. // Base texture
  90553. newTexture.level = this.level;
  90554. return newTexture;
  90555. };
  90556. /**
  90557. * Called during delayed load for textures.
  90558. */
  90559. ColorGradingTexture.prototype.delayLoad = function () {
  90560. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  90561. return;
  90562. }
  90563. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  90564. this._texture = this._getFromCache(this.url, true);
  90565. if (!this._texture) {
  90566. this.loadTexture();
  90567. }
  90568. };
  90569. /**
  90570. * Parses a color grading texture serialized by Babylon.
  90571. * @param parsedTexture The texture information being parsedTexture
  90572. * @param scene The scene to load the texture in
  90573. * @param rootUrl The root url of the data assets to load
  90574. * @return A color gradind texture
  90575. */
  90576. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  90577. var texture = null;
  90578. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  90579. texture = new ColorGradingTexture(parsedTexture.name, scene);
  90580. texture.name = parsedTexture.name;
  90581. texture.level = parsedTexture.level;
  90582. }
  90583. return texture;
  90584. };
  90585. /**
  90586. * Serializes the LUT texture to json format.
  90587. */
  90588. ColorGradingTexture.prototype.serialize = function () {
  90589. if (!this.name) {
  90590. return null;
  90591. }
  90592. var serializationObject = {};
  90593. serializationObject.name = this.name;
  90594. serializationObject.level = this.level;
  90595. serializationObject.customType = "BABYLON.ColorGradingTexture";
  90596. return serializationObject;
  90597. };
  90598. /**
  90599. * Empty line regex stored for GC.
  90600. */
  90601. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  90602. return ColorGradingTexture;
  90603. }(BABYLON.BaseTexture));
  90604. BABYLON.ColorGradingTexture = ColorGradingTexture;
  90605. })(BABYLON || (BABYLON = {}));
  90606. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  90607. var BABYLON;
  90608. (function (BABYLON) {
  90609. /**
  90610. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  90611. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  90612. * 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;
  90613. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  90614. */
  90615. var ColorCurves = /** @class */ (function () {
  90616. function ColorCurves() {
  90617. this._dirty = true;
  90618. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  90619. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  90620. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  90621. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  90622. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  90623. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  90624. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  90625. this._globalHue = 30;
  90626. this._globalDensity = 0;
  90627. this._globalSaturation = 0;
  90628. this._globalExposure = 0;
  90629. this._highlightsHue = 30;
  90630. this._highlightsDensity = 0;
  90631. this._highlightsSaturation = 0;
  90632. this._highlightsExposure = 0;
  90633. this._midtonesHue = 30;
  90634. this._midtonesDensity = 0;
  90635. this._midtonesSaturation = 0;
  90636. this._midtonesExposure = 0;
  90637. this._shadowsHue = 30;
  90638. this._shadowsDensity = 0;
  90639. this._shadowsSaturation = 0;
  90640. this._shadowsExposure = 0;
  90641. }
  90642. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  90643. /**
  90644. * Gets the global Hue value.
  90645. * 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).
  90646. */
  90647. get: function () {
  90648. return this._globalHue;
  90649. },
  90650. /**
  90651. * Sets the global Hue value.
  90652. * 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).
  90653. */
  90654. set: function (value) {
  90655. this._globalHue = value;
  90656. this._dirty = true;
  90657. },
  90658. enumerable: true,
  90659. configurable: true
  90660. });
  90661. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  90662. /**
  90663. * Gets the global Density value.
  90664. * 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.
  90665. * Values less than zero provide a filter of opposite hue.
  90666. */
  90667. get: function () {
  90668. return this._globalDensity;
  90669. },
  90670. /**
  90671. * Sets the global Density value.
  90672. * 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.
  90673. * Values less than zero provide a filter of opposite hue.
  90674. */
  90675. set: function (value) {
  90676. this._globalDensity = value;
  90677. this._dirty = true;
  90678. },
  90679. enumerable: true,
  90680. configurable: true
  90681. });
  90682. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  90683. /**
  90684. * Gets the global Saturation value.
  90685. * 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.
  90686. */
  90687. get: function () {
  90688. return this._globalSaturation;
  90689. },
  90690. /**
  90691. * Sets the global Saturation value.
  90692. * 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.
  90693. */
  90694. set: function (value) {
  90695. this._globalSaturation = value;
  90696. this._dirty = true;
  90697. },
  90698. enumerable: true,
  90699. configurable: true
  90700. });
  90701. Object.defineProperty(ColorCurves.prototype, "globalExposure", {
  90702. /**
  90703. * Gets the global Exposure value.
  90704. * 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.
  90705. */
  90706. get: function () {
  90707. return this._globalExposure;
  90708. },
  90709. /**
  90710. * Sets the global Exposure value.
  90711. * 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.
  90712. */
  90713. set: function (value) {
  90714. this._globalExposure = value;
  90715. this._dirty = true;
  90716. },
  90717. enumerable: true,
  90718. configurable: true
  90719. });
  90720. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  90721. /**
  90722. * Gets the highlights Hue value.
  90723. * 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).
  90724. */
  90725. get: function () {
  90726. return this._highlightsHue;
  90727. },
  90728. /**
  90729. * Sets the highlights Hue value.
  90730. * 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).
  90731. */
  90732. set: function (value) {
  90733. this._highlightsHue = value;
  90734. this._dirty = true;
  90735. },
  90736. enumerable: true,
  90737. configurable: true
  90738. });
  90739. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  90740. /**
  90741. * Gets the highlights Density value.
  90742. * 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.
  90743. * Values less than zero provide a filter of opposite hue.
  90744. */
  90745. get: function () {
  90746. return this._highlightsDensity;
  90747. },
  90748. /**
  90749. * Sets the highlights Density value.
  90750. * 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.
  90751. * Values less than zero provide a filter of opposite hue.
  90752. */
  90753. set: function (value) {
  90754. this._highlightsDensity = value;
  90755. this._dirty = true;
  90756. },
  90757. enumerable: true,
  90758. configurable: true
  90759. });
  90760. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  90761. /**
  90762. * Gets the highlights Saturation value.
  90763. * 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.
  90764. */
  90765. get: function () {
  90766. return this._highlightsSaturation;
  90767. },
  90768. /**
  90769. * Sets the highlights Saturation value.
  90770. * 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.
  90771. */
  90772. set: function (value) {
  90773. this._highlightsSaturation = value;
  90774. this._dirty = true;
  90775. },
  90776. enumerable: true,
  90777. configurable: true
  90778. });
  90779. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  90780. /**
  90781. * Gets the highlights Exposure value.
  90782. * 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.
  90783. */
  90784. get: function () {
  90785. return this._highlightsExposure;
  90786. },
  90787. /**
  90788. * Sets the highlights Exposure value.
  90789. * 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.
  90790. */
  90791. set: function (value) {
  90792. this._highlightsExposure = value;
  90793. this._dirty = true;
  90794. },
  90795. enumerable: true,
  90796. configurable: true
  90797. });
  90798. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  90799. /**
  90800. * Gets the midtones Hue value.
  90801. * 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).
  90802. */
  90803. get: function () {
  90804. return this._midtonesHue;
  90805. },
  90806. /**
  90807. * Sets the midtones Hue value.
  90808. * 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).
  90809. */
  90810. set: function (value) {
  90811. this._midtonesHue = value;
  90812. this._dirty = true;
  90813. },
  90814. enumerable: true,
  90815. configurable: true
  90816. });
  90817. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  90818. /**
  90819. * Gets the midtones Density value.
  90820. * 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.
  90821. * Values less than zero provide a filter of opposite hue.
  90822. */
  90823. get: function () {
  90824. return this._midtonesDensity;
  90825. },
  90826. /**
  90827. * Sets the midtones Density value.
  90828. * 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.
  90829. * Values less than zero provide a filter of opposite hue.
  90830. */
  90831. set: function (value) {
  90832. this._midtonesDensity = value;
  90833. this._dirty = true;
  90834. },
  90835. enumerable: true,
  90836. configurable: true
  90837. });
  90838. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  90839. /**
  90840. * Gets the midtones Saturation value.
  90841. * 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.
  90842. */
  90843. get: function () {
  90844. return this._midtonesSaturation;
  90845. },
  90846. /**
  90847. * Sets the midtones Saturation value.
  90848. * 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.
  90849. */
  90850. set: function (value) {
  90851. this._midtonesSaturation = value;
  90852. this._dirty = true;
  90853. },
  90854. enumerable: true,
  90855. configurable: true
  90856. });
  90857. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  90858. /**
  90859. * Gets the midtones Exposure value.
  90860. * 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.
  90861. */
  90862. get: function () {
  90863. return this._midtonesExposure;
  90864. },
  90865. /**
  90866. * Sets the midtones Exposure value.
  90867. * 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.
  90868. */
  90869. set: function (value) {
  90870. this._midtonesExposure = value;
  90871. this._dirty = true;
  90872. },
  90873. enumerable: true,
  90874. configurable: true
  90875. });
  90876. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  90877. /**
  90878. * Gets the shadows Hue value.
  90879. * 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).
  90880. */
  90881. get: function () {
  90882. return this._shadowsHue;
  90883. },
  90884. /**
  90885. * Sets the shadows Hue value.
  90886. * 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).
  90887. */
  90888. set: function (value) {
  90889. this._shadowsHue = value;
  90890. this._dirty = true;
  90891. },
  90892. enumerable: true,
  90893. configurable: true
  90894. });
  90895. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  90896. /**
  90897. * Gets the shadows Density value.
  90898. * 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.
  90899. * Values less than zero provide a filter of opposite hue.
  90900. */
  90901. get: function () {
  90902. return this._shadowsDensity;
  90903. },
  90904. /**
  90905. * Sets the shadows Density value.
  90906. * 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.
  90907. * Values less than zero provide a filter of opposite hue.
  90908. */
  90909. set: function (value) {
  90910. this._shadowsDensity = value;
  90911. this._dirty = true;
  90912. },
  90913. enumerable: true,
  90914. configurable: true
  90915. });
  90916. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  90917. /**
  90918. * Gets the shadows Saturation value.
  90919. * 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.
  90920. */
  90921. get: function () {
  90922. return this._shadowsSaturation;
  90923. },
  90924. /**
  90925. * Sets the shadows Saturation value.
  90926. * 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.
  90927. */
  90928. set: function (value) {
  90929. this._shadowsSaturation = value;
  90930. this._dirty = true;
  90931. },
  90932. enumerable: true,
  90933. configurable: true
  90934. });
  90935. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  90936. /**
  90937. * Gets the shadows Exposure value.
  90938. * 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.
  90939. */
  90940. get: function () {
  90941. return this._shadowsExposure;
  90942. },
  90943. /**
  90944. * Sets the shadows Exposure value.
  90945. * 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.
  90946. */
  90947. set: function (value) {
  90948. this._shadowsExposure = value;
  90949. this._dirty = true;
  90950. },
  90951. enumerable: true,
  90952. configurable: true
  90953. });
  90954. /**
  90955. * Returns the class name
  90956. * @returns The class name
  90957. */
  90958. ColorCurves.prototype.getClassName = function () {
  90959. return "ColorCurves";
  90960. };
  90961. /**
  90962. * Binds the color curves to the shader.
  90963. * @param colorCurves The color curve to bind
  90964. * @param effect The effect to bind to
  90965. * @param positiveUniform The positive uniform shader parameter
  90966. * @param neutralUniform The neutral uniform shader parameter
  90967. * @param negativeUniform The negative uniform shader parameter
  90968. */
  90969. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  90970. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  90971. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  90972. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  90973. if (colorCurves._dirty) {
  90974. colorCurves._dirty = false;
  90975. // Fill in global info.
  90976. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  90977. // Compute highlights info.
  90978. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  90979. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  90980. // Compute midtones info.
  90981. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  90982. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  90983. // Compute shadows info.
  90984. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  90985. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  90986. // Compute deltas (neutral is midtones).
  90987. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  90988. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  90989. }
  90990. if (effect) {
  90991. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  90992. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  90993. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  90994. }
  90995. };
  90996. /**
  90997. * Prepare the list of uniforms associated with the ColorCurves effects.
  90998. * @param uniformsList The list of uniforms used in the effect
  90999. */
  91000. ColorCurves.PrepareUniforms = function (uniformsList) {
  91001. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  91002. };
  91003. /**
  91004. * Returns color grading data based on a hue, density, saturation and exposure value.
  91005. * @param filterHue The hue of the color filter.
  91006. * @param filterDensity The density of the color filter.
  91007. * @param saturation The saturation.
  91008. * @param exposure The exposure.
  91009. * @param result The result data container.
  91010. */
  91011. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  91012. if (hue == null) {
  91013. return;
  91014. }
  91015. hue = ColorCurves.clamp(hue, 0, 360);
  91016. density = ColorCurves.clamp(density, -100, 100);
  91017. saturation = ColorCurves.clamp(saturation, -100, 100);
  91018. exposure = ColorCurves.clamp(exposure, -100, 100);
  91019. // Remap the slider/config filter density with non-linear mapping and also scale by half
  91020. // so that the maximum filter density is only 50% control. This provides fine control
  91021. // for small values and reasonable range.
  91022. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  91023. density *= 0.5;
  91024. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  91025. if (density < 0) {
  91026. density *= -1;
  91027. hue = (hue + 180) % 360;
  91028. }
  91029. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  91030. result.scaleToRef(2, result);
  91031. result.a = 1 + 0.01 * saturation;
  91032. };
  91033. /**
  91034. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  91035. * @param value The input slider value in range [-100,100].
  91036. * @returns Adjusted value.
  91037. */
  91038. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  91039. value /= 100;
  91040. var x = Math.abs(value);
  91041. x = Math.pow(x, 2);
  91042. if (value < 0) {
  91043. x *= -1;
  91044. }
  91045. x *= 100;
  91046. return x;
  91047. };
  91048. /**
  91049. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  91050. * @param hue The hue (H) input.
  91051. * @param saturation The saturation (S) input.
  91052. * @param brightness The brightness (B) input.
  91053. * @result An RGBA color represented as Vector4.
  91054. */
  91055. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  91056. var h = ColorCurves.clamp(hue, 0, 360);
  91057. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  91058. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  91059. if (s === 0) {
  91060. result.r = v;
  91061. result.g = v;
  91062. result.b = v;
  91063. }
  91064. else {
  91065. // sector 0 to 5
  91066. h /= 60;
  91067. var i = Math.floor(h);
  91068. // fractional part of h
  91069. var f = h - i;
  91070. var p = v * (1 - s);
  91071. var q = v * (1 - s * f);
  91072. var t = v * (1 - s * (1 - f));
  91073. switch (i) {
  91074. case 0:
  91075. result.r = v;
  91076. result.g = t;
  91077. result.b = p;
  91078. break;
  91079. case 1:
  91080. result.r = q;
  91081. result.g = v;
  91082. result.b = p;
  91083. break;
  91084. case 2:
  91085. result.r = p;
  91086. result.g = v;
  91087. result.b = t;
  91088. break;
  91089. case 3:
  91090. result.r = p;
  91091. result.g = q;
  91092. result.b = v;
  91093. break;
  91094. case 4:
  91095. result.r = t;
  91096. result.g = p;
  91097. result.b = v;
  91098. break;
  91099. default: // case 5:
  91100. result.r = v;
  91101. result.g = p;
  91102. result.b = q;
  91103. break;
  91104. }
  91105. }
  91106. result.a = 1;
  91107. };
  91108. /**
  91109. * Returns a value clamped between min and max
  91110. * @param value The value to clamp
  91111. * @param min The minimum of value
  91112. * @param max The maximum of value
  91113. * @returns The clamped value.
  91114. */
  91115. ColorCurves.clamp = function (value, min, max) {
  91116. return Math.min(Math.max(value, min), max);
  91117. };
  91118. /**
  91119. * Clones the current color curve instance.
  91120. * @return The cloned curves
  91121. */
  91122. ColorCurves.prototype.clone = function () {
  91123. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  91124. };
  91125. /**
  91126. * Serializes the current color curve instance to a json representation.
  91127. * @return a JSON representation
  91128. */
  91129. ColorCurves.prototype.serialize = function () {
  91130. return BABYLON.SerializationHelper.Serialize(this);
  91131. };
  91132. /**
  91133. * Parses the color curve from a json representation.
  91134. * @param source the JSON source to parse
  91135. * @return The parsed curves
  91136. */
  91137. ColorCurves.Parse = function (source) {
  91138. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  91139. };
  91140. __decorate([
  91141. BABYLON.serialize()
  91142. ], ColorCurves.prototype, "_globalHue", void 0);
  91143. __decorate([
  91144. BABYLON.serialize()
  91145. ], ColorCurves.prototype, "_globalDensity", void 0);
  91146. __decorate([
  91147. BABYLON.serialize()
  91148. ], ColorCurves.prototype, "_globalSaturation", void 0);
  91149. __decorate([
  91150. BABYLON.serialize()
  91151. ], ColorCurves.prototype, "_globalExposure", void 0);
  91152. __decorate([
  91153. BABYLON.serialize()
  91154. ], ColorCurves.prototype, "_highlightsHue", void 0);
  91155. __decorate([
  91156. BABYLON.serialize()
  91157. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  91158. __decorate([
  91159. BABYLON.serialize()
  91160. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  91161. __decorate([
  91162. BABYLON.serialize()
  91163. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  91164. __decorate([
  91165. BABYLON.serialize()
  91166. ], ColorCurves.prototype, "_midtonesHue", void 0);
  91167. __decorate([
  91168. BABYLON.serialize()
  91169. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  91170. __decorate([
  91171. BABYLON.serialize()
  91172. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  91173. __decorate([
  91174. BABYLON.serialize()
  91175. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  91176. return ColorCurves;
  91177. }());
  91178. BABYLON.ColorCurves = ColorCurves;
  91179. })(BABYLON || (BABYLON = {}));
  91180. //# sourceMappingURL=babylon.colorCurves.js.map
  91181. var BABYLON;
  91182. (function (BABYLON) {
  91183. /**
  91184. * Post process which applies a refractin texture
  91185. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses#refraction
  91186. */
  91187. var RefractionPostProcess = /** @class */ (function (_super) {
  91188. __extends(RefractionPostProcess, _super);
  91189. /**
  91190. * Initializes the RefractionPostProcess
  91191. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses#refraction
  91192. * @param name The name of the effect.
  91193. * @param refractionTextureUrl Url of the refraction texture to use
  91194. * @param color the base color of the refraction (used to taint the rendering)
  91195. * @param depth simulated refraction depth
  91196. * @param colorLevel the coefficient of the base color (0 to remove base color tainting)
  91197. * @param camera The camera to apply the render pass to.
  91198. * @param options The required width/height ratio to downsize to before computing the render pass.
  91199. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  91200. * @param engine The engine which the post process will be applied. (default: current engine)
  91201. * @param reusable If the post process can be reused on the same frame. (default: false)
  91202. */
  91203. function RefractionPostProcess(name, refractionTextureUrl,
  91204. /** the base color of the refraction (used to taint the rendering) */
  91205. color,
  91206. /** simulated refraction depth */
  91207. depth,
  91208. /** the coefficient of the base color (0 to remove base color tainting) */
  91209. colorLevel, options, camera, samplingMode, engine, reusable) {
  91210. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  91211. _this.color = color;
  91212. _this.depth = depth;
  91213. _this.colorLevel = colorLevel;
  91214. _this._ownRefractionTexture = true;
  91215. _this.onActivateObservable.add(function (cam) {
  91216. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  91217. });
  91218. _this.onApplyObservable.add(function (effect) {
  91219. effect.setColor3("baseColor", _this.color);
  91220. effect.setFloat("depth", _this.depth);
  91221. effect.setFloat("colorLevel", _this.colorLevel);
  91222. effect.setTexture("refractionSampler", _this._refTexture);
  91223. });
  91224. return _this;
  91225. }
  91226. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  91227. /**
  91228. * Gets or sets the refraction texture
  91229. * Please note that you are responsible for disposing the texture if you set it manually
  91230. */
  91231. get: function () {
  91232. return this._refTexture;
  91233. },
  91234. set: function (value) {
  91235. if (this._refTexture && this._ownRefractionTexture) {
  91236. this._refTexture.dispose();
  91237. }
  91238. this._refTexture = value;
  91239. this._ownRefractionTexture = false;
  91240. },
  91241. enumerable: true,
  91242. configurable: true
  91243. });
  91244. // Methods
  91245. /**
  91246. * Disposes of the post process
  91247. * @param camera Camera to dispose post process on
  91248. */
  91249. RefractionPostProcess.prototype.dispose = function (camera) {
  91250. if (this._refTexture && this._ownRefractionTexture) {
  91251. this._refTexture.dispose();
  91252. this._refTexture = null;
  91253. }
  91254. _super.prototype.dispose.call(this, camera);
  91255. };
  91256. return RefractionPostProcess;
  91257. }(BABYLON.PostProcess));
  91258. BABYLON.RefractionPostProcess = RefractionPostProcess;
  91259. })(BABYLON || (BABYLON = {}));
  91260. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  91261. var BABYLON;
  91262. (function (BABYLON) {
  91263. /**
  91264. * Post process used to render in black and white
  91265. */
  91266. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  91267. __extends(BlackAndWhitePostProcess, _super);
  91268. /**
  91269. * Creates a black and white post process
  91270. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses#black-and-white
  91271. * @param name The name of the effect.
  91272. * @param options The required width/height ratio to downsize to before computing the render pass.
  91273. * @param camera The camera to apply the render pass to.
  91274. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  91275. * @param engine The engine which the post process will be applied. (default: current engine)
  91276. * @param reusable If the post process can be reused on the same frame. (default: false)
  91277. */
  91278. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  91279. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  91280. /**
  91281. * Linear about to convert he result to black and white (default: 1)
  91282. */
  91283. _this.degree = 1;
  91284. _this.onApplyObservable.add(function (effect) {
  91285. effect.setFloat("degree", _this.degree);
  91286. });
  91287. return _this;
  91288. }
  91289. return BlackAndWhitePostProcess;
  91290. }(BABYLON.PostProcess));
  91291. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  91292. })(BABYLON || (BABYLON = {}));
  91293. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  91294. var BABYLON;
  91295. (function (BABYLON) {
  91296. /**
  91297. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  91298. * input texture to perform effects such as edge detection or sharpening
  91299. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  91300. */
  91301. var ConvolutionPostProcess = /** @class */ (function (_super) {
  91302. __extends(ConvolutionPostProcess, _super);
  91303. /**
  91304. * Creates a new instance ConvolutionPostProcess
  91305. * @param name The name of the effect.
  91306. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  91307. * @param options The required width/height ratio to downsize to before computing the render pass.
  91308. * @param camera The camera to apply the render pass to.
  91309. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  91310. * @param engine The engine which the post process will be applied. (default: current engine)
  91311. * @param reusable If the post process can be reused on the same frame. (default: false)
  91312. * @param textureType Type of textures used when performing the post process. (default: 0)
  91313. */
  91314. function ConvolutionPostProcess(name,
  91315. /** Array of 9 values corrisponding to the 3x3 kernel to be applied */
  91316. kernel, options, camera, samplingMode, engine, reusable, textureType) {
  91317. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  91318. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  91319. _this.kernel = kernel;
  91320. _this.onApply = function (effect) {
  91321. effect.setFloat2("screenSize", _this.width, _this.height);
  91322. effect.setArray("kernel", _this.kernel);
  91323. };
  91324. return _this;
  91325. }
  91326. // Statics
  91327. /**
  91328. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  91329. */
  91330. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  91331. /**
  91332. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  91333. */
  91334. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  91335. /**
  91336. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  91337. */
  91338. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  91339. /**
  91340. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  91341. */
  91342. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  91343. /**
  91344. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  91345. */
  91346. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  91347. /**
  91348. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  91349. */
  91350. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  91351. return ConvolutionPostProcess;
  91352. }(BABYLON.PostProcess));
  91353. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  91354. })(BABYLON || (BABYLON = {}));
  91355. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  91356. var BABYLON;
  91357. (function (BABYLON) {
  91358. /**
  91359. * Applies a kernel filter to the image
  91360. */
  91361. var FilterPostProcess = /** @class */ (function (_super) {
  91362. __extends(FilterPostProcess, _super);
  91363. /**
  91364. *
  91365. * @param name The name of the effect.
  91366. * @param kernelMatrix The matrix to be applied to the image
  91367. * @param options The required width/height ratio to downsize to before computing the render pass.
  91368. * @param camera The camera to apply the render pass to.
  91369. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  91370. * @param engine The engine which the post process will be applied. (default: current engine)
  91371. * @param reusable If the post process can be reused on the same frame. (default: false)
  91372. */
  91373. function FilterPostProcess(name,
  91374. /** The matrix to be applied to the image */
  91375. kernelMatrix, options, camera, samplingMode, engine, reusable) {
  91376. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  91377. _this.kernelMatrix = kernelMatrix;
  91378. _this.onApply = function (effect) {
  91379. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  91380. };
  91381. return _this;
  91382. }
  91383. return FilterPostProcess;
  91384. }(BABYLON.PostProcess));
  91385. BABYLON.FilterPostProcess = FilterPostProcess;
  91386. })(BABYLON || (BABYLON = {}));
  91387. //# sourceMappingURL=babylon.filterPostProcess.js.map
  91388. var BABYLON;
  91389. (function (BABYLON) {
  91390. /**
  91391. * Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  91392. */
  91393. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  91394. __extends(VolumetricLightScatteringPostProcess, _super);
  91395. /**
  91396. * @constructor
  91397. * @param name The post-process name
  91398. * @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)
  91399. * @param camera The camera that the post-process will be attached to
  91400. * @param mesh The mesh used to create the light scattering
  91401. * @param samples The post-process quality, default 100
  91402. * @param samplingModeThe post-process filtering mode
  91403. * @param engine The babylon engine
  91404. * @param reusable If the post-process is reusable
  91405. * @param scene The constructor needs a scene reference to initialize internal components. If "camera" is null a "scene" must be provided
  91406. */
  91407. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  91408. if (samples === void 0) { samples = 100; }
  91409. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  91410. 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;
  91411. _this._screenCoordinates = BABYLON.Vector2.Zero();
  91412. /**
  91413. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  91414. */
  91415. _this.customMeshPosition = BABYLON.Vector3.Zero();
  91416. /**
  91417. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  91418. */
  91419. _this.useCustomMeshPosition = false;
  91420. /**
  91421. * If the post-process should inverse the light scattering direction
  91422. */
  91423. _this.invert = true;
  91424. /**
  91425. * Array containing the excluded meshes not rendered in the internal pass
  91426. */
  91427. _this.excludedMeshes = new Array();
  91428. /**
  91429. * Controls the overall intensity of the post-process
  91430. */
  91431. _this.exposure = 0.3;
  91432. /**
  91433. * Dissipates each sample's contribution in range [0, 1]
  91434. */
  91435. _this.decay = 0.96815;
  91436. /**
  91437. * Controls the overall intensity of each sample
  91438. */
  91439. _this.weight = 0.58767;
  91440. /**
  91441. * Controls the density of each sample
  91442. */
  91443. _this.density = 0.926;
  91444. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  91445. engine = scene.getEngine();
  91446. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  91447. // Configure mesh
  91448. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  91449. // Configure
  91450. _this._createPass(scene, ratio.passRatio || ratio);
  91451. _this.onActivate = function (camera) {
  91452. if (!_this.isSupported) {
  91453. _this.dispose(camera);
  91454. }
  91455. _this.onActivate = null;
  91456. };
  91457. _this.onApplyObservable.add(function (effect) {
  91458. _this._updateMeshScreenCoordinates(scene);
  91459. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  91460. effect.setFloat("exposure", _this.exposure);
  91461. effect.setFloat("decay", _this.decay);
  91462. effect.setFloat("weight", _this.weight);
  91463. effect.setFloat("density", _this.density);
  91464. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  91465. });
  91466. return _this;
  91467. }
  91468. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  91469. /**
  91470. * @hidden
  91471. * VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead
  91472. */
  91473. get: function () {
  91474. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  91475. return false;
  91476. },
  91477. set: function (useDiffuseColor) {
  91478. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  91479. },
  91480. enumerable: true,
  91481. configurable: true
  91482. });
  91483. /**
  91484. * Returns the string "VolumetricLightScatteringPostProcess"
  91485. * @returns "VolumetricLightScatteringPostProcess"
  91486. */
  91487. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  91488. return "VolumetricLightScatteringPostProcess";
  91489. };
  91490. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  91491. var mesh = subMesh.getMesh();
  91492. // Render this.mesh as default
  91493. if (mesh === this.mesh && mesh.material) {
  91494. return mesh.material.isReady(mesh);
  91495. }
  91496. var defines = [];
  91497. var attribs = [BABYLON.VertexBuffer.PositionKind];
  91498. var material = subMesh.getMaterial();
  91499. // Alpha test
  91500. if (material) {
  91501. if (material.needAlphaTesting()) {
  91502. defines.push("#define ALPHATEST");
  91503. }
  91504. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  91505. attribs.push(BABYLON.VertexBuffer.UVKind);
  91506. defines.push("#define UV1");
  91507. }
  91508. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  91509. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  91510. defines.push("#define UV2");
  91511. }
  91512. }
  91513. // Bones
  91514. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  91515. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  91516. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  91517. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  91518. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  91519. }
  91520. else {
  91521. defines.push("#define NUM_BONE_INFLUENCERS 0");
  91522. }
  91523. // Instances
  91524. if (useInstances) {
  91525. defines.push("#define INSTANCES");
  91526. attribs.push("world0");
  91527. attribs.push("world1");
  91528. attribs.push("world2");
  91529. attribs.push("world3");
  91530. }
  91531. // Get correct effect
  91532. var join = defines.join("\n");
  91533. if (this._cachedDefines !== join) {
  91534. this._cachedDefines = join;
  91535. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  91536. }
  91537. return this._volumetricLightScatteringPass.isReady();
  91538. };
  91539. /**
  91540. * Sets the new light position for light scattering effect
  91541. * @param position The new custom light position
  91542. */
  91543. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  91544. this.customMeshPosition = position;
  91545. };
  91546. /**
  91547. * Returns the light position for light scattering effect
  91548. * @return Vector3 The custom light position
  91549. */
  91550. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  91551. return this.customMeshPosition;
  91552. };
  91553. /**
  91554. * Disposes the internal assets and detaches the post-process from the camera
  91555. */
  91556. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  91557. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  91558. if (rttIndex !== -1) {
  91559. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  91560. }
  91561. this._volumetricLightScatteringRTT.dispose();
  91562. _super.prototype.dispose.call(this, camera);
  91563. };
  91564. /**
  91565. * Returns the render target texture used by the post-process
  91566. * @return the render target texture used by the post-process
  91567. */
  91568. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  91569. return this._volumetricLightScatteringRTT;
  91570. };
  91571. // Private methods
  91572. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  91573. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  91574. return true;
  91575. }
  91576. return false;
  91577. };
  91578. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  91579. var _this = this;
  91580. var engine = scene.getEngine();
  91581. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  91582. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91583. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91584. this._volumetricLightScatteringRTT.renderList = null;
  91585. this._volumetricLightScatteringRTT.renderParticles = false;
  91586. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  91587. var camera = this.getCamera();
  91588. if (camera) {
  91589. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  91590. }
  91591. else {
  91592. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  91593. }
  91594. // Custom render function for submeshes
  91595. var renderSubMesh = function (subMesh) {
  91596. var mesh = subMesh.getRenderingMesh();
  91597. if (_this._meshExcluded(mesh)) {
  91598. return;
  91599. }
  91600. var material = subMesh.getMaterial();
  91601. if (!material) {
  91602. return;
  91603. }
  91604. var scene = mesh.getScene();
  91605. var engine = scene.getEngine();
  91606. // Culling
  91607. engine.setState(material.backFaceCulling);
  91608. // Managing instances
  91609. var batch = mesh._getInstancesRenderList(subMesh._id);
  91610. if (batch.mustReturn) {
  91611. return;
  91612. }
  91613. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  91614. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  91615. var effect = _this._volumetricLightScatteringPass;
  91616. if (mesh === _this.mesh) {
  91617. if (subMesh.effect) {
  91618. effect = subMesh.effect;
  91619. }
  91620. else {
  91621. effect = material.getEffect();
  91622. }
  91623. }
  91624. engine.enableEffect(effect);
  91625. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  91626. if (mesh === _this.mesh) {
  91627. material.bind(mesh.getWorldMatrix(), mesh);
  91628. }
  91629. else {
  91630. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  91631. // Alpha test
  91632. if (material && material.needAlphaTesting()) {
  91633. var alphaTexture = material.getAlphaTestTexture();
  91634. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  91635. if (alphaTexture) {
  91636. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  91637. }
  91638. }
  91639. // Bones
  91640. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  91641. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  91642. }
  91643. }
  91644. // Draw
  91645. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  91646. }
  91647. };
  91648. // Render target texture callbacks
  91649. var savedSceneClearColor;
  91650. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  91651. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  91652. savedSceneClearColor = scene.clearColor;
  91653. scene.clearColor = sceneClearColor;
  91654. });
  91655. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  91656. scene.clearColor = savedSceneClearColor;
  91657. });
  91658. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  91659. var engine = scene.getEngine();
  91660. var index;
  91661. if (depthOnlySubMeshes.length) {
  91662. engine.setColorWrite(false);
  91663. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  91664. renderSubMesh(depthOnlySubMeshes.data[index]);
  91665. }
  91666. engine.setColorWrite(true);
  91667. }
  91668. for (index = 0; index < opaqueSubMeshes.length; index++) {
  91669. renderSubMesh(opaqueSubMeshes.data[index]);
  91670. }
  91671. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  91672. renderSubMesh(alphaTestSubMeshes.data[index]);
  91673. }
  91674. if (transparentSubMeshes.length) {
  91675. // Sort sub meshes
  91676. for (index = 0; index < transparentSubMeshes.length; index++) {
  91677. var submesh = transparentSubMeshes.data[index];
  91678. var boundingInfo = submesh.getBoundingInfo();
  91679. if (boundingInfo && scene.activeCamera) {
  91680. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  91681. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  91682. }
  91683. }
  91684. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  91685. sortedArray.sort(function (a, b) {
  91686. // Alpha index first
  91687. if (a._alphaIndex > b._alphaIndex) {
  91688. return 1;
  91689. }
  91690. if (a._alphaIndex < b._alphaIndex) {
  91691. return -1;
  91692. }
  91693. // Then distance to camera
  91694. if (a._distanceToCamera < b._distanceToCamera) {
  91695. return 1;
  91696. }
  91697. if (a._distanceToCamera > b._distanceToCamera) {
  91698. return -1;
  91699. }
  91700. return 0;
  91701. });
  91702. // Render sub meshes
  91703. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  91704. for (index = 0; index < sortedArray.length; index++) {
  91705. renderSubMesh(sortedArray[index]);
  91706. }
  91707. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  91708. }
  91709. };
  91710. };
  91711. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  91712. var transform = scene.getTransformMatrix();
  91713. var meshPosition;
  91714. if (this.useCustomMeshPosition) {
  91715. meshPosition = this.customMeshPosition;
  91716. }
  91717. else if (this.attachedNode) {
  91718. meshPosition = this.attachedNode.position;
  91719. }
  91720. else {
  91721. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  91722. }
  91723. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  91724. this._screenCoordinates.x = pos.x / this._viewPort.width;
  91725. this._screenCoordinates.y = pos.y / this._viewPort.height;
  91726. if (this.invert) {
  91727. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  91728. }
  91729. };
  91730. // Static methods
  91731. /**
  91732. * Creates a default mesh for the Volumeric Light Scattering post-process
  91733. * @param name The mesh name
  91734. * @param scene The scene where to create the mesh
  91735. * @return the default mesh
  91736. */
  91737. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  91738. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  91739. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  91740. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  91741. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  91742. mesh.material = material;
  91743. return mesh;
  91744. };
  91745. __decorate([
  91746. BABYLON.serializeAsVector3()
  91747. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  91748. __decorate([
  91749. BABYLON.serialize()
  91750. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  91751. __decorate([
  91752. BABYLON.serialize()
  91753. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  91754. __decorate([
  91755. BABYLON.serializeAsMeshReference()
  91756. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  91757. __decorate([
  91758. BABYLON.serialize()
  91759. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  91760. __decorate([
  91761. BABYLON.serialize()
  91762. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  91763. __decorate([
  91764. BABYLON.serialize()
  91765. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  91766. __decorate([
  91767. BABYLON.serialize()
  91768. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  91769. __decorate([
  91770. BABYLON.serialize()
  91771. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  91772. return VolumetricLightScatteringPostProcess;
  91773. }(BABYLON.PostProcess));
  91774. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  91775. })(BABYLON || (BABYLON = {}));
  91776. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  91777. var BABYLON;
  91778. (function (BABYLON) {
  91779. /**
  91780. *
  91781. * This post-process allows the modification of rendered colors by using
  91782. * a 'look-up table' (LUT). This effect is also called Color Grading.
  91783. *
  91784. * The object needs to be provided an url to a texture containing the color
  91785. * look-up table: the texture must be 256 pixels wide and 16 pixels high.
  91786. * Use an image editing software to tweak the LUT to match your needs.
  91787. *
  91788. * For an example of a color LUT, see here:
  91789. * @see http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  91790. * For explanations on color grading, see here:
  91791. * @see http://udn.epicgames.com/Three/ColorGrading.html
  91792. *
  91793. */
  91794. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  91795. __extends(ColorCorrectionPostProcess, _super);
  91796. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  91797. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  91798. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  91799. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  91800. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91801. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91802. _this.onApply = function (effect) {
  91803. effect.setTexture("colorTable", _this._colorTableTexture);
  91804. };
  91805. return _this;
  91806. }
  91807. return ColorCorrectionPostProcess;
  91808. }(BABYLON.PostProcess));
  91809. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  91810. })(BABYLON || (BABYLON = {}));
  91811. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  91812. var BABYLON;
  91813. (function (BABYLON) {
  91814. /** Defines operator used for tonemapping */
  91815. var TonemappingOperator;
  91816. (function (TonemappingOperator) {
  91817. /** Hable */
  91818. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  91819. /** Reinhard */
  91820. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  91821. /** HejiDawson */
  91822. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  91823. /** Photographic */
  91824. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  91825. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  91826. /**
  91827. * Defines a post process to apply tone mapping
  91828. */
  91829. var TonemapPostProcess = /** @class */ (function (_super) {
  91830. __extends(TonemapPostProcess, _super);
  91831. /**
  91832. * Creates a new TonemapPostProcess
  91833. * @param name defines the name of the postprocess
  91834. * @param _operator defines the operator to use
  91835. * @param exposureAdjustment defines the required exposure adjustement
  91836. * @param camera defines the camera to use (can be null)
  91837. * @param samplingMode defines the required sampling mode (BABYLON.Texture.BILINEAR_SAMPLINGMODE by default)
  91838. * @param engine defines the hosting engine (can be ignore if camera is set)
  91839. * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  91840. */
  91841. function TonemapPostProcess(name, _operator,
  91842. /** Defines the required exposure adjustement */
  91843. exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  91844. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  91845. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  91846. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  91847. _this._operator = _operator;
  91848. _this.exposureAdjustment = exposureAdjustment;
  91849. var defines = "#define ";
  91850. if (_this._operator === TonemappingOperator.Hable) {
  91851. defines += "HABLE_TONEMAPPING";
  91852. }
  91853. else if (_this._operator === TonemappingOperator.Reinhard) {
  91854. defines += "REINHARD_TONEMAPPING";
  91855. }
  91856. else if (_this._operator === TonemappingOperator.HejiDawson) {
  91857. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  91858. }
  91859. else if (_this._operator === TonemappingOperator.Photographic) {
  91860. defines += "PHOTOGRAPHIC_TONEMAPPING";
  91861. }
  91862. //sadly a second call to create the effect.
  91863. _this.updateEffect(defines);
  91864. _this.onApply = function (effect) {
  91865. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  91866. };
  91867. return _this;
  91868. }
  91869. return TonemapPostProcess;
  91870. }(BABYLON.PostProcess));
  91871. BABYLON.TonemapPostProcess = TonemapPostProcess;
  91872. })(BABYLON || (BABYLON = {}));
  91873. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  91874. var BABYLON;
  91875. (function (BABYLON) {
  91876. /**
  91877. * DisplayPassPostProcess which produces an output the same as it's input
  91878. */
  91879. var DisplayPassPostProcess = /** @class */ (function (_super) {
  91880. __extends(DisplayPassPostProcess, _super);
  91881. /**
  91882. * Creates the DisplayPassPostProcess
  91883. * @param name The name of the effect.
  91884. * @param options The required width/height ratio to downsize to before computing the render pass.
  91885. * @param camera The camera to apply the render pass to.
  91886. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  91887. * @param engine The engine which the post process will be applied. (default: current engine)
  91888. * @param reusable If the post process can be reused on the same frame. (default: false)
  91889. */
  91890. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  91891. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  91892. }
  91893. return DisplayPassPostProcess;
  91894. }(BABYLON.PostProcess));
  91895. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  91896. })(BABYLON || (BABYLON = {}));
  91897. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  91898. var BABYLON;
  91899. (function (BABYLON) {
  91900. /**
  91901. * Extracts highlights from the image
  91902. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  91903. */
  91904. var HighlightsPostProcess = /** @class */ (function (_super) {
  91905. __extends(HighlightsPostProcess, _super);
  91906. /**
  91907. * Extracts highlights from the image
  91908. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  91909. * @param name The name of the effect.
  91910. * @param options The required width/height ratio to downsize to before computing the render pass.
  91911. * @param camera The camera to apply the render pass to.
  91912. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  91913. * @param engine The engine which the post process will be applied. (default: current engine)
  91914. * @param reusable If the post process can be reused on the same frame. (default: false)
  91915. * @param textureType Type of texture for the post process (default: Engine.TEXTURETYPE_UNSIGNED_INT)
  91916. */
  91917. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  91918. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  91919. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  91920. }
  91921. return HighlightsPostProcess;
  91922. }(BABYLON.PostProcess));
  91923. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  91924. })(BABYLON || (BABYLON = {}));
  91925. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  91926. var BABYLON;
  91927. (function (BABYLON) {
  91928. /**
  91929. * ImageProcessingPostProcess
  91930. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses#imageprocessing
  91931. */
  91932. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  91933. __extends(ImageProcessingPostProcess, _super);
  91934. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  91935. if (camera === void 0) { camera = null; }
  91936. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  91937. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  91938. _this._fromLinearSpace = true;
  91939. /**
  91940. * Defines cache preventing GC.
  91941. */
  91942. _this._defines = {
  91943. IMAGEPROCESSING: false,
  91944. VIGNETTE: false,
  91945. VIGNETTEBLENDMODEMULTIPLY: false,
  91946. VIGNETTEBLENDMODEOPAQUE: false,
  91947. TONEMAPPING: false,
  91948. TONEMAPPING_ACES: false,
  91949. CONTRAST: false,
  91950. COLORCURVES: false,
  91951. COLORGRADING: false,
  91952. COLORGRADING3D: false,
  91953. FROMLINEARSPACE: false,
  91954. SAMPLER3DGREENDEPTH: false,
  91955. SAMPLER3DBGRMAP: false,
  91956. IMAGEPROCESSINGPOSTPROCESS: false,
  91957. EXPOSURE: false,
  91958. };
  91959. // Setup the configuration as forced by the constructor. This would then not force the
  91960. // scene materials output in linear space and let untouched the default forward pass.
  91961. if (imageProcessingConfiguration) {
  91962. imageProcessingConfiguration.applyByPostProcess = true;
  91963. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  91964. // This will cause the shader to be compiled
  91965. _this.fromLinearSpace = false;
  91966. }
  91967. // Setup the default processing configuration to the scene.
  91968. else {
  91969. _this._attachImageProcessingConfiguration(null, true);
  91970. _this.imageProcessingConfiguration.applyByPostProcess = true;
  91971. }
  91972. _this.onApply = function (effect) {
  91973. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  91974. };
  91975. return _this;
  91976. }
  91977. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  91978. /**
  91979. * Gets the image processing configuration used either in this material.
  91980. */
  91981. get: function () {
  91982. return this._imageProcessingConfiguration;
  91983. },
  91984. /**
  91985. * Sets the Default image processing configuration used either in the this material.
  91986. *
  91987. * If sets to null, the scene one is in use.
  91988. */
  91989. set: function (value) {
  91990. this._attachImageProcessingConfiguration(value);
  91991. },
  91992. enumerable: true,
  91993. configurable: true
  91994. });
  91995. /**
  91996. * Attaches a new image processing configuration to the PBR Material.
  91997. * @param configuration
  91998. */
  91999. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  92000. var _this = this;
  92001. if (doNotBuild === void 0) { doNotBuild = false; }
  92002. if (configuration === this._imageProcessingConfiguration) {
  92003. return;
  92004. }
  92005. // Detaches observer.
  92006. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  92007. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  92008. }
  92009. // Pick the scene configuration if needed.
  92010. if (!configuration) {
  92011. var scene = null;
  92012. var engine = this.getEngine();
  92013. var camera = this.getCamera();
  92014. if (camera) {
  92015. scene = camera.getScene();
  92016. }
  92017. else if (engine && engine.scenes) {
  92018. var scenes = engine.scenes;
  92019. scene = scenes[scenes.length - 1];
  92020. }
  92021. else {
  92022. scene = BABYLON.Engine.LastCreatedScene;
  92023. }
  92024. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  92025. }
  92026. else {
  92027. this._imageProcessingConfiguration = configuration;
  92028. }
  92029. // Attaches observer.
  92030. if (this._imageProcessingConfiguration) {
  92031. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  92032. _this._updateParameters();
  92033. });
  92034. }
  92035. // Ensure the effect will be rebuilt.
  92036. if (!doNotBuild) {
  92037. this._updateParameters();
  92038. }
  92039. };
  92040. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  92041. /**
  92042. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  92043. */
  92044. get: function () {
  92045. return this.imageProcessingConfiguration.colorCurves;
  92046. },
  92047. /**
  92048. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  92049. */
  92050. set: function (value) {
  92051. this.imageProcessingConfiguration.colorCurves = value;
  92052. },
  92053. enumerable: true,
  92054. configurable: true
  92055. });
  92056. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  92057. /**
  92058. * Gets wether the color curves effect is enabled.
  92059. */
  92060. get: function () {
  92061. return this.imageProcessingConfiguration.colorCurvesEnabled;
  92062. },
  92063. /**
  92064. * Sets wether the color curves effect is enabled.
  92065. */
  92066. set: function (value) {
  92067. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  92068. },
  92069. enumerable: true,
  92070. configurable: true
  92071. });
  92072. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  92073. /**
  92074. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  92075. */
  92076. get: function () {
  92077. return this.imageProcessingConfiguration.colorGradingTexture;
  92078. },
  92079. /**
  92080. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  92081. */
  92082. set: function (value) {
  92083. this.imageProcessingConfiguration.colorGradingTexture = value;
  92084. },
  92085. enumerable: true,
  92086. configurable: true
  92087. });
  92088. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  92089. /**
  92090. * Gets wether the color grading effect is enabled.
  92091. */
  92092. get: function () {
  92093. return this.imageProcessingConfiguration.colorGradingEnabled;
  92094. },
  92095. /**
  92096. * Gets wether the color grading effect is enabled.
  92097. */
  92098. set: function (value) {
  92099. this.imageProcessingConfiguration.colorGradingEnabled = value;
  92100. },
  92101. enumerable: true,
  92102. configurable: true
  92103. });
  92104. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  92105. /**
  92106. * Gets exposure used in the effect.
  92107. */
  92108. get: function () {
  92109. return this.imageProcessingConfiguration.exposure;
  92110. },
  92111. /**
  92112. * Sets exposure used in the effect.
  92113. */
  92114. set: function (value) {
  92115. this.imageProcessingConfiguration.exposure = value;
  92116. },
  92117. enumerable: true,
  92118. configurable: true
  92119. });
  92120. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  92121. /**
  92122. * Gets wether tonemapping is enabled or not.
  92123. */
  92124. get: function () {
  92125. return this._imageProcessingConfiguration.toneMappingEnabled;
  92126. },
  92127. /**
  92128. * Sets wether tonemapping is enabled or not
  92129. */
  92130. set: function (value) {
  92131. this._imageProcessingConfiguration.toneMappingEnabled = value;
  92132. },
  92133. enumerable: true,
  92134. configurable: true
  92135. });
  92136. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  92137. /**
  92138. * Gets contrast used in the effect.
  92139. */
  92140. get: function () {
  92141. return this.imageProcessingConfiguration.contrast;
  92142. },
  92143. /**
  92144. * Sets contrast used in the effect.
  92145. */
  92146. set: function (value) {
  92147. this.imageProcessingConfiguration.contrast = value;
  92148. },
  92149. enumerable: true,
  92150. configurable: true
  92151. });
  92152. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  92153. /**
  92154. * Gets Vignette stretch size.
  92155. */
  92156. get: function () {
  92157. return this.imageProcessingConfiguration.vignetteStretch;
  92158. },
  92159. /**
  92160. * Sets Vignette stretch size.
  92161. */
  92162. set: function (value) {
  92163. this.imageProcessingConfiguration.vignetteStretch = value;
  92164. },
  92165. enumerable: true,
  92166. configurable: true
  92167. });
  92168. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  92169. /**
  92170. * Gets Vignette centre X Offset.
  92171. */
  92172. get: function () {
  92173. return this.imageProcessingConfiguration.vignetteCentreX;
  92174. },
  92175. /**
  92176. * Sets Vignette centre X Offset.
  92177. */
  92178. set: function (value) {
  92179. this.imageProcessingConfiguration.vignetteCentreX = value;
  92180. },
  92181. enumerable: true,
  92182. configurable: true
  92183. });
  92184. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  92185. /**
  92186. * Gets Vignette centre Y Offset.
  92187. */
  92188. get: function () {
  92189. return this.imageProcessingConfiguration.vignetteCentreY;
  92190. },
  92191. /**
  92192. * Sets Vignette centre Y Offset.
  92193. */
  92194. set: function (value) {
  92195. this.imageProcessingConfiguration.vignetteCentreY = value;
  92196. },
  92197. enumerable: true,
  92198. configurable: true
  92199. });
  92200. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  92201. /**
  92202. * Gets Vignette weight or intensity of the vignette effect.
  92203. */
  92204. get: function () {
  92205. return this.imageProcessingConfiguration.vignetteWeight;
  92206. },
  92207. /**
  92208. * Sets Vignette weight or intensity of the vignette effect.
  92209. */
  92210. set: function (value) {
  92211. this.imageProcessingConfiguration.vignetteWeight = value;
  92212. },
  92213. enumerable: true,
  92214. configurable: true
  92215. });
  92216. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  92217. /**
  92218. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  92219. * if vignetteEnabled is set to true.
  92220. */
  92221. get: function () {
  92222. return this.imageProcessingConfiguration.vignetteColor;
  92223. },
  92224. /**
  92225. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  92226. * if vignetteEnabled is set to true.
  92227. */
  92228. set: function (value) {
  92229. this.imageProcessingConfiguration.vignetteColor = value;
  92230. },
  92231. enumerable: true,
  92232. configurable: true
  92233. });
  92234. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  92235. /**
  92236. * Gets Camera field of view used by the Vignette effect.
  92237. */
  92238. get: function () {
  92239. return this.imageProcessingConfiguration.vignetteCameraFov;
  92240. },
  92241. /**
  92242. * Sets Camera field of view used by the Vignette effect.
  92243. */
  92244. set: function (value) {
  92245. this.imageProcessingConfiguration.vignetteCameraFov = value;
  92246. },
  92247. enumerable: true,
  92248. configurable: true
  92249. });
  92250. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  92251. /**
  92252. * Gets the vignette blend mode allowing different kind of effect.
  92253. */
  92254. get: function () {
  92255. return this.imageProcessingConfiguration.vignetteBlendMode;
  92256. },
  92257. /**
  92258. * Sets the vignette blend mode allowing different kind of effect.
  92259. */
  92260. set: function (value) {
  92261. this.imageProcessingConfiguration.vignetteBlendMode = value;
  92262. },
  92263. enumerable: true,
  92264. configurable: true
  92265. });
  92266. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  92267. /**
  92268. * Gets wether the vignette effect is enabled.
  92269. */
  92270. get: function () {
  92271. return this.imageProcessingConfiguration.vignetteEnabled;
  92272. },
  92273. /**
  92274. * Sets wether the vignette effect is enabled.
  92275. */
  92276. set: function (value) {
  92277. this.imageProcessingConfiguration.vignetteEnabled = value;
  92278. },
  92279. enumerable: true,
  92280. configurable: true
  92281. });
  92282. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  92283. /**
  92284. * Gets wether the input of the processing is in Gamma or Linear Space.
  92285. */
  92286. get: function () {
  92287. return this._fromLinearSpace;
  92288. },
  92289. /**
  92290. * Sets wether the input of the processing is in Gamma or Linear Space.
  92291. */
  92292. set: function (value) {
  92293. if (this._fromLinearSpace === value) {
  92294. return;
  92295. }
  92296. this._fromLinearSpace = value;
  92297. this._updateParameters();
  92298. },
  92299. enumerable: true,
  92300. configurable: true
  92301. });
  92302. /**
  92303. * "ImageProcessingPostProcess"
  92304. * @returns "ImageProcessingPostProcess"
  92305. */
  92306. ImageProcessingPostProcess.prototype.getClassName = function () {
  92307. return "ImageProcessingPostProcess";
  92308. };
  92309. ImageProcessingPostProcess.prototype._updateParameters = function () {
  92310. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  92311. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  92312. var defines = "";
  92313. for (var define in this._defines) {
  92314. if (this._defines[define]) {
  92315. defines += "#define " + define + ";\r\n";
  92316. }
  92317. }
  92318. var samplers = ["textureSampler"];
  92319. var uniforms = ["scale"];
  92320. if (BABYLON.ImageProcessingConfiguration) {
  92321. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  92322. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  92323. }
  92324. this.updateEffect(defines, uniforms, samplers);
  92325. };
  92326. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  92327. _super.prototype.dispose.call(this, camera);
  92328. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  92329. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  92330. }
  92331. if (this._imageProcessingConfiguration) {
  92332. this.imageProcessingConfiguration.applyByPostProcess = false;
  92333. }
  92334. };
  92335. __decorate([
  92336. BABYLON.serialize()
  92337. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  92338. return ImageProcessingPostProcess;
  92339. }(BABYLON.PostProcess));
  92340. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  92341. })(BABYLON || (BABYLON = {}));
  92342. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  92343. var BABYLON;
  92344. (function (BABYLON) {
  92345. /**
  92346. * The Motion Blur Post Process which blurs an image based on the objects velocity in scene.
  92347. * Velocity can be affected by each object's rotation, position and scale depending on the transformation speed.
  92348. * As an example, all you have to do is to create the post-process:
  92349. * var mb = new BABYLON.MotionBlurPostProcess(
  92350. * 'mb', // The name of the effect.
  92351. * scene, // The scene containing the objects to blur according to their velocity.
  92352. * 1.0, // The required width/height ratio to downsize to before computing the render pass.
  92353. * camera // The camera to apply the render pass to.
  92354. * );
  92355. * Then, all objects moving, rotating and/or scaling will be blurred depending on the transformation speed.
  92356. */
  92357. var MotionBlurPostProcess = /** @class */ (function (_super) {
  92358. __extends(MotionBlurPostProcess, _super);
  92359. /**
  92360. * Creates a new instance MotionBlurPostProcess
  92361. * @param name The name of the effect.
  92362. * @param scene The scene containing the objects to blur according to their velocity.
  92363. * @param options The required width/height ratio to downsize to before computing the render pass.
  92364. * @param camera The camera to apply the render pass to.
  92365. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  92366. * @param engine The engine which the post process will be applied. (default: current engine)
  92367. * @param reusable If the post process can be reused on the same frame. (default: false)
  92368. * @param textureType Type of textures used when performing the post process. (default: 0)
  92369. * @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)
  92370. */
  92371. function MotionBlurPostProcess(name, scene, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  92372. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  92373. if (blockCompilation === void 0) { blockCompilation = false; }
  92374. var _this = _super.call(this, name, "motionBlur", ["motionStrength", "motionScale", "screenSize"], ["velocitySampler"], options, camera, samplingMode, engine, reusable, "#define GEOMETRY_SUPPORTED\n#define SAMPLES 64.0", textureType, undefined, null, blockCompilation) || this;
  92375. /**
  92376. * Defines how much the image is blurred by the movement. Default value is equal to 1
  92377. */
  92378. _this.motionStrength = 1;
  92379. _this._motionBlurSamples = 32;
  92380. _this._geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  92381. if (!_this._geometryBufferRenderer) {
  92382. // Geometry buffer renderer is not supported. So, work as a passthrough.
  92383. BABYLON.Tools.Warn("Multiple Render Target support needed to compute object based motion blur");
  92384. _this.updateEffect();
  92385. }
  92386. else {
  92387. // Geometry buffer renderer is supported.
  92388. _this._geometryBufferRenderer.enableVelocity = true;
  92389. _this.onApply = function (effect) {
  92390. effect.setVector2("screenSize", new BABYLON.Vector2(_this.width, _this.height));
  92391. effect.setFloat("motionScale", scene.getAnimationRatio());
  92392. effect.setFloat("motionStrength", _this.motionStrength);
  92393. if (_this._geometryBufferRenderer) {
  92394. var velocityIndex = _this._geometryBufferRenderer.getTextureIndex(BABYLON.GeometryBufferRenderer.VELOCITY_TEXTURE_TYPE);
  92395. effect.setTexture("velocitySampler", _this._geometryBufferRenderer.getGBuffer().textures[velocityIndex]);
  92396. }
  92397. };
  92398. }
  92399. return _this;
  92400. }
  92401. Object.defineProperty(MotionBlurPostProcess.prototype, "motionBlurSamples", {
  92402. /**
  92403. * Gets the number of iterations are used for motion blur quality. Default value is equal to 32
  92404. */
  92405. get: function () {
  92406. return this._motionBlurSamples;
  92407. },
  92408. /**
  92409. * Sets the number of iterations to be used for motion blur quality
  92410. */
  92411. set: function (samples) {
  92412. this._motionBlurSamples = samples;
  92413. if (this._geometryBufferRenderer) {
  92414. this.updateEffect("#define GEOMETRY_SUPPORTED\n#define SAMPLES " + samples.toFixed(1));
  92415. }
  92416. },
  92417. enumerable: true,
  92418. configurable: true
  92419. });
  92420. /**
  92421. * Disposes the post process.
  92422. * @param camera The camera to dispose the post process on.
  92423. */
  92424. MotionBlurPostProcess.prototype.dispose = function (camera) {
  92425. if (this._geometryBufferRenderer) {
  92426. // Clear previous transformation matrices dictionary used to compute objects velocities
  92427. this._geometryBufferRenderer._previousTransformationMatrices = {};
  92428. }
  92429. _super.prototype.dispose.call(this, camera);
  92430. };
  92431. return MotionBlurPostProcess;
  92432. }(BABYLON.PostProcess));
  92433. BABYLON.MotionBlurPostProcess = MotionBlurPostProcess;
  92434. })(BABYLON || (BABYLON = {}));
  92435. //# sourceMappingURL=babylon.motionBlurPostProcess.js.map
  92436. var BABYLON;
  92437. (function (BABYLON) {
  92438. /**
  92439. * Class used to store bone information
  92440. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  92441. */
  92442. var Bone = /** @class */ (function (_super) {
  92443. __extends(Bone, _super);
  92444. /**
  92445. * Create a new bone
  92446. * @param name defines the bone name
  92447. * @param skeleton defines the parent skeleton
  92448. * @param parentBone defines the parent (can be null if the bone is the root)
  92449. * @param localMatrix defines the local matrix
  92450. * @param restPose defines the rest pose matrix
  92451. * @param baseMatrix defines the base matrix
  92452. * @param index defines index of the bone in the hiearchy
  92453. */
  92454. function Bone(
  92455. /**
  92456. * defines the bone name
  92457. */
  92458. name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  92459. if (parentBone === void 0) { parentBone = null; }
  92460. if (localMatrix === void 0) { localMatrix = null; }
  92461. if (restPose === void 0) { restPose = null; }
  92462. if (baseMatrix === void 0) { baseMatrix = null; }
  92463. if (index === void 0) { index = null; }
  92464. var _this = _super.call(this, name, skeleton.getScene(), false) || this;
  92465. _this.name = name;
  92466. /**
  92467. * Gets the list of child bones
  92468. */
  92469. _this.children = new Array();
  92470. /** Gets the animations associated with this bone */
  92471. _this.animations = new Array();
  92472. /**
  92473. * @hidden Internal only
  92474. * Set this value to map this bone to a different index in the transform matrices
  92475. * Set this value to -1 to exclude the bone from the transform matrices
  92476. */
  92477. _this._index = null;
  92478. _this._absoluteTransform = new BABYLON.Matrix();
  92479. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  92480. _this._scalingDeterminant = 1;
  92481. _this._worldTransform = new BABYLON.Matrix();
  92482. _this._needToDecompose = true;
  92483. _this._needToCompose = false;
  92484. /** @hidden */
  92485. _this._linkedTransformNode = null;
  92486. _this._skeleton = skeleton;
  92487. _this._localMatrix = localMatrix ? localMatrix.clone() : BABYLON.Matrix.Identity();
  92488. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  92489. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  92490. _this._index = index;
  92491. skeleton.bones.push(_this);
  92492. _this.setParent(parentBone, false);
  92493. if (baseMatrix || localMatrix) {
  92494. _this._updateDifferenceMatrix();
  92495. }
  92496. return _this;
  92497. }
  92498. Object.defineProperty(Bone.prototype, "_matrix", {
  92499. /** @hidden */
  92500. get: function () {
  92501. this._compose();
  92502. return this._localMatrix;
  92503. },
  92504. /** @hidden */
  92505. set: function (value) {
  92506. this._localMatrix.copyFrom(value);
  92507. this._needToDecompose = true;
  92508. },
  92509. enumerable: true,
  92510. configurable: true
  92511. });
  92512. // Members
  92513. /**
  92514. * Gets the parent skeleton
  92515. * @returns a skeleton
  92516. */
  92517. Bone.prototype.getSkeleton = function () {
  92518. return this._skeleton;
  92519. };
  92520. /**
  92521. * Gets parent bone
  92522. * @returns a bone or null if the bone is the root of the bone hierarchy
  92523. */
  92524. Bone.prototype.getParent = function () {
  92525. return this._parent;
  92526. };
  92527. /**
  92528. * Sets the parent bone
  92529. * @param parent defines the parent (can be null if the bone is the root)
  92530. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  92531. */
  92532. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  92533. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  92534. if (this._parent === parent) {
  92535. return;
  92536. }
  92537. if (this._parent) {
  92538. var index = this._parent.children.indexOf(this);
  92539. if (index !== -1) {
  92540. this._parent.children.splice(index, 1);
  92541. }
  92542. }
  92543. this._parent = parent;
  92544. if (this._parent) {
  92545. this._parent.children.push(this);
  92546. }
  92547. if (updateDifferenceMatrix) {
  92548. this._updateDifferenceMatrix();
  92549. }
  92550. this.markAsDirty();
  92551. };
  92552. /**
  92553. * Gets the local matrix
  92554. * @returns a matrix
  92555. */
  92556. Bone.prototype.getLocalMatrix = function () {
  92557. this._compose();
  92558. return this._localMatrix;
  92559. };
  92560. /**
  92561. * Gets the base matrix (initial matrix which remains unchanged)
  92562. * @returns a matrix
  92563. */
  92564. Bone.prototype.getBaseMatrix = function () {
  92565. return this._baseMatrix;
  92566. };
  92567. /**
  92568. * Gets the rest pose matrix
  92569. * @returns a matrix
  92570. */
  92571. Bone.prototype.getRestPose = function () {
  92572. return this._restPose;
  92573. };
  92574. /**
  92575. * Gets a matrix used to store world matrix (ie. the matrix sent to shaders)
  92576. */
  92577. Bone.prototype.getWorldMatrix = function () {
  92578. return this._worldTransform;
  92579. };
  92580. /**
  92581. * Sets the local matrix to rest pose matrix
  92582. */
  92583. Bone.prototype.returnToRest = function () {
  92584. this.updateMatrix(this._restPose.clone());
  92585. };
  92586. /**
  92587. * Gets the inverse of the absolute transform matrix.
  92588. * This matrix will be multiplied by local matrix to get the difference matrix (ie. the difference between original state and current state)
  92589. * @returns a matrix
  92590. */
  92591. Bone.prototype.getInvertedAbsoluteTransform = function () {
  92592. return this._invertedAbsoluteTransform;
  92593. };
  92594. /**
  92595. * Gets the absolute transform matrix (ie base matrix * parent world matrix)
  92596. * @returns a matrix
  92597. */
  92598. Bone.prototype.getAbsoluteTransform = function () {
  92599. return this._absoluteTransform;
  92600. };
  92601. /**
  92602. * Links with the given transform node.
  92603. * The local matrix of this bone is copied from the transform node every frame.
  92604. * @param transformNode defines the transform node to link to
  92605. */
  92606. Bone.prototype.linkTransformNode = function (transformNode) {
  92607. if (this._linkedTransformNode) {
  92608. this._skeleton._numBonesWithLinkedTransformNode--;
  92609. }
  92610. this._linkedTransformNode = transformNode;
  92611. if (this._linkedTransformNode) {
  92612. this._skeleton._numBonesWithLinkedTransformNode++;
  92613. }
  92614. };
  92615. Object.defineProperty(Bone.prototype, "position", {
  92616. // Properties (matches AbstractMesh properties)
  92617. /** Gets or sets current position (in local space) */
  92618. get: function () {
  92619. this._decompose();
  92620. return this._localPosition;
  92621. },
  92622. set: function (newPosition) {
  92623. this._decompose();
  92624. this._localPosition.copyFrom(newPosition);
  92625. this._markAsDirtyAndCompose();
  92626. },
  92627. enumerable: true,
  92628. configurable: true
  92629. });
  92630. Object.defineProperty(Bone.prototype, "rotation", {
  92631. /** Gets or sets current rotation (in local space) */
  92632. get: function () {
  92633. return this.getRotation();
  92634. },
  92635. set: function (newRotation) {
  92636. this.setRotation(newRotation);
  92637. },
  92638. enumerable: true,
  92639. configurable: true
  92640. });
  92641. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  92642. /** Gets or sets current rotation quaternion (in local space) */
  92643. get: function () {
  92644. this._decompose();
  92645. return this._localRotation;
  92646. },
  92647. set: function (newRotation) {
  92648. this.setRotationQuaternion(newRotation);
  92649. },
  92650. enumerable: true,
  92651. configurable: true
  92652. });
  92653. Object.defineProperty(Bone.prototype, "scaling", {
  92654. /** Gets or sets current scaling (in local space) */
  92655. get: function () {
  92656. return this.getScale();
  92657. },
  92658. set: function (newScaling) {
  92659. this.setScale(newScaling);
  92660. },
  92661. enumerable: true,
  92662. configurable: true
  92663. });
  92664. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  92665. /**
  92666. * Gets the animation properties override
  92667. */
  92668. get: function () {
  92669. return this._skeleton.animationPropertiesOverride;
  92670. },
  92671. enumerable: true,
  92672. configurable: true
  92673. });
  92674. // Methods
  92675. Bone.prototype._decompose = function () {
  92676. if (!this._needToDecompose) {
  92677. return;
  92678. }
  92679. this._needToDecompose = false;
  92680. if (!this._localScaling) {
  92681. this._localScaling = BABYLON.Vector3.Zero();
  92682. this._localRotation = BABYLON.Quaternion.Zero();
  92683. this._localPosition = BABYLON.Vector3.Zero();
  92684. }
  92685. this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition);
  92686. };
  92687. Bone.prototype._compose = function () {
  92688. if (!this._needToCompose) {
  92689. return;
  92690. }
  92691. this._needToCompose = false;
  92692. BABYLON.Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix);
  92693. };
  92694. /**
  92695. * Update the base and local matrices
  92696. * @param matrix defines the new base or local matrix
  92697. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  92698. * @param updateLocalMatrix defines if the local matrix should be updated
  92699. */
  92700. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix, updateLocalMatrix) {
  92701. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  92702. if (updateLocalMatrix === void 0) { updateLocalMatrix = true; }
  92703. this._baseMatrix.copyFrom(matrix);
  92704. if (updateDifferenceMatrix) {
  92705. this._updateDifferenceMatrix();
  92706. }
  92707. if (updateLocalMatrix) {
  92708. this._localMatrix.copyFrom(matrix);
  92709. this._markAsDirtyAndDecompose();
  92710. }
  92711. else {
  92712. this.markAsDirty();
  92713. }
  92714. };
  92715. /** @hidden */
  92716. Bone.prototype._updateDifferenceMatrix = function (rootMatrix, updateChildren) {
  92717. if (updateChildren === void 0) { updateChildren = true; }
  92718. if (!rootMatrix) {
  92719. rootMatrix = this._baseMatrix;
  92720. }
  92721. if (this._parent) {
  92722. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  92723. }
  92724. else {
  92725. this._absoluteTransform.copyFrom(rootMatrix);
  92726. }
  92727. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  92728. if (updateChildren) {
  92729. for (var index = 0; index < this.children.length; index++) {
  92730. this.children[index]._updateDifferenceMatrix();
  92731. }
  92732. }
  92733. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  92734. };
  92735. /**
  92736. * Flag the bone as dirty (Forcing it to update everything)
  92737. */
  92738. Bone.prototype.markAsDirty = function () {
  92739. this._currentRenderId++;
  92740. this._childRenderId++;
  92741. this._skeleton._markAsDirty();
  92742. };
  92743. Bone.prototype._markAsDirtyAndCompose = function () {
  92744. this.markAsDirty();
  92745. this._needToCompose = true;
  92746. };
  92747. Bone.prototype._markAsDirtyAndDecompose = function () {
  92748. this.markAsDirty();
  92749. this._needToDecompose = true;
  92750. };
  92751. /**
  92752. * Copy an animation range from another bone
  92753. * @param source defines the source bone
  92754. * @param rangeName defines the range name to copy
  92755. * @param frameOffset defines the frame offset
  92756. * @param rescaleAsRequired defines if rescaling must be applied if required
  92757. * @param skelDimensionsRatio defines the scaling ratio
  92758. * @returns true if operation was successful
  92759. */
  92760. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  92761. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  92762. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  92763. // all animation may be coming from a library skeleton, so may need to create animation
  92764. if (this.animations.length === 0) {
  92765. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  92766. this.animations[0].setKeys([]);
  92767. }
  92768. // get animation info / verify there is such a range from the source bone
  92769. var sourceRange = source.animations[0].getRange(rangeName);
  92770. if (!sourceRange) {
  92771. return false;
  92772. }
  92773. var from = sourceRange.from;
  92774. var to = sourceRange.to;
  92775. var sourceKeys = source.animations[0].getKeys();
  92776. // rescaling prep
  92777. var sourceBoneLength = source.length;
  92778. var sourceParent = source.getParent();
  92779. var parent = this.getParent();
  92780. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  92781. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  92782. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  92783. var destKeys = this.animations[0].getKeys();
  92784. // loop vars declaration
  92785. var orig;
  92786. var origTranslation;
  92787. var mat;
  92788. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  92789. orig = sourceKeys[key];
  92790. if (orig.frame >= from && orig.frame <= to) {
  92791. if (rescaleAsRequired) {
  92792. mat = orig.value.clone();
  92793. // scale based on parent ratio, when bone has parent
  92794. if (parentScalingReqd) {
  92795. origTranslation = mat.getTranslation();
  92796. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  92797. // scale based on skeleton dimension ratio when root bone, and value is passed
  92798. }
  92799. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  92800. origTranslation = mat.getTranslation();
  92801. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  92802. // use original when root bone, and no data for skelDimensionsRatio
  92803. }
  92804. else {
  92805. mat = orig.value;
  92806. }
  92807. }
  92808. else {
  92809. mat = orig.value;
  92810. }
  92811. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  92812. }
  92813. }
  92814. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  92815. return true;
  92816. };
  92817. /**
  92818. * Translate the bone in local or world space
  92819. * @param vec The amount to translate the bone
  92820. * @param space The space that the translation is in
  92821. * @param mesh The mesh that this bone is attached to. This is only used in world space
  92822. */
  92823. Bone.prototype.translate = function (vec, space, mesh) {
  92824. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  92825. var lm = this.getLocalMatrix();
  92826. if (space == BABYLON.Space.LOCAL) {
  92827. lm.addAtIndex(12, vec.x);
  92828. lm.addAtIndex(13, vec.y);
  92829. lm.addAtIndex(14, vec.z);
  92830. }
  92831. else {
  92832. var wm = null;
  92833. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  92834. if (mesh) {
  92835. wm = mesh.getWorldMatrix();
  92836. }
  92837. this._skeleton.computeAbsoluteTransforms();
  92838. var tmat = Bone._tmpMats[0];
  92839. var tvec = Bone._tmpVecs[0];
  92840. if (this._parent) {
  92841. if (mesh && wm) {
  92842. tmat.copyFrom(this._parent.getAbsoluteTransform());
  92843. tmat.multiplyToRef(wm, tmat);
  92844. }
  92845. else {
  92846. tmat.copyFrom(this._parent.getAbsoluteTransform());
  92847. }
  92848. }
  92849. tmat.setTranslationFromFloats(0, 0, 0);
  92850. tmat.invert();
  92851. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  92852. lm.addAtIndex(12, tvec.x);
  92853. lm.addAtIndex(13, tvec.y);
  92854. lm.addAtIndex(14, tvec.z);
  92855. }
  92856. this._markAsDirtyAndDecompose();
  92857. };
  92858. /**
  92859. * Set the postion of the bone in local or world space
  92860. * @param position The position to set the bone
  92861. * @param space The space that the position is in
  92862. * @param mesh The mesh that this bone is attached to. This is only used in world space
  92863. */
  92864. Bone.prototype.setPosition = function (position, space, mesh) {
  92865. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  92866. var lm = this.getLocalMatrix();
  92867. if (space == BABYLON.Space.LOCAL) {
  92868. lm.setTranslationFromFloats(position.x, position.y, position.z);
  92869. }
  92870. else {
  92871. var wm = null;
  92872. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  92873. if (mesh) {
  92874. wm = mesh.getWorldMatrix();
  92875. }
  92876. this._skeleton.computeAbsoluteTransforms();
  92877. var tmat = Bone._tmpMats[0];
  92878. var vec = Bone._tmpVecs[0];
  92879. if (this._parent) {
  92880. if (mesh && wm) {
  92881. tmat.copyFrom(this._parent.getAbsoluteTransform());
  92882. tmat.multiplyToRef(wm, tmat);
  92883. }
  92884. else {
  92885. tmat.copyFrom(this._parent.getAbsoluteTransform());
  92886. }
  92887. }
  92888. tmat.invert();
  92889. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  92890. lm.setTranslationFromFloats(vec.x, vec.y, vec.z);
  92891. }
  92892. this._markAsDirtyAndDecompose();
  92893. };
  92894. /**
  92895. * Set the absolute position of the bone (world space)
  92896. * @param position The position to set the bone
  92897. * @param mesh The mesh that this bone is attached to
  92898. */
  92899. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  92900. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  92901. };
  92902. /**
  92903. * Scale the bone on the x, y and z axes (in local space)
  92904. * @param x The amount to scale the bone on the x axis
  92905. * @param y The amount to scale the bone on the y axis
  92906. * @param z The amount to scale the bone on the z axis
  92907. * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default)
  92908. */
  92909. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  92910. if (scaleChildren === void 0) { scaleChildren = false; }
  92911. var locMat = this.getLocalMatrix();
  92912. // Apply new scaling on top of current local matrix
  92913. var scaleMat = Bone._tmpMats[0];
  92914. BABYLON.Matrix.ScalingToRef(x, y, z, scaleMat);
  92915. scaleMat.multiplyToRef(locMat, locMat);
  92916. // Invert scaling matrix and apply the inverse to all children
  92917. scaleMat.invert();
  92918. for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
  92919. var child = _a[_i];
  92920. var cm = child.getLocalMatrix();
  92921. cm.multiplyToRef(scaleMat, cm);
  92922. cm.multiplyAtIndex(12, x);
  92923. cm.multiplyAtIndex(13, y);
  92924. cm.multiplyAtIndex(14, z);
  92925. child._markAsDirtyAndDecompose();
  92926. }
  92927. this._markAsDirtyAndDecompose();
  92928. if (scaleChildren) {
  92929. for (var _b = 0, _c = this.children; _b < _c.length; _b++) {
  92930. var child = _c[_b];
  92931. child.scale(x, y, z, scaleChildren);
  92932. }
  92933. }
  92934. };
  92935. /**
  92936. * Set the bone scaling in local space
  92937. * @param scale defines the scaling vector
  92938. */
  92939. Bone.prototype.setScale = function (scale) {
  92940. this._decompose();
  92941. this._localScaling.copyFrom(scale);
  92942. this._markAsDirtyAndCompose();
  92943. };
  92944. /**
  92945. * Gets the current scaling in local space
  92946. * @returns the current scaling vector
  92947. */
  92948. Bone.prototype.getScale = function () {
  92949. this._decompose();
  92950. return this._localScaling;
  92951. };
  92952. /**
  92953. * Gets the current scaling in local space and stores it in a target vector
  92954. * @param result defines the target vector
  92955. */
  92956. Bone.prototype.getScaleToRef = function (result) {
  92957. this._decompose();
  92958. result.copyFrom(this._localScaling);
  92959. };
  92960. /**
  92961. * Set the yaw, pitch, and roll of the bone in local or world space
  92962. * @param yaw The rotation of the bone on the y axis
  92963. * @param pitch The rotation of the bone on the x axis
  92964. * @param roll The rotation of the bone on the z axis
  92965. * @param space The space that the axes of rotation are in
  92966. * @param mesh The mesh that this bone is attached to. This is only used in world space
  92967. */
  92968. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  92969. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  92970. if (space === BABYLON.Space.LOCAL) {
  92971. var quat = Bone._tmpQuat;
  92972. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat);
  92973. this.setRotationQuaternion(quat, space, mesh);
  92974. return;
  92975. }
  92976. var rotMatInv = Bone._tmpMats[0];
  92977. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  92978. return;
  92979. }
  92980. var rotMat = Bone._tmpMats[1];
  92981. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  92982. rotMatInv.multiplyToRef(rotMat, rotMat);
  92983. this._rotateWithMatrix(rotMat, space, mesh);
  92984. };
  92985. /**
  92986. * Add a rotation to the bone on an axis in local or world space
  92987. * @param axis The axis to rotate the bone on
  92988. * @param amount The amount to rotate the bone
  92989. * @param space The space that the axis is in
  92990. * @param mesh The mesh that this bone is attached to. This is only used in world space
  92991. */
  92992. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  92993. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  92994. var rmat = Bone._tmpMats[0];
  92995. rmat.setTranslationFromFloats(0, 0, 0);
  92996. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  92997. this._rotateWithMatrix(rmat, space, mesh);
  92998. };
  92999. /**
  93000. * Set the rotation of the bone to a particular axis angle in local or world space
  93001. * @param axis The axis to rotate the bone on
  93002. * @param angle The angle that the bone should be rotated to
  93003. * @param space The space that the axis is in
  93004. * @param mesh The mesh that this bone is attached to. This is only used in world space
  93005. */
  93006. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  93007. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  93008. if (space === BABYLON.Space.LOCAL) {
  93009. var quat = Bone._tmpQuat;
  93010. BABYLON.Quaternion.RotationAxisToRef(axis, angle, quat);
  93011. this.setRotationQuaternion(quat, space, mesh);
  93012. return;
  93013. }
  93014. var rotMatInv = Bone._tmpMats[0];
  93015. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  93016. return;
  93017. }
  93018. var rotMat = Bone._tmpMats[1];
  93019. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  93020. rotMatInv.multiplyToRef(rotMat, rotMat);
  93021. this._rotateWithMatrix(rotMat, space, mesh);
  93022. };
  93023. /**
  93024. * Set the euler rotation of the bone in local of world space
  93025. * @param rotation The euler rotation that the bone should be set to
  93026. * @param space The space that the rotation is in
  93027. * @param mesh The mesh that this bone is attached to. This is only used in world space
  93028. */
  93029. Bone.prototype.setRotation = function (rotation, space, mesh) {
  93030. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  93031. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  93032. };
  93033. /**
  93034. * Set the quaternion rotation of the bone in local of world space
  93035. * @param quat The quaternion rotation that the bone should be set to
  93036. * @param space The space that the rotation is in
  93037. * @param mesh The mesh that this bone is attached to. This is only used in world space
  93038. */
  93039. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  93040. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  93041. if (space === BABYLON.Space.LOCAL) {
  93042. this._decompose();
  93043. this._localRotation.copyFrom(quat);
  93044. this._markAsDirtyAndCompose();
  93045. return;
  93046. }
  93047. var rotMatInv = Bone._tmpMats[0];
  93048. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  93049. return;
  93050. }
  93051. var rotMat = Bone._tmpMats[1];
  93052. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  93053. rotMatInv.multiplyToRef(rotMat, rotMat);
  93054. this._rotateWithMatrix(rotMat, space, mesh);
  93055. };
  93056. /**
  93057. * Set the rotation matrix of the bone in local of world space
  93058. * @param rotMat The rotation matrix that the bone should be set to
  93059. * @param space The space that the rotation is in
  93060. * @param mesh The mesh that this bone is attached to. This is only used in world space
  93061. */
  93062. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  93063. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  93064. if (space === BABYLON.Space.LOCAL) {
  93065. var quat = Bone._tmpQuat;
  93066. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, quat);
  93067. this.setRotationQuaternion(quat, space, mesh);
  93068. return;
  93069. }
  93070. var rotMatInv = Bone._tmpMats[0];
  93071. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  93072. return;
  93073. }
  93074. var rotMat2 = Bone._tmpMats[1];
  93075. rotMat2.copyFrom(rotMat);
  93076. rotMatInv.multiplyToRef(rotMat, rotMat2);
  93077. this._rotateWithMatrix(rotMat2, space, mesh);
  93078. };
  93079. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  93080. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  93081. var lmat = this.getLocalMatrix();
  93082. var lx = lmat.m[12];
  93083. var ly = lmat.m[13];
  93084. var lz = lmat.m[14];
  93085. var parent = this.getParent();
  93086. var parentScale = Bone._tmpMats[3];
  93087. var parentScaleInv = Bone._tmpMats[4];
  93088. if (parent && space == BABYLON.Space.WORLD) {
  93089. if (mesh) {
  93090. parentScale.copyFrom(mesh.getWorldMatrix());
  93091. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  93092. }
  93093. else {
  93094. parentScale.copyFrom(parent.getAbsoluteTransform());
  93095. }
  93096. parentScaleInv.copyFrom(parentScale);
  93097. parentScaleInv.invert();
  93098. lmat.multiplyToRef(parentScale, lmat);
  93099. lmat.multiplyToRef(rmat, lmat);
  93100. lmat.multiplyToRef(parentScaleInv, lmat);
  93101. }
  93102. else {
  93103. if (space == BABYLON.Space.WORLD && mesh) {
  93104. parentScale.copyFrom(mesh.getWorldMatrix());
  93105. parentScaleInv.copyFrom(parentScale);
  93106. parentScaleInv.invert();
  93107. lmat.multiplyToRef(parentScale, lmat);
  93108. lmat.multiplyToRef(rmat, lmat);
  93109. lmat.multiplyToRef(parentScaleInv, lmat);
  93110. }
  93111. else {
  93112. lmat.multiplyToRef(rmat, lmat);
  93113. }
  93114. }
  93115. lmat.setTranslationFromFloats(lx, ly, lz);
  93116. this.computeAbsoluteTransforms();
  93117. this._markAsDirtyAndDecompose();
  93118. };
  93119. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, mesh) {
  93120. var scaleMatrix = Bone._tmpMats[2];
  93121. rotMatInv.copyFrom(this.getAbsoluteTransform());
  93122. if (mesh) {
  93123. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  93124. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, scaleMatrix);
  93125. }
  93126. rotMatInv.invert();
  93127. if (isNaN(rotMatInv.m[0])) {
  93128. // Matrix failed to invert.
  93129. // This can happen if scale is zero for example.
  93130. return false;
  93131. }
  93132. scaleMatrix.multiplyAtIndex(0, this._scalingDeterminant);
  93133. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  93134. return true;
  93135. };
  93136. /**
  93137. * Get the position of the bone in local or world space
  93138. * @param space The space that the returned position is in
  93139. * @param mesh The mesh that this bone is attached to. This is only used in world space
  93140. * @returns The position of the bone
  93141. */
  93142. Bone.prototype.getPosition = function (space, mesh) {
  93143. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  93144. if (mesh === void 0) { mesh = null; }
  93145. var pos = BABYLON.Vector3.Zero();
  93146. this.getPositionToRef(space, mesh, pos);
  93147. return pos;
  93148. };
  93149. /**
  93150. * Copy the position of the bone to a vector3 in local or world space
  93151. * @param space The space that the returned position is in
  93152. * @param mesh The mesh that this bone is attached to. This is only used in world space
  93153. * @param result The vector3 to copy the position to
  93154. */
  93155. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  93156. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  93157. if (space == BABYLON.Space.LOCAL) {
  93158. var lm = this.getLocalMatrix();
  93159. result.x = lm.m[12];
  93160. result.y = lm.m[13];
  93161. result.z = lm.m[14];
  93162. }
  93163. else {
  93164. var wm = null;
  93165. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  93166. if (mesh) {
  93167. wm = mesh.getWorldMatrix();
  93168. }
  93169. this._skeleton.computeAbsoluteTransforms();
  93170. var tmat = Bone._tmpMats[0];
  93171. if (mesh && wm) {
  93172. tmat.copyFrom(this.getAbsoluteTransform());
  93173. tmat.multiplyToRef(wm, tmat);
  93174. }
  93175. else {
  93176. tmat = this.getAbsoluteTransform();
  93177. }
  93178. result.x = tmat.m[12];
  93179. result.y = tmat.m[13];
  93180. result.z = tmat.m[14];
  93181. }
  93182. };
  93183. /**
  93184. * Get the absolute position of the bone (world space)
  93185. * @param mesh The mesh that this bone is attached to
  93186. * @returns The absolute position of the bone
  93187. */
  93188. Bone.prototype.getAbsolutePosition = function (mesh) {
  93189. if (mesh === void 0) { mesh = null; }
  93190. var pos = BABYLON.Vector3.Zero();
  93191. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  93192. return pos;
  93193. };
  93194. /**
  93195. * Copy the absolute position of the bone (world space) to the result param
  93196. * @param mesh The mesh that this bone is attached to
  93197. * @param result The vector3 to copy the absolute position to
  93198. */
  93199. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  93200. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  93201. };
  93202. /**
  93203. * Compute the absolute transforms of this bone and its children
  93204. */
  93205. Bone.prototype.computeAbsoluteTransforms = function () {
  93206. this._compose();
  93207. if (this._parent) {
  93208. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  93209. }
  93210. else {
  93211. this._absoluteTransform.copyFrom(this._localMatrix);
  93212. var poseMatrix = this._skeleton.getPoseMatrix();
  93213. if (poseMatrix) {
  93214. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  93215. }
  93216. }
  93217. var children = this.children;
  93218. var len = children.length;
  93219. for (var i = 0; i < len; i++) {
  93220. children[i].computeAbsoluteTransforms();
  93221. }
  93222. };
  93223. /**
  93224. * Get the world direction from an axis that is in the local space of the bone
  93225. * @param localAxis The local direction that is used to compute the world direction
  93226. * @param mesh The mesh that this bone is attached to
  93227. * @returns The world direction
  93228. */
  93229. Bone.prototype.getDirection = function (localAxis, mesh) {
  93230. if (mesh === void 0) { mesh = null; }
  93231. var result = BABYLON.Vector3.Zero();
  93232. this.getDirectionToRef(localAxis, mesh, result);
  93233. return result;
  93234. };
  93235. /**
  93236. * Copy the world direction to a vector3 from an axis that is in the local space of the bone
  93237. * @param localAxis The local direction that is used to compute the world direction
  93238. * @param mesh The mesh that this bone is attached to
  93239. * @param result The vector3 that the world direction will be copied to
  93240. */
  93241. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  93242. if (mesh === void 0) { mesh = null; }
  93243. var wm = null;
  93244. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  93245. if (mesh) {
  93246. wm = mesh.getWorldMatrix();
  93247. }
  93248. this._skeleton.computeAbsoluteTransforms();
  93249. var mat = Bone._tmpMats[0];
  93250. mat.copyFrom(this.getAbsoluteTransform());
  93251. if (mesh && wm) {
  93252. mat.multiplyToRef(wm, mat);
  93253. }
  93254. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  93255. result.normalize();
  93256. };
  93257. /**
  93258. * Get the euler rotation of the bone in local or world space
  93259. * @param space The space that the rotation should be in
  93260. * @param mesh The mesh that this bone is attached to. This is only used in world space
  93261. * @returns The euler rotation
  93262. */
  93263. Bone.prototype.getRotation = function (space, mesh) {
  93264. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  93265. if (mesh === void 0) { mesh = null; }
  93266. var result = BABYLON.Vector3.Zero();
  93267. this.getRotationToRef(space, mesh, result);
  93268. return result;
  93269. };
  93270. /**
  93271. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space
  93272. * @param space The space that the rotation should be in
  93273. * @param mesh The mesh that this bone is attached to. This is only used in world space
  93274. * @param result The vector3 that the rotation should be copied to
  93275. */
  93276. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  93277. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  93278. if (mesh === void 0) { mesh = null; }
  93279. var quat = Bone._tmpQuat;
  93280. this.getRotationQuaternionToRef(space, mesh, quat);
  93281. quat.toEulerAnglesToRef(result);
  93282. };
  93283. /**
  93284. * Get the quaternion rotation of the bone in either local or world space
  93285. * @param space The space that the rotation should be in
  93286. * @param mesh The mesh that this bone is attached to. This is only used in world space
  93287. * @returns The quaternion rotation
  93288. */
  93289. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  93290. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  93291. if (mesh === void 0) { mesh = null; }
  93292. var result = BABYLON.Quaternion.Identity();
  93293. this.getRotationQuaternionToRef(space, mesh, result);
  93294. return result;
  93295. };
  93296. /**
  93297. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space
  93298. * @param space The space that the rotation should be in
  93299. * @param mesh The mesh that this bone is attached to. This is only used in world space
  93300. * @param result The quaternion that the rotation should be copied to
  93301. */
  93302. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  93303. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  93304. if (mesh === void 0) { mesh = null; }
  93305. if (space == BABYLON.Space.LOCAL) {
  93306. this._decompose();
  93307. result.copyFrom(this._localRotation);
  93308. }
  93309. else {
  93310. var mat = Bone._tmpMats[0];
  93311. var amat = this.getAbsoluteTransform();
  93312. if (mesh) {
  93313. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  93314. }
  93315. else {
  93316. mat.copyFrom(amat);
  93317. }
  93318. mat.multiplyAtIndex(0, this._scalingDeterminant);
  93319. mat.multiplyAtIndex(1, this._scalingDeterminant);
  93320. mat.multiplyAtIndex(2, this._scalingDeterminant);
  93321. mat.decompose(undefined, result, undefined);
  93322. }
  93323. };
  93324. /**
  93325. * Get the rotation matrix of the bone in local or world space
  93326. * @param space The space that the rotation should be in
  93327. * @param mesh The mesh that this bone is attached to. This is only used in world space
  93328. * @returns The rotation matrix
  93329. */
  93330. Bone.prototype.getRotationMatrix = function (space, mesh) {
  93331. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  93332. var result = BABYLON.Matrix.Identity();
  93333. this.getRotationMatrixToRef(space, mesh, result);
  93334. return result;
  93335. };
  93336. /**
  93337. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space
  93338. * @param space The space that the rotation should be in
  93339. * @param mesh The mesh that this bone is attached to. This is only used in world space
  93340. * @param result The quaternion that the rotation should be copied to
  93341. */
  93342. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  93343. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  93344. if (space == BABYLON.Space.LOCAL) {
  93345. this.getLocalMatrix().getRotationMatrixToRef(result);
  93346. }
  93347. else {
  93348. var mat = Bone._tmpMats[0];
  93349. var amat = this.getAbsoluteTransform();
  93350. if (mesh) {
  93351. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  93352. }
  93353. else {
  93354. mat.copyFrom(amat);
  93355. }
  93356. mat.multiplyAtIndex(0, this._scalingDeterminant);
  93357. mat.multiplyAtIndex(1, this._scalingDeterminant);
  93358. mat.multiplyAtIndex(2, this._scalingDeterminant);
  93359. mat.getRotationMatrixToRef(result);
  93360. }
  93361. };
  93362. /**
  93363. * Get the world position of a point that is in the local space of the bone
  93364. * @param position The local position
  93365. * @param mesh The mesh that this bone is attached to
  93366. * @returns The world position
  93367. */
  93368. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  93369. if (mesh === void 0) { mesh = null; }
  93370. var result = BABYLON.Vector3.Zero();
  93371. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  93372. return result;
  93373. };
  93374. /**
  93375. * Get the world position of a point that is in the local space of the bone and copy it to the result param
  93376. * @param position The local position
  93377. * @param mesh The mesh that this bone is attached to
  93378. * @param result The vector3 that the world position should be copied to
  93379. */
  93380. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  93381. if (mesh === void 0) { mesh = null; }
  93382. var wm = null;
  93383. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  93384. if (mesh) {
  93385. wm = mesh.getWorldMatrix();
  93386. }
  93387. this._skeleton.computeAbsoluteTransforms();
  93388. var tmat = Bone._tmpMats[0];
  93389. if (mesh && wm) {
  93390. tmat.copyFrom(this.getAbsoluteTransform());
  93391. tmat.multiplyToRef(wm, tmat);
  93392. }
  93393. else {
  93394. tmat = this.getAbsoluteTransform();
  93395. }
  93396. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  93397. };
  93398. /**
  93399. * Get the local position of a point that is in world space
  93400. * @param position The world position
  93401. * @param mesh The mesh that this bone is attached to
  93402. * @returns The local position
  93403. */
  93404. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  93405. if (mesh === void 0) { mesh = null; }
  93406. var result = BABYLON.Vector3.Zero();
  93407. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  93408. return result;
  93409. };
  93410. /**
  93411. * Get the local position of a point that is in world space and copy it to the result param
  93412. * @param position The world position
  93413. * @param mesh The mesh that this bone is attached to
  93414. * @param result The vector3 that the local position should be copied to
  93415. */
  93416. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  93417. if (mesh === void 0) { mesh = null; }
  93418. var wm = null;
  93419. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  93420. if (mesh) {
  93421. wm = mesh.getWorldMatrix();
  93422. }
  93423. this._skeleton.computeAbsoluteTransforms();
  93424. var tmat = Bone._tmpMats[0];
  93425. tmat.copyFrom(this.getAbsoluteTransform());
  93426. if (mesh && wm) {
  93427. tmat.multiplyToRef(wm, tmat);
  93428. }
  93429. tmat.invert();
  93430. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  93431. };
  93432. Bone._tmpVecs = BABYLON.Tools.BuildArray(2, BABYLON.Vector3.Zero);
  93433. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  93434. Bone._tmpMats = BABYLON.Tools.BuildArray(5, BABYLON.Matrix.Identity);
  93435. return Bone;
  93436. }(BABYLON.Node));
  93437. BABYLON.Bone = Bone;
  93438. })(BABYLON || (BABYLON = {}));
  93439. //# sourceMappingURL=babylon.bone.js.map
  93440. var BABYLON;
  93441. (function (BABYLON) {
  93442. /**
  93443. * Class used to apply inverse kinematics to bones
  93444. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#boneikcontroller
  93445. */
  93446. var BoneIKController = /** @class */ (function () {
  93447. /**
  93448. * Creates a new BoneIKController
  93449. * @param mesh defines the mesh to control
  93450. * @param bone defines the bone to control
  93451. * @param options defines options to set up the controller
  93452. */
  93453. function BoneIKController(mesh, bone, options) {
  93454. /**
  93455. * Gets or sets the target position
  93456. */
  93457. this.targetPosition = BABYLON.Vector3.Zero();
  93458. /**
  93459. * Gets or sets the pole target position
  93460. */
  93461. this.poleTargetPosition = BABYLON.Vector3.Zero();
  93462. /**
  93463. * Gets or sets the pole target local offset
  93464. */
  93465. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  93466. /**
  93467. * Gets or sets the pole angle
  93468. */
  93469. this.poleAngle = 0;
  93470. /**
  93471. * 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)
  93472. */
  93473. this.slerpAmount = 1;
  93474. this._bone1Quat = BABYLON.Quaternion.Identity();
  93475. this._bone1Mat = BABYLON.Matrix.Identity();
  93476. this._bone2Ang = Math.PI;
  93477. this._maxAngle = Math.PI;
  93478. this._rightHandedSystem = false;
  93479. this._bendAxis = BABYLON.Vector3.Right();
  93480. this._slerping = false;
  93481. this._adjustRoll = 0;
  93482. this._bone2 = bone;
  93483. this._bone1 = bone.getParent();
  93484. if (!this._bone1) {
  93485. return;
  93486. }
  93487. this.mesh = mesh;
  93488. var bonePos = bone.getPosition();
  93489. if (bone.getAbsoluteTransform().determinant() > 0) {
  93490. this._rightHandedSystem = true;
  93491. this._bendAxis.x = 0;
  93492. this._bendAxis.y = 0;
  93493. this._bendAxis.z = -1;
  93494. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  93495. this._adjustRoll = Math.PI * .5;
  93496. this._bendAxis.z = 1;
  93497. }
  93498. }
  93499. if (this._bone1.length) {
  93500. var boneScale1 = this._bone1.getScale();
  93501. var boneScale2 = this._bone2.getScale();
  93502. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  93503. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  93504. }
  93505. else if (this._bone1.children[0]) {
  93506. mesh.computeWorldMatrix(true);
  93507. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  93508. var pos2 = this._bone2.getAbsolutePosition(mesh);
  93509. var pos3 = this._bone1.getAbsolutePosition(mesh);
  93510. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  93511. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  93512. }
  93513. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  93514. this.maxAngle = Math.PI;
  93515. if (options) {
  93516. if (options.targetMesh) {
  93517. this.targetMesh = options.targetMesh;
  93518. this.targetMesh.computeWorldMatrix(true);
  93519. }
  93520. if (options.poleTargetMesh) {
  93521. this.poleTargetMesh = options.poleTargetMesh;
  93522. this.poleTargetMesh.computeWorldMatrix(true);
  93523. }
  93524. else if (options.poleTargetBone) {
  93525. this.poleTargetBone = options.poleTargetBone;
  93526. }
  93527. else if (this._bone1.getParent()) {
  93528. this.poleTargetBone = this._bone1.getParent();
  93529. }
  93530. if (options.poleTargetLocalOffset) {
  93531. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  93532. }
  93533. if (options.poleAngle) {
  93534. this.poleAngle = options.poleAngle;
  93535. }
  93536. if (options.bendAxis) {
  93537. this._bendAxis.copyFrom(options.bendAxis);
  93538. }
  93539. if (options.maxAngle) {
  93540. this.maxAngle = options.maxAngle;
  93541. }
  93542. if (options.slerpAmount) {
  93543. this.slerpAmount = options.slerpAmount;
  93544. }
  93545. }
  93546. }
  93547. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  93548. /**
  93549. * Gets or sets maximum allowed angle
  93550. */
  93551. get: function () {
  93552. return this._maxAngle;
  93553. },
  93554. set: function (value) {
  93555. this._setMaxAngle(value);
  93556. },
  93557. enumerable: true,
  93558. configurable: true
  93559. });
  93560. BoneIKController.prototype._setMaxAngle = function (ang) {
  93561. if (ang < 0) {
  93562. ang = 0;
  93563. }
  93564. if (ang > Math.PI || ang == undefined) {
  93565. ang = Math.PI;
  93566. }
  93567. this._maxAngle = ang;
  93568. var a = this._bone1Length;
  93569. var b = this._bone2Length;
  93570. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  93571. };
  93572. /**
  93573. * Force the controller to update the bones
  93574. */
  93575. BoneIKController.prototype.update = function () {
  93576. var bone1 = this._bone1;
  93577. if (!bone1) {
  93578. return;
  93579. }
  93580. var target = this.targetPosition;
  93581. var poleTarget = this.poleTargetPosition;
  93582. var mat1 = BoneIKController._tmpMats[0];
  93583. var mat2 = BoneIKController._tmpMats[1];
  93584. if (this.targetMesh) {
  93585. target.copyFrom(this.targetMesh.getAbsolutePosition());
  93586. }
  93587. if (this.poleTargetBone) {
  93588. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  93589. }
  93590. else if (this.poleTargetMesh) {
  93591. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  93592. }
  93593. var bonePos = BoneIKController._tmpVecs[0];
  93594. var zaxis = BoneIKController._tmpVecs[1];
  93595. var xaxis = BoneIKController._tmpVecs[2];
  93596. var yaxis = BoneIKController._tmpVecs[3];
  93597. var upAxis = BoneIKController._tmpVecs[4];
  93598. var _tmpQuat = BoneIKController._tmpQuat;
  93599. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  93600. poleTarget.subtractToRef(bonePos, upAxis);
  93601. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  93602. upAxis.y = 1;
  93603. }
  93604. else {
  93605. upAxis.normalize();
  93606. }
  93607. target.subtractToRef(bonePos, yaxis);
  93608. yaxis.normalize();
  93609. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  93610. zaxis.normalize();
  93611. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  93612. xaxis.normalize();
  93613. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  93614. var a = this._bone1Length;
  93615. var b = this._bone2Length;
  93616. var c = BABYLON.Vector3.Distance(bonePos, target);
  93617. if (this._maxReach > 0) {
  93618. c = Math.min(this._maxReach, c);
  93619. }
  93620. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  93621. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  93622. if (acosa > 1) {
  93623. acosa = 1;
  93624. }
  93625. if (acosb > 1) {
  93626. acosb = 1;
  93627. }
  93628. if (acosa < -1) {
  93629. acosa = -1;
  93630. }
  93631. if (acosb < -1) {
  93632. acosb = -1;
  93633. }
  93634. var angA = Math.acos(acosa);
  93635. var angB = Math.acos(acosb);
  93636. var angC = -angA - angB;
  93637. if (this._rightHandedSystem) {
  93638. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  93639. mat2.multiplyToRef(mat1, mat1);
  93640. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  93641. mat2.multiplyToRef(mat1, mat1);
  93642. }
  93643. else {
  93644. var _tmpVec = BoneIKController._tmpVecs[5];
  93645. _tmpVec.copyFrom(this._bendAxis);
  93646. _tmpVec.x *= -1;
  93647. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  93648. mat2.multiplyToRef(mat1, mat1);
  93649. }
  93650. if (this.poleAngle) {
  93651. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  93652. mat1.multiplyToRef(mat2, mat1);
  93653. }
  93654. if (this._bone1) {
  93655. if (this.slerpAmount < 1) {
  93656. if (!this._slerping) {
  93657. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  93658. }
  93659. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  93660. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  93661. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  93662. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  93663. this._slerping = true;
  93664. }
  93665. else {
  93666. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  93667. this._bone1Mat.copyFrom(mat1);
  93668. this._slerping = false;
  93669. }
  93670. }
  93671. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  93672. this._bone2Ang = angC;
  93673. };
  93674. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  93675. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  93676. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  93677. return BoneIKController;
  93678. }());
  93679. BABYLON.BoneIKController = BoneIKController;
  93680. })(BABYLON || (BABYLON = {}));
  93681. //# sourceMappingURL=babylon.boneIKController.js.map
  93682. var BABYLON;
  93683. (function (BABYLON) {
  93684. /**
  93685. * Class used to make a bone look toward a point in space
  93686. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#bonelookcontroller
  93687. */
  93688. var BoneLookController = /** @class */ (function () {
  93689. /**
  93690. * Create a BoneLookController
  93691. * @param mesh the mesh that the bone belongs to
  93692. * @param bone the bone that will be looking to the target
  93693. * @param target the target Vector3 to look at
  93694. * @param settings optional settings:
  93695. * * maxYaw: the maximum angle the bone will yaw to
  93696. * * minYaw: the minimum angle the bone will yaw to
  93697. * * maxPitch: the maximum angle the bone will pitch to
  93698. * * minPitch: the minimum angle the bone will yaw to
  93699. * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  93700. * * upAxis: the up axis of the coordinate system
  93701. * * upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  93702. * * yawAxis: set yawAxis if the bone does not yaw on the y axis
  93703. * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  93704. * * adjustYaw: used to make an adjustment to the yaw of the bone
  93705. * * adjustPitch: used to make an adjustment to the pitch of the bone
  93706. * * adjustRoll: used to make an adjustment to the roll of the bone
  93707. **/
  93708. function BoneLookController(mesh, bone, target, options) {
  93709. /**
  93710. * The up axis of the coordinate system that is used when the bone is rotated
  93711. */
  93712. this.upAxis = BABYLON.Vector3.Up();
  93713. /**
  93714. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD
  93715. */
  93716. this.upAxisSpace = BABYLON.Space.LOCAL;
  93717. /**
  93718. * Used to make an adjustment to the yaw of the bone
  93719. */
  93720. this.adjustYaw = 0;
  93721. /**
  93722. * Used to make an adjustment to the pitch of the bone
  93723. */
  93724. this.adjustPitch = 0;
  93725. /**
  93726. * Used to make an adjustment to the roll of the bone
  93727. */
  93728. this.adjustRoll = 0;
  93729. /**
  93730. * 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)
  93731. */
  93732. this.slerpAmount = 1;
  93733. this._boneQuat = BABYLON.Quaternion.Identity();
  93734. this._slerping = false;
  93735. this._firstFrameSkipped = false;
  93736. this._fowardAxis = BABYLON.Vector3.Forward();
  93737. this.mesh = mesh;
  93738. this.bone = bone;
  93739. this.target = target;
  93740. if (options) {
  93741. if (options.adjustYaw) {
  93742. this.adjustYaw = options.adjustYaw;
  93743. }
  93744. if (options.adjustPitch) {
  93745. this.adjustPitch = options.adjustPitch;
  93746. }
  93747. if (options.adjustRoll) {
  93748. this.adjustRoll = options.adjustRoll;
  93749. }
  93750. if (options.maxYaw != null) {
  93751. this.maxYaw = options.maxYaw;
  93752. }
  93753. else {
  93754. this.maxYaw = Math.PI;
  93755. }
  93756. if (options.minYaw != null) {
  93757. this.minYaw = options.minYaw;
  93758. }
  93759. else {
  93760. this.minYaw = -Math.PI;
  93761. }
  93762. if (options.maxPitch != null) {
  93763. this.maxPitch = options.maxPitch;
  93764. }
  93765. else {
  93766. this.maxPitch = Math.PI;
  93767. }
  93768. if (options.minPitch != null) {
  93769. this.minPitch = options.minPitch;
  93770. }
  93771. else {
  93772. this.minPitch = -Math.PI;
  93773. }
  93774. if (options.slerpAmount != null) {
  93775. this.slerpAmount = options.slerpAmount;
  93776. }
  93777. if (options.upAxis != null) {
  93778. this.upAxis = options.upAxis;
  93779. }
  93780. if (options.upAxisSpace != null) {
  93781. this.upAxisSpace = options.upAxisSpace;
  93782. }
  93783. if (options.yawAxis != null || options.pitchAxis != null) {
  93784. var newYawAxis = BABYLON.Axis.Y;
  93785. var newPitchAxis = BABYLON.Axis.X;
  93786. if (options.yawAxis != null) {
  93787. newYawAxis = options.yawAxis.clone();
  93788. newYawAxis.normalize();
  93789. }
  93790. if (options.pitchAxis != null) {
  93791. newPitchAxis = options.pitchAxis.clone();
  93792. newPitchAxis.normalize();
  93793. }
  93794. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  93795. this._transformYawPitch = BABYLON.Matrix.Identity();
  93796. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  93797. this._transformYawPitchInv = this._transformYawPitch.clone();
  93798. this._transformYawPitch.invert();
  93799. }
  93800. }
  93801. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  93802. this.upAxisSpace = BABYLON.Space.LOCAL;
  93803. }
  93804. }
  93805. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  93806. /**
  93807. * Gets or sets the minimum yaw angle that the bone can look to
  93808. */
  93809. get: function () {
  93810. return this._minYaw;
  93811. },
  93812. set: function (value) {
  93813. this._minYaw = value;
  93814. this._minYawSin = Math.sin(value);
  93815. this._minYawCos = Math.cos(value);
  93816. if (this._maxYaw != null) {
  93817. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  93818. this._yawRange = this._maxYaw - this._minYaw;
  93819. }
  93820. },
  93821. enumerable: true,
  93822. configurable: true
  93823. });
  93824. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  93825. /**
  93826. * Gets or sets the maximum yaw angle that the bone can look to
  93827. */
  93828. get: function () {
  93829. return this._maxYaw;
  93830. },
  93831. set: function (value) {
  93832. this._maxYaw = value;
  93833. this._maxYawSin = Math.sin(value);
  93834. this._maxYawCos = Math.cos(value);
  93835. if (this._minYaw != null) {
  93836. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  93837. this._yawRange = this._maxYaw - this._minYaw;
  93838. }
  93839. },
  93840. enumerable: true,
  93841. configurable: true
  93842. });
  93843. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  93844. /**
  93845. * Gets or sets the minimum pitch angle that the bone can look to
  93846. */
  93847. get: function () {
  93848. return this._minPitch;
  93849. },
  93850. set: function (value) {
  93851. this._minPitch = value;
  93852. this._minPitchTan = Math.tan(value);
  93853. },
  93854. enumerable: true,
  93855. configurable: true
  93856. });
  93857. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  93858. /**
  93859. * Gets or sets the maximum pitch angle that the bone can look to
  93860. */
  93861. get: function () {
  93862. return this._maxPitch;
  93863. },
  93864. set: function (value) {
  93865. this._maxPitch = value;
  93866. this._maxPitchTan = Math.tan(value);
  93867. },
  93868. enumerable: true,
  93869. configurable: true
  93870. });
  93871. /**
  93872. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender())
  93873. */
  93874. BoneLookController.prototype.update = function () {
  93875. //skip the first frame when slerping so that the mesh rotation is correct
  93876. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  93877. this._firstFrameSkipped = true;
  93878. return;
  93879. }
  93880. var bone = this.bone;
  93881. var bonePos = BoneLookController._tmpVecs[0];
  93882. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  93883. var target = this.target;
  93884. var _tmpMat1 = BoneLookController._tmpMats[0];
  93885. var _tmpMat2 = BoneLookController._tmpMats[1];
  93886. var mesh = this.mesh;
  93887. var parentBone = bone.getParent();
  93888. var upAxis = BoneLookController._tmpVecs[1];
  93889. upAxis.copyFrom(this.upAxis);
  93890. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  93891. if (this._transformYawPitch) {
  93892. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  93893. }
  93894. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  93895. }
  93896. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  93897. mesh.getDirectionToRef(upAxis, upAxis);
  93898. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  93899. upAxis.normalize();
  93900. }
  93901. }
  93902. var checkYaw = false;
  93903. var checkPitch = false;
  93904. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  93905. checkYaw = true;
  93906. }
  93907. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  93908. checkPitch = true;
  93909. }
  93910. if (checkYaw || checkPitch) {
  93911. var spaceMat = BoneLookController._tmpMats[2];
  93912. var spaceMatInv = BoneLookController._tmpMats[3];
  93913. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  93914. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  93915. }
  93916. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  93917. spaceMat.copyFrom(mesh.getWorldMatrix());
  93918. }
  93919. else {
  93920. var forwardAxis = BoneLookController._tmpVecs[2];
  93921. forwardAxis.copyFrom(this._fowardAxis);
  93922. if (this._transformYawPitch) {
  93923. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  93924. }
  93925. if (parentBone) {
  93926. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  93927. }
  93928. else {
  93929. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  93930. }
  93931. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  93932. rightAxis.normalize();
  93933. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  93934. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  93935. }
  93936. spaceMat.invertToRef(spaceMatInv);
  93937. var xzlen = null;
  93938. if (checkPitch) {
  93939. var localTarget = BoneLookController._tmpVecs[3];
  93940. target.subtractToRef(bonePos, localTarget);
  93941. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  93942. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  93943. var pitch = Math.atan2(localTarget.y, xzlen);
  93944. var newPitch = pitch;
  93945. if (pitch > this._maxPitch) {
  93946. localTarget.y = this._maxPitchTan * xzlen;
  93947. newPitch = this._maxPitch;
  93948. }
  93949. else if (pitch < this._minPitch) {
  93950. localTarget.y = this._minPitchTan * xzlen;
  93951. newPitch = this._minPitch;
  93952. }
  93953. if (pitch != newPitch) {
  93954. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  93955. localTarget.addInPlace(bonePos);
  93956. target = localTarget;
  93957. }
  93958. }
  93959. if (checkYaw) {
  93960. var localTarget = BoneLookController._tmpVecs[4];
  93961. target.subtractToRef(bonePos, localTarget);
  93962. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  93963. var yaw = Math.atan2(localTarget.x, localTarget.z);
  93964. var newYaw = yaw;
  93965. if (yaw > this._maxYaw || yaw < this._minYaw) {
  93966. if (xzlen == null) {
  93967. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  93968. }
  93969. if (this._yawRange > Math.PI) {
  93970. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  93971. localTarget.z = this._maxYawCos * xzlen;
  93972. localTarget.x = this._maxYawSin * xzlen;
  93973. newYaw = this._maxYaw;
  93974. }
  93975. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  93976. localTarget.z = this._minYawCos * xzlen;
  93977. localTarget.x = this._minYawSin * xzlen;
  93978. newYaw = this._minYaw;
  93979. }
  93980. }
  93981. else {
  93982. if (yaw > this._maxYaw) {
  93983. localTarget.z = this._maxYawCos * xzlen;
  93984. localTarget.x = this._maxYawSin * xzlen;
  93985. newYaw = this._maxYaw;
  93986. }
  93987. else if (yaw < this._minYaw) {
  93988. localTarget.z = this._minYawCos * xzlen;
  93989. localTarget.x = this._minYawSin * xzlen;
  93990. newYaw = this._minYaw;
  93991. }
  93992. }
  93993. }
  93994. if (this._slerping && this._yawRange > Math.PI) {
  93995. //are we going to be crossing into the min/max region?
  93996. var boneFwd = BoneLookController._tmpVecs[8];
  93997. boneFwd.copyFrom(BABYLON.Axis.Z);
  93998. if (this._transformYawPitch) {
  93999. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  94000. }
  94001. var boneRotMat = BoneLookController._tmpMats[4];
  94002. this._boneQuat.toRotationMatrix(boneRotMat);
  94003. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  94004. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  94005. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  94006. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  94007. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  94008. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  94009. if (angBtwTar > angBtwMidYaw) {
  94010. if (xzlen == null) {
  94011. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  94012. }
  94013. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  94014. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  94015. if (angBtwMin < angBtwMax) {
  94016. newYaw = boneYaw + Math.PI * .75;
  94017. localTarget.z = Math.cos(newYaw) * xzlen;
  94018. localTarget.x = Math.sin(newYaw) * xzlen;
  94019. }
  94020. else {
  94021. newYaw = boneYaw - Math.PI * .75;
  94022. localTarget.z = Math.cos(newYaw) * xzlen;
  94023. localTarget.x = Math.sin(newYaw) * xzlen;
  94024. }
  94025. }
  94026. }
  94027. if (yaw != newYaw) {
  94028. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  94029. localTarget.addInPlace(bonePos);
  94030. target = localTarget;
  94031. }
  94032. }
  94033. }
  94034. var zaxis = BoneLookController._tmpVecs[5];
  94035. var xaxis = BoneLookController._tmpVecs[6];
  94036. var yaxis = BoneLookController._tmpVecs[7];
  94037. var _tmpQuat = BoneLookController._tmpQuat;
  94038. target.subtractToRef(bonePos, zaxis);
  94039. zaxis.normalize();
  94040. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  94041. xaxis.normalize();
  94042. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  94043. yaxis.normalize();
  94044. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  94045. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  94046. return;
  94047. }
  94048. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  94049. return;
  94050. }
  94051. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  94052. return;
  94053. }
  94054. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  94055. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  94056. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  94057. }
  94058. if (this.slerpAmount < 1) {
  94059. if (!this._slerping) {
  94060. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  94061. }
  94062. if (this._transformYawPitch) {
  94063. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  94064. }
  94065. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  94066. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  94067. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  94068. this._slerping = true;
  94069. }
  94070. else {
  94071. if (this._transformYawPitch) {
  94072. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  94073. }
  94074. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  94075. this._slerping = false;
  94076. }
  94077. };
  94078. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  94079. var angDiff = ang2 - ang1;
  94080. angDiff %= Math.PI * 2;
  94081. if (angDiff > Math.PI) {
  94082. angDiff -= Math.PI * 2;
  94083. }
  94084. else if (angDiff < -Math.PI) {
  94085. angDiff += Math.PI * 2;
  94086. }
  94087. return angDiff;
  94088. };
  94089. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  94090. ang1 %= (2 * Math.PI);
  94091. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  94092. ang2 %= (2 * Math.PI);
  94093. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  94094. var ab = 0;
  94095. if (ang1 < ang2) {
  94096. ab = ang2 - ang1;
  94097. }
  94098. else {
  94099. ab = ang1 - ang2;
  94100. }
  94101. if (ab > Math.PI) {
  94102. ab = Math.PI * 2 - ab;
  94103. }
  94104. return ab;
  94105. };
  94106. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  94107. ang %= (2 * Math.PI);
  94108. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  94109. ang1 %= (2 * Math.PI);
  94110. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  94111. ang2 %= (2 * Math.PI);
  94112. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  94113. if (ang1 < ang2) {
  94114. if (ang > ang1 && ang < ang2) {
  94115. return true;
  94116. }
  94117. }
  94118. else {
  94119. if (ang > ang2 && ang < ang1) {
  94120. return true;
  94121. }
  94122. }
  94123. return false;
  94124. };
  94125. BoneLookController._tmpVecs = BABYLON.Tools.BuildArray(10, BABYLON.Vector3.Zero);
  94126. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  94127. BoneLookController._tmpMats = BABYLON.Tools.BuildArray(5, BABYLON.Matrix.Identity);
  94128. return BoneLookController;
  94129. }());
  94130. BABYLON.BoneLookController = BoneLookController;
  94131. })(BABYLON || (BABYLON = {}));
  94132. //# sourceMappingURL=babylon.boneLookController.js.map
  94133. var BABYLON;
  94134. (function (BABYLON) {
  94135. /**
  94136. * Class used to handle skinning animations
  94137. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  94138. */
  94139. var Skeleton = /** @class */ (function () {
  94140. /**
  94141. * Creates a new skeleton
  94142. * @param name defines the skeleton name
  94143. * @param id defines the skeleton Id
  94144. * @param scene defines the hosting scene
  94145. */
  94146. function Skeleton(
  94147. /** defines the skeleton name */
  94148. name,
  94149. /** defines the skeleton Id */
  94150. id, scene) {
  94151. this.name = name;
  94152. this.id = id;
  94153. /**
  94154. * Defines the list of child bones
  94155. */
  94156. this.bones = new Array();
  94157. /**
  94158. * Defines a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value)
  94159. */
  94160. this.needInitialSkinMatrix = false;
  94161. /**
  94162. * Defines a mesh that override the matrix used to get the world matrix (null by default).
  94163. */
  94164. this.overrideMesh = null;
  94165. this._isDirty = true;
  94166. this._meshesWithPoseMatrix = new Array();
  94167. this._identity = BABYLON.Matrix.Identity();
  94168. this._ranges = {};
  94169. this._lastAbsoluteTransformsUpdateId = -1;
  94170. this._canUseTextureForBones = false;
  94171. /** @hidden */
  94172. this._numBonesWithLinkedTransformNode = 0;
  94173. /**
  94174. * Specifies if the skeleton should be serialized
  94175. */
  94176. this.doNotSerialize = false;
  94177. /**
  94178. * Gets or sets a boolean indicating that bone matrices should be stored as a texture instead of using shader uniforms (default is true).
  94179. * Please note that this option is not available when needInitialSkinMatrix === true or if the hardware does not support it
  94180. */
  94181. this.useTextureToStoreBoneMatrices = true;
  94182. this._animationPropertiesOverride = null;
  94183. // Events
  94184. /**
  94185. * An observable triggered before computing the skeleton's matrices
  94186. */
  94187. this.onBeforeComputeObservable = new BABYLON.Observable();
  94188. this.bones = [];
  94189. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  94190. this._scene.skeletons.push(this);
  94191. //make sure it will recalculate the matrix next time prepare is called.
  94192. this._isDirty = true;
  94193. var engineCaps = this._scene.getEngine().getCaps();
  94194. this._canUseTextureForBones = engineCaps.textureFloat && engineCaps.maxVertexTextureImageUnits > 0;
  94195. }
  94196. Object.defineProperty(Skeleton.prototype, "animationPropertiesOverride", {
  94197. /**
  94198. * Gets or sets the animation properties override
  94199. */
  94200. get: function () {
  94201. if (!this._animationPropertiesOverride) {
  94202. return this._scene.animationPropertiesOverride;
  94203. }
  94204. return this._animationPropertiesOverride;
  94205. },
  94206. set: function (value) {
  94207. this._animationPropertiesOverride = value;
  94208. },
  94209. enumerable: true,
  94210. configurable: true
  94211. });
  94212. Object.defineProperty(Skeleton.prototype, "isUsingTextureForMatrices", {
  94213. /**
  94214. * Gets a boolean indicating that the skeleton effectively stores matrices into a texture
  94215. */
  94216. get: function () {
  94217. return this.useTextureToStoreBoneMatrices && this._canUseTextureForBones && !this.needInitialSkinMatrix;
  94218. },
  94219. enumerable: true,
  94220. configurable: true
  94221. });
  94222. // Members
  94223. /**
  94224. * Gets the list of transform matrices to send to shaders (one matrix per bone)
  94225. * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)
  94226. * @returns a Float32Array containing matrices data
  94227. */
  94228. Skeleton.prototype.getTransformMatrices = function (mesh) {
  94229. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  94230. return mesh._bonesTransformMatrices;
  94231. }
  94232. if (!this._transformMatrices) {
  94233. this.prepare();
  94234. }
  94235. return this._transformMatrices;
  94236. };
  94237. /**
  94238. * Gets the list of transform matrices to send to shaders inside a texture (one matrix per bone)
  94239. * @returns a raw texture containing the data
  94240. */
  94241. Skeleton.prototype.getTransformMatrixTexture = function () {
  94242. return this._transformMatrixTexture;
  94243. };
  94244. /**
  94245. * Gets the current hosting scene
  94246. * @returns a scene object
  94247. */
  94248. Skeleton.prototype.getScene = function () {
  94249. return this._scene;
  94250. };
  94251. // Methods
  94252. /**
  94253. * Gets a string representing the current skeleton data
  94254. * @param fullDetails defines a boolean indicating if we want a verbose version
  94255. * @returns a string representing the current skeleton data
  94256. */
  94257. Skeleton.prototype.toString = function (fullDetails) {
  94258. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  94259. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  94260. if (fullDetails) {
  94261. ret += ", Ranges: {";
  94262. var first = true;
  94263. for (var name_1 in this._ranges) {
  94264. if (first) {
  94265. ret += ", ";
  94266. first = false;
  94267. }
  94268. ret += name_1;
  94269. }
  94270. ret += "}";
  94271. }
  94272. return ret;
  94273. };
  94274. /**
  94275. * Get bone's index searching by name
  94276. * @param name defines bone's name to search for
  94277. * @return the indice of the bone. Returns -1 if not found
  94278. */
  94279. Skeleton.prototype.getBoneIndexByName = function (name) {
  94280. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  94281. if (this.bones[boneIndex].name === name) {
  94282. return boneIndex;
  94283. }
  94284. }
  94285. return -1;
  94286. };
  94287. /**
  94288. * Creater a new animation range
  94289. * @param name defines the name of the range
  94290. * @param from defines the start key
  94291. * @param to defines the end key
  94292. */
  94293. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  94294. // check name not already in use
  94295. if (!this._ranges[name]) {
  94296. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  94297. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  94298. if (this.bones[i].animations[0]) {
  94299. this.bones[i].animations[0].createRange(name, from, to);
  94300. }
  94301. }
  94302. }
  94303. };
  94304. /**
  94305. * Delete a specific animation range
  94306. * @param name defines the name of the range
  94307. * @param deleteFrames defines if frames must be removed as well
  94308. */
  94309. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  94310. if (deleteFrames === void 0) { deleteFrames = true; }
  94311. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  94312. if (this.bones[i].animations[0]) {
  94313. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  94314. }
  94315. }
  94316. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  94317. };
  94318. /**
  94319. * Gets a specific animation range
  94320. * @param name defines the name of the range to look for
  94321. * @returns the requested animation range or null if not found
  94322. */
  94323. Skeleton.prototype.getAnimationRange = function (name) {
  94324. return this._ranges[name];
  94325. };
  94326. /**
  94327. * Gets the list of all animation ranges defined on this skeleton
  94328. * @returns an array
  94329. */
  94330. Skeleton.prototype.getAnimationRanges = function () {
  94331. var animationRanges = [];
  94332. var name;
  94333. var i = 0;
  94334. for (name in this._ranges) {
  94335. animationRanges[i] = this._ranges[name];
  94336. i++;
  94337. }
  94338. return animationRanges;
  94339. };
  94340. /**
  94341. * Copy animation range from a source skeleton.
  94342. * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  94343. * @param source defines the source skeleton
  94344. * @param name defines the name of the range to copy
  94345. * @param rescaleAsRequired defines if rescaling must be applied if required
  94346. * @returns true if operation was successful
  94347. */
  94348. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  94349. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  94350. if (this._ranges[name] || !source.getAnimationRange(name)) {
  94351. return false;
  94352. }
  94353. var ret = true;
  94354. var frameOffset = this._getHighestAnimationFrame() + 1;
  94355. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  94356. var boneDict = {};
  94357. var sourceBones = source.bones;
  94358. var nBones;
  94359. var i;
  94360. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  94361. boneDict[sourceBones[i].name] = sourceBones[i];
  94362. }
  94363. if (this.bones.length !== sourceBones.length) {
  94364. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  94365. ret = false;
  94366. }
  94367. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  94368. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  94369. var boneName = this.bones[i].name;
  94370. var sourceBone = boneDict[boneName];
  94371. if (sourceBone) {
  94372. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  94373. }
  94374. else {
  94375. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  94376. ret = false;
  94377. }
  94378. }
  94379. // do not call createAnimationRange(), since it also is done to bones, which was already done
  94380. var range = source.getAnimationRange(name);
  94381. if (range) {
  94382. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  94383. }
  94384. return ret;
  94385. };
  94386. /**
  94387. * Forces the skeleton to go to rest pose
  94388. */
  94389. Skeleton.prototype.returnToRest = function () {
  94390. for (var index = 0; index < this.bones.length; index++) {
  94391. this.bones[index].returnToRest();
  94392. }
  94393. };
  94394. Skeleton.prototype._getHighestAnimationFrame = function () {
  94395. var ret = 0;
  94396. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  94397. if (this.bones[i].animations[0]) {
  94398. var highest = this.bones[i].animations[0].getHighestFrame();
  94399. if (ret < highest) {
  94400. ret = highest;
  94401. }
  94402. }
  94403. }
  94404. return ret;
  94405. };
  94406. /**
  94407. * Begin a specific animation range
  94408. * @param name defines the name of the range to start
  94409. * @param loop defines if looping must be turned on (false by default)
  94410. * @param speedRatio defines the speed ratio to apply (1 by default)
  94411. * @param onAnimationEnd defines a callback which will be called when animation will end
  94412. * @returns a new animatable
  94413. */
  94414. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  94415. var range = this.getAnimationRange(name);
  94416. if (!range) {
  94417. return null;
  94418. }
  94419. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  94420. };
  94421. /** @hidden */
  94422. Skeleton.prototype._markAsDirty = function () {
  94423. this._isDirty = true;
  94424. };
  94425. /** @hidden */
  94426. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  94427. this._meshesWithPoseMatrix.push(mesh);
  94428. };
  94429. /** @hidden */
  94430. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  94431. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  94432. if (index > -1) {
  94433. this._meshesWithPoseMatrix.splice(index, 1);
  94434. }
  94435. };
  94436. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  94437. this.onBeforeComputeObservable.notifyObservers(this);
  94438. for (var index = 0; index < this.bones.length; index++) {
  94439. var bone = this.bones[index];
  94440. var parentBone = bone.getParent();
  94441. if (parentBone) {
  94442. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  94443. }
  94444. else {
  94445. if (initialSkinMatrix) {
  94446. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  94447. }
  94448. else {
  94449. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  94450. }
  94451. }
  94452. if (bone._index !== -1) {
  94453. var mappedIndex = bone._index === null ? index : bone._index;
  94454. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  94455. }
  94456. }
  94457. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  94458. };
  94459. /**
  94460. * Build all resources required to render a skeleton
  94461. */
  94462. Skeleton.prototype.prepare = function () {
  94463. // Update the local matrix of bones with linked transform nodes.
  94464. if (this._numBonesWithLinkedTransformNode > 0) {
  94465. for (var _i = 0, _a = this.bones; _i < _a.length; _i++) {
  94466. var bone_1 = _a[_i];
  94467. if (bone_1._linkedTransformNode) {
  94468. // Computing the world matrix also computes the local matrix.
  94469. bone_1._linkedTransformNode.computeWorldMatrix();
  94470. bone_1._matrix = bone_1._linkedTransformNode._localMatrix;
  94471. bone_1.markAsDirty();
  94472. }
  94473. }
  94474. }
  94475. if (!this._isDirty) {
  94476. return;
  94477. }
  94478. if (this.needInitialSkinMatrix) {
  94479. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  94480. var mesh = this._meshesWithPoseMatrix[index];
  94481. var poseMatrix = mesh.getPoseMatrix();
  94482. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  94483. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  94484. }
  94485. if (this._synchronizedWithMesh !== mesh) {
  94486. this._synchronizedWithMesh = mesh;
  94487. // Prepare bones
  94488. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  94489. var bone = this.bones[boneIndex];
  94490. if (!bone.getParent()) {
  94491. var matrix = bone.getBaseMatrix();
  94492. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  94493. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  94494. }
  94495. }
  94496. }
  94497. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  94498. }
  94499. }
  94500. else {
  94501. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  94502. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  94503. if (this.isUsingTextureForMatrices) {
  94504. if (this._transformMatrixTexture) {
  94505. this._transformMatrixTexture.dispose();
  94506. }
  94507. this._transformMatrixTexture = BABYLON.RawTexture.CreateRGBATexture(this._transformMatrices, (this.bones.length + 1) * 4, 1, this._scene, false, false, BABYLON.Engine.TEXTURE_NEAREST_SAMPLINGMODE, BABYLON.Engine.TEXTURETYPE_FLOAT);
  94508. }
  94509. }
  94510. this._computeTransformMatrices(this._transformMatrices, null);
  94511. if (this.isUsingTextureForMatrices && this._transformMatrixTexture) {
  94512. this._transformMatrixTexture.update(this._transformMatrices);
  94513. }
  94514. }
  94515. this._isDirty = false;
  94516. this._scene._activeBones.addCount(this.bones.length, false);
  94517. };
  94518. /**
  94519. * Gets the list of animatables currently running for this skeleton
  94520. * @returns an array of animatables
  94521. */
  94522. Skeleton.prototype.getAnimatables = function () {
  94523. if (!this._animatables || this._animatables.length !== this.bones.length) {
  94524. this._animatables = [];
  94525. for (var index = 0; index < this.bones.length; index++) {
  94526. this._animatables.push(this.bones[index]);
  94527. }
  94528. }
  94529. return this._animatables;
  94530. };
  94531. /**
  94532. * Clone the current skeleton
  94533. * @param name defines the name of the new skeleton
  94534. * @param id defines the id of the enw skeleton
  94535. * @returns the new skeleton
  94536. */
  94537. Skeleton.prototype.clone = function (name, id) {
  94538. var result = new Skeleton(name, id || name, this._scene);
  94539. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  94540. for (var index = 0; index < this.bones.length; index++) {
  94541. var source = this.bones[index];
  94542. var parentBone = null;
  94543. var parent_1 = source.getParent();
  94544. if (parent_1) {
  94545. var parentIndex = this.bones.indexOf(parent_1);
  94546. parentBone = result.bones[parentIndex];
  94547. }
  94548. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  94549. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  94550. }
  94551. if (this._ranges) {
  94552. result._ranges = {};
  94553. for (var rangeName in this._ranges) {
  94554. var range = this._ranges[rangeName];
  94555. if (range) {
  94556. result._ranges[rangeName] = range.clone();
  94557. }
  94558. }
  94559. }
  94560. this._isDirty = true;
  94561. return result;
  94562. };
  94563. /**
  94564. * Enable animation blending for this skeleton
  94565. * @param blendingSpeed defines the blending speed to apply
  94566. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  94567. */
  94568. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  94569. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  94570. this.bones.forEach(function (bone) {
  94571. bone.animations.forEach(function (animation) {
  94572. animation.enableBlending = true;
  94573. animation.blendingSpeed = blendingSpeed;
  94574. });
  94575. });
  94576. };
  94577. /**
  94578. * Releases all resources associated with the current skeleton
  94579. */
  94580. Skeleton.prototype.dispose = function () {
  94581. this._meshesWithPoseMatrix = [];
  94582. // Animations
  94583. this.getScene().stopAnimation(this);
  94584. // Remove from scene
  94585. this.getScene().removeSkeleton(this);
  94586. if (this._transformMatrixTexture) {
  94587. this._transformMatrixTexture.dispose();
  94588. this._transformMatrixTexture = null;
  94589. }
  94590. };
  94591. /**
  94592. * Serialize the skeleton in a JSON object
  94593. * @returns a JSON object
  94594. */
  94595. Skeleton.prototype.serialize = function () {
  94596. var serializationObject = {};
  94597. serializationObject.name = this.name;
  94598. serializationObject.id = this.id;
  94599. if (this.dimensionsAtRest) {
  94600. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  94601. }
  94602. serializationObject.bones = [];
  94603. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  94604. for (var index = 0; index < this.bones.length; index++) {
  94605. var bone = this.bones[index];
  94606. var parent_2 = bone.getParent();
  94607. var serializedBone = {
  94608. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  94609. name: bone.name,
  94610. matrix: bone.getBaseMatrix().toArray(),
  94611. rest: bone.getRestPose().toArray()
  94612. };
  94613. serializationObject.bones.push(serializedBone);
  94614. if (bone.length) {
  94615. serializedBone.length = bone.length;
  94616. }
  94617. if (bone.metadata) {
  94618. serializedBone.metadata = bone.metadata;
  94619. }
  94620. if (bone.animations && bone.animations.length > 0) {
  94621. serializedBone.animation = bone.animations[0].serialize();
  94622. }
  94623. serializationObject.ranges = [];
  94624. for (var name in this._ranges) {
  94625. var source = this._ranges[name];
  94626. if (!source) {
  94627. continue;
  94628. }
  94629. var range = {};
  94630. range.name = name;
  94631. range.from = source.from;
  94632. range.to = source.to;
  94633. serializationObject.ranges.push(range);
  94634. }
  94635. }
  94636. return serializationObject;
  94637. };
  94638. /**
  94639. * Creates a new skeleton from serialized data
  94640. * @param parsedSkeleton defines the serialized data
  94641. * @param scene defines the hosting scene
  94642. * @returns a new skeleton
  94643. */
  94644. Skeleton.Parse = function (parsedSkeleton, scene) {
  94645. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  94646. if (parsedSkeleton.dimensionsAtRest) {
  94647. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  94648. }
  94649. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  94650. var index;
  94651. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  94652. var parsedBone = parsedSkeleton.bones[index];
  94653. var parentBone = null;
  94654. if (parsedBone.parentBoneIndex > -1) {
  94655. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  94656. }
  94657. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  94658. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  94659. if (parsedBone.id !== undefined && parsedBone.id !== null) {
  94660. bone.id = parsedBone.id;
  94661. }
  94662. if (parsedBone.length) {
  94663. bone.length = parsedBone.length;
  94664. }
  94665. if (parsedBone.metadata) {
  94666. bone.metadata = parsedBone.metadata;
  94667. }
  94668. if (parsedBone.animation) {
  94669. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  94670. }
  94671. }
  94672. // placed after bones, so createAnimationRange can cascade down
  94673. if (parsedSkeleton.ranges) {
  94674. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  94675. var data = parsedSkeleton.ranges[index];
  94676. skeleton.createAnimationRange(data.name, data.from, data.to);
  94677. }
  94678. }
  94679. return skeleton;
  94680. };
  94681. /**
  94682. * Compute all node absolute transforms
  94683. * @param forceUpdate defines if computation must be done even if cache is up to date
  94684. */
  94685. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  94686. if (forceUpdate === void 0) { forceUpdate = false; }
  94687. var renderId = this._scene.getRenderId();
  94688. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  94689. this.bones[0].computeAbsoluteTransforms();
  94690. this._lastAbsoluteTransformsUpdateId = renderId;
  94691. }
  94692. };
  94693. /**
  94694. * Gets the root pose matrix
  94695. * @returns a matrix
  94696. */
  94697. Skeleton.prototype.getPoseMatrix = function () {
  94698. var poseMatrix = null;
  94699. if (this._meshesWithPoseMatrix.length > 0) {
  94700. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  94701. }
  94702. return poseMatrix;
  94703. };
  94704. /**
  94705. * Sorts bones per internal index
  94706. */
  94707. Skeleton.prototype.sortBones = function () {
  94708. var bones = new Array();
  94709. var visited = new Array(this.bones.length);
  94710. for (var index = 0; index < this.bones.length; index++) {
  94711. this._sortBones(index, bones, visited);
  94712. }
  94713. this.bones = bones;
  94714. };
  94715. Skeleton.prototype._sortBones = function (index, bones, visited) {
  94716. if (visited[index]) {
  94717. return;
  94718. }
  94719. visited[index] = true;
  94720. var bone = this.bones[index];
  94721. if (bone._index === undefined) {
  94722. bone._index = index;
  94723. }
  94724. var parentBone = bone.getParent();
  94725. if (parentBone) {
  94726. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  94727. }
  94728. bones.push(bone);
  94729. };
  94730. return Skeleton;
  94731. }());
  94732. BABYLON.Skeleton = Skeleton;
  94733. })(BABYLON || (BABYLON = {}));
  94734. //# sourceMappingURL=babylon.skeleton.js.map
  94735. var BABYLON;
  94736. (function (BABYLON) {
  94737. /**
  94738. * This groups tools to convert HDR texture to native colors array.
  94739. */
  94740. var HDRTools = /** @class */ (function () {
  94741. function HDRTools() {
  94742. }
  94743. HDRTools.Ldexp = function (mantissa, exponent) {
  94744. if (exponent > 1023) {
  94745. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  94746. }
  94747. if (exponent < -1074) {
  94748. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  94749. }
  94750. return mantissa * Math.pow(2, exponent);
  94751. };
  94752. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  94753. if (exponent > 0) { /*nonzero pixel*/
  94754. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  94755. float32array[index + 0] = red * exponent;
  94756. float32array[index + 1] = green * exponent;
  94757. float32array[index + 2] = blue * exponent;
  94758. }
  94759. else {
  94760. float32array[index + 0] = 0;
  94761. float32array[index + 1] = 0;
  94762. float32array[index + 2] = 0;
  94763. }
  94764. };
  94765. HDRTools.readStringLine = function (uint8array, startIndex) {
  94766. var line = "";
  94767. var character = "";
  94768. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  94769. character = String.fromCharCode(uint8array[i]);
  94770. if (character == "\n") {
  94771. break;
  94772. }
  94773. line += character;
  94774. }
  94775. return line;
  94776. };
  94777. /**
  94778. * Reads header information from an RGBE texture stored in a native array.
  94779. * More information on this format are available here:
  94780. * https://en.wikipedia.org/wiki/RGBE_image_format
  94781. *
  94782. * @param uint8array The binary file stored in native array.
  94783. * @return The header information.
  94784. */
  94785. HDRTools.RGBE_ReadHeader = function (uint8array) {
  94786. var height = 0;
  94787. var width = 0;
  94788. var line = this.readStringLine(uint8array, 0);
  94789. if (line[0] != '#' || line[1] != '?') {
  94790. throw "Bad HDR Format.";
  94791. }
  94792. var endOfHeader = false;
  94793. var findFormat = false;
  94794. var lineIndex = 0;
  94795. do {
  94796. lineIndex += (line.length + 1);
  94797. line = this.readStringLine(uint8array, lineIndex);
  94798. if (line == "FORMAT=32-bit_rle_rgbe") {
  94799. findFormat = true;
  94800. }
  94801. else if (line.length == 0) {
  94802. endOfHeader = true;
  94803. }
  94804. } while (!endOfHeader);
  94805. if (!findFormat) {
  94806. throw "HDR Bad header format, unsupported FORMAT";
  94807. }
  94808. lineIndex += (line.length + 1);
  94809. line = this.readStringLine(uint8array, lineIndex);
  94810. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  94811. var match = sizeRegexp.exec(line);
  94812. // TODO. Support +Y and -X if needed.
  94813. if (!match || match.length < 3) {
  94814. throw "HDR Bad header format, no size";
  94815. }
  94816. width = parseInt(match[2]);
  94817. height = parseInt(match[1]);
  94818. if (width < 8 || width > 0x7fff) {
  94819. throw "HDR Bad header format, unsupported size";
  94820. }
  94821. lineIndex += (line.length + 1);
  94822. return {
  94823. height: height,
  94824. width: width,
  94825. dataPosition: lineIndex
  94826. };
  94827. };
  94828. /**
  94829. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  94830. * This RGBE texture needs to store the information as a panorama.
  94831. *
  94832. * More information on this format are available here:
  94833. * https://en.wikipedia.org/wiki/RGBE_image_format
  94834. *
  94835. * @param buffer The binary file stored in an array buffer.
  94836. * @param size The expected size of the extracted cubemap.
  94837. * @return The Cube Map information.
  94838. */
  94839. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  94840. var uint8array = new Uint8Array(buffer);
  94841. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  94842. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  94843. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  94844. return cubeMapData;
  94845. };
  94846. /**
  94847. * Returns the pixels data extracted from an RGBE texture.
  94848. * This pixels will be stored left to right up to down in the R G B order in one array.
  94849. *
  94850. * More information on this format are available here:
  94851. * https://en.wikipedia.org/wiki/RGBE_image_format
  94852. *
  94853. * @param uint8array The binary file stored in an array buffer.
  94854. * @param hdrInfo The header information of the file.
  94855. * @return The pixels data in RGB right to left up to down order.
  94856. */
  94857. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  94858. // Keep for multi format supports.
  94859. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  94860. };
  94861. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  94862. var num_scanlines = hdrInfo.height;
  94863. var scanline_width = hdrInfo.width;
  94864. var a, b, c, d, count;
  94865. var dataIndex = hdrInfo.dataPosition;
  94866. var index = 0, endIndex = 0, i = 0;
  94867. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  94868. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  94869. // 3 channels of 4 bytes per pixel in float.
  94870. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  94871. var resultArray = new Float32Array(resultBuffer);
  94872. // read in each successive scanline
  94873. while (num_scanlines > 0) {
  94874. a = uint8array[dataIndex++];
  94875. b = uint8array[dataIndex++];
  94876. c = uint8array[dataIndex++];
  94877. d = uint8array[dataIndex++];
  94878. if (a != 2 || b != 2 || (c & 0x80)) {
  94879. // this file is not run length encoded
  94880. throw "HDR Bad header format, not RLE";
  94881. }
  94882. if (((c << 8) | d) != scanline_width) {
  94883. throw "HDR Bad header format, wrong scan line width";
  94884. }
  94885. index = 0;
  94886. // read each of the four channels for the scanline into the buffer
  94887. for (i = 0; i < 4; i++) {
  94888. endIndex = (i + 1) * scanline_width;
  94889. while (index < endIndex) {
  94890. a = uint8array[dataIndex++];
  94891. b = uint8array[dataIndex++];
  94892. if (a > 128) {
  94893. // a run of the same value
  94894. count = a - 128;
  94895. if ((count == 0) || (count > endIndex - index)) {
  94896. throw "HDR Bad Format, bad scanline data (run)";
  94897. }
  94898. while (count-- > 0) {
  94899. scanLineArray[index++] = b;
  94900. }
  94901. }
  94902. else {
  94903. // a non-run
  94904. count = a;
  94905. if ((count == 0) || (count > endIndex - index)) {
  94906. throw "HDR Bad Format, bad scanline data (non-run)";
  94907. }
  94908. scanLineArray[index++] = b;
  94909. if (--count > 0) {
  94910. for (var j = 0; j < count; j++) {
  94911. scanLineArray[index++] = uint8array[dataIndex++];
  94912. }
  94913. }
  94914. }
  94915. }
  94916. }
  94917. // now convert data from buffer into floats
  94918. for (i = 0; i < scanline_width; i++) {
  94919. a = scanLineArray[i];
  94920. b = scanLineArray[i + scanline_width];
  94921. c = scanLineArray[i + 2 * scanline_width];
  94922. d = scanLineArray[i + 3 * scanline_width];
  94923. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  94924. }
  94925. num_scanlines--;
  94926. }
  94927. return resultArray;
  94928. };
  94929. return HDRTools;
  94930. }());
  94931. BABYLON.HDRTools = HDRTools;
  94932. })(BABYLON || (BABYLON = {}));
  94933. //# sourceMappingURL=babylon.hdr.js.map
  94934. var BABYLON;
  94935. (function (BABYLON) {
  94936. /**
  94937. * This represents a texture coming from an HDR input.
  94938. *
  94939. * The only supported format is currently panorama picture stored in RGBE format.
  94940. * Example of such files can be found on HDRLib: http://hdrlib.com/
  94941. */
  94942. var HDRCubeTexture = /** @class */ (function (_super) {
  94943. __extends(HDRCubeTexture, _super);
  94944. /**
  94945. * Instantiates an HDRTexture from the following parameters.
  94946. *
  94947. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  94948. * @param scene The scene the texture will be used in
  94949. * @param size The cubemap desired size (the more it increases the longer the generation will be)
  94950. * @param noMipmap Forces to not generate the mipmap if true
  94951. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  94952. * @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)
  94953. * @param reserved Reserved flag for internal use.
  94954. */
  94955. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, gammaSpace, reserved, onLoad, onError) {
  94956. if (noMipmap === void 0) { noMipmap = false; }
  94957. if (generateHarmonics === void 0) { generateHarmonics = true; }
  94958. if (gammaSpace === void 0) { gammaSpace = false; }
  94959. if (reserved === void 0) { reserved = false; }
  94960. if (onLoad === void 0) { onLoad = null; }
  94961. if (onError === void 0) { onError = null; }
  94962. var _this = _super.call(this, scene) || this;
  94963. _this._generateHarmonics = true;
  94964. _this._onLoad = null;
  94965. _this._onError = null;
  94966. /**
  94967. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  94968. */
  94969. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  94970. _this._isBlocking = true;
  94971. _this._rotationY = 0;
  94972. /**
  94973. * Gets or sets the center of the bounding box associated with the cube texture
  94974. * It must define where the camera used to render the texture was set
  94975. */
  94976. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  94977. if (!url) {
  94978. return _this;
  94979. }
  94980. _this.name = url;
  94981. _this.url = url;
  94982. _this.hasAlpha = false;
  94983. _this.isCube = true;
  94984. _this._textureMatrix = BABYLON.Matrix.Identity();
  94985. _this._onLoad = onLoad;
  94986. _this._onError = onError;
  94987. _this.gammaSpace = gammaSpace;
  94988. _this._noMipmap = noMipmap;
  94989. _this._size = size;
  94990. _this._texture = _this._getFromCache(url, _this._noMipmap);
  94991. if (!_this._texture) {
  94992. if (!scene.useDelayedTextureLoading) {
  94993. _this.loadTexture();
  94994. }
  94995. else {
  94996. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  94997. }
  94998. }
  94999. return _this;
  95000. }
  95001. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  95002. /**
  95003. * Gets wether or not the texture is blocking during loading.
  95004. */
  95005. get: function () {
  95006. return this._isBlocking;
  95007. },
  95008. /**
  95009. * Sets wether or not the texture is blocking during loading.
  95010. */
  95011. set: function (value) {
  95012. this._isBlocking = value;
  95013. },
  95014. enumerable: true,
  95015. configurable: true
  95016. });
  95017. Object.defineProperty(HDRCubeTexture.prototype, "rotationY", {
  95018. /**
  95019. * Gets texture matrix rotation angle around Y axis radians.
  95020. */
  95021. get: function () {
  95022. return this._rotationY;
  95023. },
  95024. /**
  95025. * Sets texture matrix rotation angle around Y axis in radians.
  95026. */
  95027. set: function (value) {
  95028. this._rotationY = value;
  95029. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  95030. },
  95031. enumerable: true,
  95032. configurable: true
  95033. });
  95034. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  95035. get: function () {
  95036. return this._boundingBoxSize;
  95037. },
  95038. /**
  95039. * Gets or sets the size of the bounding box associated with the cube texture
  95040. * When defined, the cubemap will switch to local mode
  95041. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  95042. * @example https://www.babylonjs-playground.com/#RNASML
  95043. */
  95044. set: function (value) {
  95045. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  95046. return;
  95047. }
  95048. this._boundingBoxSize = value;
  95049. var scene = this.getScene();
  95050. if (scene) {
  95051. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  95052. }
  95053. },
  95054. enumerable: true,
  95055. configurable: true
  95056. });
  95057. /**
  95058. * Get the current class name of the texture useful for serialization or dynamic coding.
  95059. * @returns "HDRCubeTexture"
  95060. */
  95061. HDRCubeTexture.prototype.getClassName = function () {
  95062. return "HDRCubeTexture";
  95063. };
  95064. /**
  95065. * Occurs when the file is raw .hdr file.
  95066. */
  95067. HDRCubeTexture.prototype.loadTexture = function () {
  95068. var _this = this;
  95069. var callback = function (buffer) {
  95070. _this.lodGenerationOffset = 0.0;
  95071. _this.lodGenerationScale = 0.8;
  95072. var scene = _this.getScene();
  95073. if (!scene) {
  95074. return null;
  95075. }
  95076. // Extract the raw linear data.
  95077. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  95078. // Generate harmonics if needed.
  95079. if (_this._generateHarmonics) {
  95080. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  95081. _this.sphericalPolynomial = sphericalPolynomial;
  95082. }
  95083. var results = [];
  95084. var byteArray = null;
  95085. // Push each faces.
  95086. for (var j = 0; j < 6; j++) {
  95087. // Create uintarray fallback.
  95088. if (!scene.getEngine().getCaps().textureFloat) {
  95089. // 3 channels of 1 bytes per pixel in bytes.
  95090. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  95091. byteArray = new Uint8Array(byteBuffer);
  95092. }
  95093. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  95094. // If special cases.
  95095. if (_this.gammaSpace || byteArray) {
  95096. for (var i = 0; i < _this._size * _this._size; i++) {
  95097. // Put in gamma space if requested.
  95098. if (_this.gammaSpace) {
  95099. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  95100. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  95101. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  95102. }
  95103. // Convert to int texture for fallback.
  95104. if (byteArray) {
  95105. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  95106. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  95107. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  95108. // May use luminance instead if the result is not accurate.
  95109. var max = Math.max(Math.max(r, g), b);
  95110. if (max > 255) {
  95111. var scale = 255 / max;
  95112. r *= scale;
  95113. g *= scale;
  95114. b *= scale;
  95115. }
  95116. byteArray[(i * 3) + 0] = r;
  95117. byteArray[(i * 3) + 1] = g;
  95118. byteArray[(i * 3) + 2] = b;
  95119. }
  95120. }
  95121. }
  95122. if (byteArray) {
  95123. results.push(byteArray);
  95124. }
  95125. else {
  95126. results.push(dataFace);
  95127. }
  95128. }
  95129. return results;
  95130. };
  95131. var scene = this.getScene();
  95132. if (scene) {
  95133. 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);
  95134. }
  95135. };
  95136. HDRCubeTexture.prototype.clone = function () {
  95137. var scene = this.getScene();
  95138. if (!scene) {
  95139. return this;
  95140. }
  95141. var newTexture = new HDRCubeTexture(this.url, scene, this._size, this._noMipmap, this._generateHarmonics, this.gammaSpace);
  95142. // Base texture
  95143. newTexture.level = this.level;
  95144. newTexture.wrapU = this.wrapU;
  95145. newTexture.wrapV = this.wrapV;
  95146. newTexture.coordinatesIndex = this.coordinatesIndex;
  95147. newTexture.coordinatesMode = this.coordinatesMode;
  95148. return newTexture;
  95149. };
  95150. // Methods
  95151. HDRCubeTexture.prototype.delayLoad = function () {
  95152. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  95153. return;
  95154. }
  95155. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  95156. this._texture = this._getFromCache(this.url, this._noMipmap);
  95157. if (!this._texture) {
  95158. this.loadTexture();
  95159. }
  95160. };
  95161. /**
  95162. * Get the texture reflection matrix used to rotate/transform the reflection.
  95163. * @returns the reflection matrix
  95164. */
  95165. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  95166. return this._textureMatrix;
  95167. };
  95168. /**
  95169. * Set the texture reflection matrix used to rotate/transform the reflection.
  95170. * @param value Define the reflection matrix to set
  95171. */
  95172. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  95173. var _this = this;
  95174. this._textureMatrix = value;
  95175. if (value.updateFlag === this._textureMatrix.updateFlag) {
  95176. return;
  95177. }
  95178. if (value.isIdentity() !== this._textureMatrix.isIdentity()) {
  95179. this.getScene().markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) { return mat.getActiveTextures().indexOf(_this) !== -1; });
  95180. }
  95181. };
  95182. /**
  95183. * Parses a JSON representation of an HDR Texture in order to create the texture
  95184. * @param parsedTexture Define the JSON representation
  95185. * @param scene Define the scene the texture should be created in
  95186. * @param rootUrl Define the root url in case we need to load relative dependencies
  95187. * @returns the newly created texture after parsing
  95188. */
  95189. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  95190. var texture = null;
  95191. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  95192. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace);
  95193. texture.name = parsedTexture.name;
  95194. texture.hasAlpha = parsedTexture.hasAlpha;
  95195. texture.level = parsedTexture.level;
  95196. texture.coordinatesMode = parsedTexture.coordinatesMode;
  95197. texture.isBlocking = parsedTexture.isBlocking;
  95198. }
  95199. if (texture) {
  95200. if (parsedTexture.boundingBoxPosition) {
  95201. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  95202. }
  95203. if (parsedTexture.boundingBoxSize) {
  95204. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  95205. }
  95206. if (parsedTexture.rotationY) {
  95207. texture.rotationY = parsedTexture.rotationY;
  95208. }
  95209. }
  95210. return texture;
  95211. };
  95212. HDRCubeTexture.prototype.serialize = function () {
  95213. if (!this.name) {
  95214. return null;
  95215. }
  95216. var serializationObject = {};
  95217. serializationObject.name = this.name;
  95218. serializationObject.hasAlpha = this.hasAlpha;
  95219. serializationObject.isCube = true;
  95220. serializationObject.level = this.level;
  95221. serializationObject.size = this._size;
  95222. serializationObject.coordinatesMode = this.coordinatesMode;
  95223. serializationObject.useInGammaSpace = this.gammaSpace;
  95224. serializationObject.generateHarmonics = this._generateHarmonics;
  95225. serializationObject.customType = "BABYLON.HDRCubeTexture";
  95226. serializationObject.noMipmap = this._noMipmap;
  95227. serializationObject.isBlocking = this._isBlocking;
  95228. serializationObject.rotationY = this._rotationY;
  95229. return serializationObject;
  95230. };
  95231. HDRCubeTexture._facesMapping = [
  95232. "right",
  95233. "left",
  95234. "up",
  95235. "down",
  95236. "front",
  95237. "back"
  95238. ];
  95239. return HDRCubeTexture;
  95240. }(BABYLON.BaseTexture));
  95241. BABYLON.HDRCubeTexture = HDRCubeTexture;
  95242. })(BABYLON || (BABYLON = {}));
  95243. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  95244. var BABYLON;
  95245. (function (BABYLON) {
  95246. /**
  95247. * Helper class useful to convert panorama picture to their cubemap representation in 6 faces.
  95248. */
  95249. var PanoramaToCubeMapTools = /** @class */ (function () {
  95250. function PanoramaToCubeMapTools() {
  95251. }
  95252. /**
  95253. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  95254. *
  95255. * @param float32Array The source data.
  95256. * @param inputWidth The width of the input panorama.
  95257. * @param inputHeight The height of the input panorama.
  95258. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  95259. * @return The cubemap data
  95260. */
  95261. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  95262. if (!float32Array) {
  95263. throw "ConvertPanoramaToCubemap: input cannot be null";
  95264. }
  95265. if (float32Array.length != inputWidth * inputHeight * 3) {
  95266. throw "ConvertPanoramaToCubemap: input size is wrong";
  95267. }
  95268. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  95269. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  95270. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  95271. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  95272. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  95273. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  95274. return {
  95275. front: textureFront,
  95276. back: textureBack,
  95277. left: textureLeft,
  95278. right: textureRight,
  95279. up: textureUp,
  95280. down: textureDown,
  95281. size: size,
  95282. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  95283. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  95284. gammaSpace: false,
  95285. };
  95286. };
  95287. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  95288. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  95289. var textureArray = new Float32Array(buffer);
  95290. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  95291. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  95292. var dy = 1 / texSize;
  95293. var fy = 0;
  95294. for (var y = 0; y < texSize; y++) {
  95295. var xv1 = faceData[0];
  95296. var xv2 = faceData[2];
  95297. for (var x = 0; x < texSize; x++) {
  95298. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  95299. v.normalize();
  95300. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  95301. // 3 channels per pixels
  95302. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  95303. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  95304. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  95305. xv1 = xv1.add(rotDX1);
  95306. xv2 = xv2.add(rotDX2);
  95307. }
  95308. fy += dy;
  95309. }
  95310. return textureArray;
  95311. };
  95312. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  95313. var theta = Math.atan2(vDir.z, vDir.x);
  95314. var phi = Math.acos(vDir.y);
  95315. while (theta < -Math.PI) {
  95316. theta += 2 * Math.PI;
  95317. }
  95318. while (theta > Math.PI) {
  95319. theta -= 2 * Math.PI;
  95320. }
  95321. var dx = theta / Math.PI;
  95322. var dy = phi / Math.PI;
  95323. // recenter.
  95324. dx = dx * 0.5 + 0.5;
  95325. var px = Math.round(dx * inputWidth);
  95326. if (px < 0) {
  95327. px = 0;
  95328. }
  95329. else if (px >= inputWidth) {
  95330. px = inputWidth - 1;
  95331. }
  95332. var py = Math.round(dy * inputHeight);
  95333. if (py < 0) {
  95334. py = 0;
  95335. }
  95336. else if (py >= inputHeight) {
  95337. py = inputHeight - 1;
  95338. }
  95339. var inputY = (inputHeight - py - 1);
  95340. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  95341. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  95342. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  95343. return {
  95344. r: r,
  95345. g: g,
  95346. b: b
  95347. };
  95348. };
  95349. PanoramaToCubeMapTools.FACE_FRONT = [
  95350. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  95351. new BABYLON.Vector3(1.0, -1.0, -1.0),
  95352. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  95353. new BABYLON.Vector3(1.0, 1.0, -1.0)
  95354. ];
  95355. PanoramaToCubeMapTools.FACE_BACK = [
  95356. new BABYLON.Vector3(1.0, -1.0, 1.0),
  95357. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  95358. new BABYLON.Vector3(1.0, 1.0, 1.0),
  95359. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  95360. ];
  95361. PanoramaToCubeMapTools.FACE_RIGHT = [
  95362. new BABYLON.Vector3(1.0, -1.0, -1.0),
  95363. new BABYLON.Vector3(1.0, -1.0, 1.0),
  95364. new BABYLON.Vector3(1.0, 1.0, -1.0),
  95365. new BABYLON.Vector3(1.0, 1.0, 1.0)
  95366. ];
  95367. PanoramaToCubeMapTools.FACE_LEFT = [
  95368. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  95369. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  95370. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  95371. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  95372. ];
  95373. PanoramaToCubeMapTools.FACE_DOWN = [
  95374. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  95375. new BABYLON.Vector3(1.0, 1.0, -1.0),
  95376. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  95377. new BABYLON.Vector3(1.0, 1.0, 1.0)
  95378. ];
  95379. PanoramaToCubeMapTools.FACE_UP = [
  95380. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  95381. new BABYLON.Vector3(1.0, -1.0, 1.0),
  95382. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  95383. new BABYLON.Vector3(1.0, -1.0, -1.0)
  95384. ];
  95385. return PanoramaToCubeMapTools;
  95386. }());
  95387. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  95388. })(BABYLON || (BABYLON = {}));
  95389. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  95390. var BABYLON;
  95391. (function (BABYLON) {
  95392. /**
  95393. * Vector2 wth index property
  95394. */
  95395. var IndexedVector2 = /** @class */ (function (_super) {
  95396. __extends(IndexedVector2, _super);
  95397. function IndexedVector2(original,
  95398. /** Index of the vector2 */
  95399. index) {
  95400. var _this = _super.call(this, original.x, original.y) || this;
  95401. _this.index = index;
  95402. return _this;
  95403. }
  95404. return IndexedVector2;
  95405. }(BABYLON.Vector2));
  95406. /**
  95407. * Defines points to create a polygon
  95408. */
  95409. var PolygonPoints = /** @class */ (function () {
  95410. function PolygonPoints() {
  95411. this.elements = new Array();
  95412. }
  95413. PolygonPoints.prototype.add = function (originalPoints) {
  95414. var _this = this;
  95415. var result = new Array();
  95416. originalPoints.forEach(function (point) {
  95417. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  95418. var newPoint = new IndexedVector2(point, _this.elements.length);
  95419. result.push(newPoint);
  95420. _this.elements.push(newPoint);
  95421. }
  95422. });
  95423. return result;
  95424. };
  95425. PolygonPoints.prototype.computeBounds = function () {
  95426. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  95427. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  95428. this.elements.forEach(function (point) {
  95429. // x
  95430. if (point.x < lmin.x) {
  95431. lmin.x = point.x;
  95432. }
  95433. else if (point.x > lmax.x) {
  95434. lmax.x = point.x;
  95435. }
  95436. // y
  95437. if (point.y < lmin.y) {
  95438. lmin.y = point.y;
  95439. }
  95440. else if (point.y > lmax.y) {
  95441. lmax.y = point.y;
  95442. }
  95443. });
  95444. return {
  95445. min: lmin,
  95446. max: lmax,
  95447. width: lmax.x - lmin.x,
  95448. height: lmax.y - lmin.y
  95449. };
  95450. };
  95451. return PolygonPoints;
  95452. }());
  95453. /**
  95454. * Polygon
  95455. * @see https://doc.babylonjs.com/how_to/parametric_shapes#non-regular-polygon
  95456. */
  95457. var Polygon = /** @class */ (function () {
  95458. function Polygon() {
  95459. }
  95460. /**
  95461. * Creates a rectangle
  95462. * @param xmin bottom X coord
  95463. * @param ymin bottom Y coord
  95464. * @param xmax top X coord
  95465. * @param ymax top Y coord
  95466. * @returns points that make the resulting rectation
  95467. */
  95468. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  95469. return [
  95470. new BABYLON.Vector2(xmin, ymin),
  95471. new BABYLON.Vector2(xmax, ymin),
  95472. new BABYLON.Vector2(xmax, ymax),
  95473. new BABYLON.Vector2(xmin, ymax)
  95474. ];
  95475. };
  95476. /**
  95477. * Creates a circle
  95478. * @param radius radius of circle
  95479. * @param cx scale in x
  95480. * @param cy scale in y
  95481. * @param numberOfSides number of sides that make up the circle
  95482. * @returns points that make the resulting circle
  95483. */
  95484. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  95485. if (cx === void 0) { cx = 0; }
  95486. if (cy === void 0) { cy = 0; }
  95487. if (numberOfSides === void 0) { numberOfSides = 32; }
  95488. var result = new Array();
  95489. var angle = 0;
  95490. var increment = (Math.PI * 2) / numberOfSides;
  95491. for (var i = 0; i < numberOfSides; i++) {
  95492. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  95493. angle -= increment;
  95494. }
  95495. return result;
  95496. };
  95497. /**
  95498. * Creates a polygon from input string
  95499. * @param input Input polygon data
  95500. * @returns the parsed points
  95501. */
  95502. Polygon.Parse = function (input) {
  95503. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  95504. var i, result = [];
  95505. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  95506. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  95507. }
  95508. return result;
  95509. };
  95510. /**
  95511. * Starts building a polygon from x and y coordinates
  95512. * @param x x coordinate
  95513. * @param y y coordinate
  95514. * @returns the started path2
  95515. */
  95516. Polygon.StartingAt = function (x, y) {
  95517. return BABYLON.Path2.StartingAt(x, y);
  95518. };
  95519. return Polygon;
  95520. }());
  95521. BABYLON.Polygon = Polygon;
  95522. /**
  95523. * Builds a polygon
  95524. * @see https://doc.babylonjs.com/how_to/polygonmeshbuilder
  95525. */
  95526. var PolygonMeshBuilder = /** @class */ (function () {
  95527. /**
  95528. * Creates a PolygonMeshBuilder
  95529. * @param name name of the builder
  95530. * @param contours Path of the polygon
  95531. * @param scene scene to add to
  95532. */
  95533. function PolygonMeshBuilder(name, contours, scene) {
  95534. this._points = new PolygonPoints();
  95535. this._outlinepoints = new PolygonPoints();
  95536. this._holes = new Array();
  95537. this._epoints = new Array();
  95538. this._eholes = new Array();
  95539. this._name = name;
  95540. this._scene = scene;
  95541. var points;
  95542. if (contours instanceof BABYLON.Path2) {
  95543. points = contours.getPoints();
  95544. }
  95545. else {
  95546. points = contours;
  95547. }
  95548. this._addToepoint(points);
  95549. this._points.add(points);
  95550. this._outlinepoints.add(points);
  95551. if (typeof earcut === 'undefined') {
  95552. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  95553. }
  95554. }
  95555. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  95556. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  95557. var p = points_1[_i];
  95558. this._epoints.push(p.x, p.y);
  95559. }
  95560. };
  95561. /**
  95562. * Adds a whole within the polygon
  95563. * @param hole Array of points defining the hole
  95564. * @returns this
  95565. */
  95566. PolygonMeshBuilder.prototype.addHole = function (hole) {
  95567. this._points.add(hole);
  95568. var holepoints = new PolygonPoints();
  95569. holepoints.add(hole);
  95570. this._holes.push(holepoints);
  95571. this._eholes.push(this._epoints.length / 2);
  95572. this._addToepoint(hole);
  95573. return this;
  95574. };
  95575. /**
  95576. * Creates the polygon
  95577. * @param updatable If the mesh should be updatable
  95578. * @param depth The depth of the mesh created
  95579. * @returns the created mesh
  95580. */
  95581. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  95582. var _this = this;
  95583. if (updatable === void 0) { updatable = false; }
  95584. if (depth === void 0) { depth = 0; }
  95585. var result = new BABYLON.Mesh(this._name, this._scene);
  95586. var normals = new Array();
  95587. var positions = new Array();
  95588. var uvs = new Array();
  95589. var bounds = this._points.computeBounds();
  95590. this._points.elements.forEach(function (p) {
  95591. normals.push(0, 1.0, 0);
  95592. positions.push(p.x, 0, p.y);
  95593. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  95594. });
  95595. var indices = new Array();
  95596. var res = earcut(this._epoints, this._eholes, 2);
  95597. for (var i = 0; i < res.length; i++) {
  95598. indices.push(res[i]);
  95599. }
  95600. if (depth > 0) {
  95601. var positionscount = (positions.length / 3); //get the current pointcount
  95602. this._points.elements.forEach(function (p) {
  95603. normals.push(0, -1.0, 0);
  95604. positions.push(p.x, -depth, p.y);
  95605. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  95606. });
  95607. var totalCount = indices.length;
  95608. for (var i = 0; i < totalCount; i += 3) {
  95609. var i0 = indices[i + 0];
  95610. var i1 = indices[i + 1];
  95611. var i2 = indices[i + 2];
  95612. indices.push(i2 + positionscount);
  95613. indices.push(i1 + positionscount);
  95614. indices.push(i0 + positionscount);
  95615. }
  95616. //Add the sides
  95617. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  95618. this._holes.forEach(function (hole) {
  95619. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  95620. });
  95621. }
  95622. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  95623. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  95624. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  95625. result.setIndices(indices);
  95626. return result;
  95627. };
  95628. /**
  95629. * Adds a side to the polygon
  95630. * @param positions points that make the polygon
  95631. * @param normals normals of the polygon
  95632. * @param uvs uvs of the polygon
  95633. * @param indices indices of the polygon
  95634. * @param bounds bounds of the polygon
  95635. * @param points points of the polygon
  95636. * @param depth depth of the polygon
  95637. * @param flip flip of the polygon
  95638. */
  95639. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  95640. var StartIndex = positions.length / 3;
  95641. var ulength = 0;
  95642. for (var i = 0; i < points.elements.length; i++) {
  95643. var p = points.elements[i];
  95644. var p1;
  95645. if ((i + 1) > points.elements.length - 1) {
  95646. p1 = points.elements[0];
  95647. }
  95648. else {
  95649. p1 = points.elements[i + 1];
  95650. }
  95651. positions.push(p.x, 0, p.y);
  95652. positions.push(p.x, -depth, p.y);
  95653. positions.push(p1.x, 0, p1.y);
  95654. positions.push(p1.x, -depth, p1.y);
  95655. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  95656. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  95657. var v3 = v2.subtract(v1);
  95658. var v4 = new BABYLON.Vector3(0, 1, 0);
  95659. var vn = BABYLON.Vector3.Cross(v3, v4);
  95660. vn = vn.normalize();
  95661. uvs.push(ulength / bounds.width, 0);
  95662. uvs.push(ulength / bounds.width, 1);
  95663. ulength += v3.length();
  95664. uvs.push((ulength / bounds.width), 0);
  95665. uvs.push((ulength / bounds.width), 1);
  95666. if (!flip) {
  95667. normals.push(-vn.x, -vn.y, -vn.z);
  95668. normals.push(-vn.x, -vn.y, -vn.z);
  95669. normals.push(-vn.x, -vn.y, -vn.z);
  95670. normals.push(-vn.x, -vn.y, -vn.z);
  95671. indices.push(StartIndex);
  95672. indices.push(StartIndex + 1);
  95673. indices.push(StartIndex + 2);
  95674. indices.push(StartIndex + 1);
  95675. indices.push(StartIndex + 3);
  95676. indices.push(StartIndex + 2);
  95677. }
  95678. else {
  95679. normals.push(vn.x, vn.y, vn.z);
  95680. normals.push(vn.x, vn.y, vn.z);
  95681. normals.push(vn.x, vn.y, vn.z);
  95682. normals.push(vn.x, vn.y, vn.z);
  95683. indices.push(StartIndex);
  95684. indices.push(StartIndex + 2);
  95685. indices.push(StartIndex + 1);
  95686. indices.push(StartIndex + 1);
  95687. indices.push(StartIndex + 2);
  95688. indices.push(StartIndex + 3);
  95689. }
  95690. StartIndex += 4;
  95691. }
  95692. };
  95693. return PolygonMeshBuilder;
  95694. }());
  95695. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  95696. })(BABYLON || (BABYLON = {}));
  95697. //# sourceMappingURL=babylon.polygonMesh.js.map
  95698. var BABYLON;
  95699. (function (BABYLON) {
  95700. /**
  95701. * Unique ID when we import meshes from Babylon to CSG
  95702. */
  95703. var currentCSGMeshId = 0;
  95704. /**
  95705. * Represents a vertex of a polygon. Use your own vertex class instead of this
  95706. * one to provide additional features like texture coordinates and vertex
  95707. * colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  95708. * `flip()`, and `interpolate()` methods that behave analogous to the ones
  95709. * defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  95710. * functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  95711. * is not used anywhere else.
  95712. * Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  95713. */
  95714. var Vertex = /** @class */ (function () {
  95715. /**
  95716. * Initializes the vertex
  95717. * @param pos The position of the vertex
  95718. * @param normal The normal of the vertex
  95719. * @param uv The texture coordinate of the vertex
  95720. */
  95721. function Vertex(
  95722. /**
  95723. * The position of the vertex
  95724. */
  95725. pos,
  95726. /**
  95727. * The normal of the vertex
  95728. */
  95729. normal,
  95730. /**
  95731. * The texture coordinate of the vertex
  95732. */
  95733. uv) {
  95734. this.pos = pos;
  95735. this.normal = normal;
  95736. this.uv = uv;
  95737. }
  95738. /**
  95739. * Make a clone, or deep copy, of the vertex
  95740. * @returns A new Vertex
  95741. */
  95742. Vertex.prototype.clone = function () {
  95743. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  95744. };
  95745. /**
  95746. * Invert all orientation-specific data (e.g. vertex normal). Called when the
  95747. * orientation of a polygon is flipped.
  95748. */
  95749. Vertex.prototype.flip = function () {
  95750. this.normal = this.normal.scale(-1);
  95751. };
  95752. /**
  95753. * Create a new vertex between this vertex and `other` by linearly
  95754. * interpolating all properties using a parameter of `t`. Subclasses should
  95755. * override this to interpolate additional properties.
  95756. * @param other the vertex to interpolate against
  95757. * @param t The factor used to linearly interpolate between the vertices
  95758. */
  95759. Vertex.prototype.interpolate = function (other, t) {
  95760. 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));
  95761. };
  95762. return Vertex;
  95763. }());
  95764. /**
  95765. * Represents a plane in 3D space.
  95766. */
  95767. var Plane = /** @class */ (function () {
  95768. /**
  95769. * Initializes the plane
  95770. * @param normal The normal for the plane
  95771. * @param w
  95772. */
  95773. function Plane(normal, w) {
  95774. this.normal = normal;
  95775. this.w = w;
  95776. }
  95777. /**
  95778. * Construct a plane from three points
  95779. * @param a Point a
  95780. * @param b Point b
  95781. * @param c Point c
  95782. */
  95783. Plane.FromPoints = function (a, b, c) {
  95784. var v0 = c.subtract(a);
  95785. var v1 = b.subtract(a);
  95786. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  95787. return null;
  95788. }
  95789. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  95790. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  95791. };
  95792. /**
  95793. * Clone, or make a deep copy of the plane
  95794. * @returns a new Plane
  95795. */
  95796. Plane.prototype.clone = function () {
  95797. return new Plane(this.normal.clone(), this.w);
  95798. };
  95799. /**
  95800. * Flip the face of the plane
  95801. */
  95802. Plane.prototype.flip = function () {
  95803. this.normal.scaleInPlace(-1);
  95804. this.w = -this.w;
  95805. };
  95806. /**
  95807. * Split `polygon` by this plane if needed, then put the polygon or polygon
  95808. * fragments in the appropriate lists. Coplanar polygons go into either
  95809. `* coplanarFront` or `coplanarBack` depending on their orientation with
  95810. * respect to this plane. Polygons in front or in back of this plane go into
  95811. * either `front` or `back`
  95812. * @param polygon The polygon to be split
  95813. * @param coplanarFront Will contain polygons coplanar with the plane that are oriented to the front of the plane
  95814. * @param coplanarBack Will contain polygons coplanar with the plane that are oriented to the back of the plane
  95815. * @param front Will contain the polygons in front of the plane
  95816. * @param back Will contain the polygons begind the plane
  95817. */
  95818. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  95819. var COPLANAR = 0;
  95820. var FRONT = 1;
  95821. var BACK = 2;
  95822. var SPANNING = 3;
  95823. // Classify each point as well as the entire polygon into one of the above
  95824. // four classes.
  95825. var polygonType = 0;
  95826. var types = [];
  95827. var i;
  95828. var t;
  95829. for (i = 0; i < polygon.vertices.length; i++) {
  95830. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  95831. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  95832. polygonType |= type;
  95833. types.push(type);
  95834. }
  95835. // Put the polygon in the correct list, splitting it when necessary
  95836. switch (polygonType) {
  95837. case COPLANAR:
  95838. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  95839. break;
  95840. case FRONT:
  95841. front.push(polygon);
  95842. break;
  95843. case BACK:
  95844. back.push(polygon);
  95845. break;
  95846. case SPANNING:
  95847. var f = [], b = [];
  95848. for (i = 0; i < polygon.vertices.length; i++) {
  95849. var j = (i + 1) % polygon.vertices.length;
  95850. var ti = types[i], tj = types[j];
  95851. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  95852. if (ti !== BACK) {
  95853. f.push(vi);
  95854. }
  95855. if (ti !== FRONT) {
  95856. b.push(ti !== BACK ? vi.clone() : vi);
  95857. }
  95858. if ((ti | tj) === SPANNING) {
  95859. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  95860. var v = vi.interpolate(vj, t);
  95861. f.push(v);
  95862. b.push(v.clone());
  95863. }
  95864. }
  95865. var poly;
  95866. if (f.length >= 3) {
  95867. poly = new Polygon(f, polygon.shared);
  95868. if (poly.plane) {
  95869. front.push(poly);
  95870. }
  95871. }
  95872. if (b.length >= 3) {
  95873. poly = new Polygon(b, polygon.shared);
  95874. if (poly.plane) {
  95875. back.push(poly);
  95876. }
  95877. }
  95878. break;
  95879. }
  95880. };
  95881. /**
  95882. * `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  95883. * point is on the plane
  95884. */
  95885. Plane.EPSILON = 1e-5;
  95886. return Plane;
  95887. }());
  95888. /**
  95889. * Represents a convex polygon. The vertices used to initialize a polygon must
  95890. * be coplanar and form a convex loop.
  95891. *
  95892. * Each convex polygon has a `shared` property, which is shared between all
  95893. * polygons that are clones of each other or were split from the same polygon.
  95894. * This can be used to define per-polygon properties (such as surface color)
  95895. */
  95896. var Polygon = /** @class */ (function () {
  95897. /**
  95898. * Initializes the polygon
  95899. * @param vertices The vertices of the polygon
  95900. * @param shared The properties shared across all polygons
  95901. */
  95902. function Polygon(vertices, shared) {
  95903. this.vertices = vertices;
  95904. this.shared = shared;
  95905. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  95906. }
  95907. /**
  95908. * Clones, or makes a deep copy, or the polygon
  95909. */
  95910. Polygon.prototype.clone = function () {
  95911. var vertices = this.vertices.map(function (v) { return v.clone(); });
  95912. return new Polygon(vertices, this.shared);
  95913. };
  95914. /**
  95915. * Flips the faces of the polygon
  95916. */
  95917. Polygon.prototype.flip = function () {
  95918. this.vertices.reverse().map(function (v) { v.flip(); });
  95919. this.plane.flip();
  95920. };
  95921. return Polygon;
  95922. }());
  95923. /**
  95924. * Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  95925. * by picking a polygon to split along. That polygon (and all other coplanar
  95926. * polygons) are added directly to that node and the other polygons are added to
  95927. * the front and/or back subtrees. This is not a leafy BSP tree since there is
  95928. * no distinction between internal and leaf nodes
  95929. */
  95930. var Node = /** @class */ (function () {
  95931. /**
  95932. * Initializes the node
  95933. * @param polygons A collection of polygons held in the node
  95934. */
  95935. function Node(polygons) {
  95936. this.plane = null;
  95937. this.front = null;
  95938. this.back = null;
  95939. this.polygons = new Array();
  95940. if (polygons) {
  95941. this.build(polygons);
  95942. }
  95943. }
  95944. /**
  95945. * Clones, or makes a deep copy, of the node
  95946. * @returns The cloned node
  95947. */
  95948. Node.prototype.clone = function () {
  95949. var node = new Node();
  95950. node.plane = this.plane && this.plane.clone();
  95951. node.front = this.front && this.front.clone();
  95952. node.back = this.back && this.back.clone();
  95953. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  95954. return node;
  95955. };
  95956. /**
  95957. * Convert solid space to empty space and empty space to solid space
  95958. */
  95959. Node.prototype.invert = function () {
  95960. for (var i = 0; i < this.polygons.length; i++) {
  95961. this.polygons[i].flip();
  95962. }
  95963. if (this.plane) {
  95964. this.plane.flip();
  95965. }
  95966. if (this.front) {
  95967. this.front.invert();
  95968. }
  95969. if (this.back) {
  95970. this.back.invert();
  95971. }
  95972. var temp = this.front;
  95973. this.front = this.back;
  95974. this.back = temp;
  95975. };
  95976. /**
  95977. * Recursively remove all polygons in `polygons` that are inside this BSP
  95978. * tree.
  95979. * @param polygons Polygons to remove from the BSP
  95980. * @returns Polygons clipped from the BSP
  95981. */
  95982. Node.prototype.clipPolygons = function (polygons) {
  95983. if (!this.plane) {
  95984. return polygons.slice();
  95985. }
  95986. var front = new Array(), back = new Array();
  95987. for (var i = 0; i < polygons.length; i++) {
  95988. this.plane.splitPolygon(polygons[i], front, back, front, back);
  95989. }
  95990. if (this.front) {
  95991. front = this.front.clipPolygons(front);
  95992. }
  95993. if (this.back) {
  95994. back = this.back.clipPolygons(back);
  95995. }
  95996. else {
  95997. back = [];
  95998. }
  95999. return front.concat(back);
  96000. };
  96001. /**
  96002. * Remove all polygons in this BSP tree that are inside the other BSP tree
  96003. * `bsp`.
  96004. * @param bsp BSP containing polygons to remove from this BSP
  96005. */
  96006. Node.prototype.clipTo = function (bsp) {
  96007. this.polygons = bsp.clipPolygons(this.polygons);
  96008. if (this.front) {
  96009. this.front.clipTo(bsp);
  96010. }
  96011. if (this.back) {
  96012. this.back.clipTo(bsp);
  96013. }
  96014. };
  96015. /**
  96016. * Return a list of all polygons in this BSP tree
  96017. * @returns List of all polygons in this BSP tree
  96018. */
  96019. Node.prototype.allPolygons = function () {
  96020. var polygons = this.polygons.slice();
  96021. if (this.front) {
  96022. polygons = polygons.concat(this.front.allPolygons());
  96023. }
  96024. if (this.back) {
  96025. polygons = polygons.concat(this.back.allPolygons());
  96026. }
  96027. return polygons;
  96028. };
  96029. /**
  96030. * Build a BSP tree out of `polygons`. When called on an existing tree, the
  96031. * new polygons are filtered down to the bottom of the tree and become new
  96032. * nodes there. Each set of polygons is partitioned using the first polygon
  96033. * (no heuristic is used to pick a good split)
  96034. * @param polygons Polygons used to construct the BSP tree
  96035. */
  96036. Node.prototype.build = function (polygons) {
  96037. if (!polygons.length) {
  96038. return;
  96039. }
  96040. if (!this.plane) {
  96041. this.plane = polygons[0].plane.clone();
  96042. }
  96043. var front = new Array(), back = new Array();
  96044. for (var i = 0; i < polygons.length; i++) {
  96045. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  96046. }
  96047. if (front.length) {
  96048. if (!this.front) {
  96049. this.front = new Node();
  96050. }
  96051. this.front.build(front);
  96052. }
  96053. if (back.length) {
  96054. if (!this.back) {
  96055. this.back = new Node();
  96056. }
  96057. this.back.build(back);
  96058. }
  96059. };
  96060. return Node;
  96061. }());
  96062. /**
  96063. * Class for building Constructive Solid Geometry
  96064. */
  96065. var CSG = /** @class */ (function () {
  96066. function CSG() {
  96067. this.polygons = new Array();
  96068. }
  96069. /**
  96070. * Convert the BABYLON.Mesh to BABYLON.CSG
  96071. * @param mesh The BABYLON.Mesh to convert to BABYLON.CSG
  96072. * @returns A new BABYLON.CSG from the BABYLON.Mesh
  96073. */
  96074. CSG.FromMesh = function (mesh) {
  96075. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  96076. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  96077. if (mesh instanceof BABYLON.Mesh) {
  96078. mesh.computeWorldMatrix(true);
  96079. matrix = mesh.getWorldMatrix();
  96080. meshPosition = mesh.position.clone();
  96081. meshRotation = mesh.rotation.clone();
  96082. if (mesh.rotationQuaternion) {
  96083. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  96084. }
  96085. meshScaling = mesh.scaling.clone();
  96086. }
  96087. else {
  96088. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  96089. }
  96090. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  96091. var subMeshes = mesh.subMeshes;
  96092. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  96093. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  96094. vertices = [];
  96095. for (var j = 0; j < 3; j++) {
  96096. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  96097. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  96098. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  96099. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  96100. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  96101. vertex = new Vertex(position, normal, uv);
  96102. vertices.push(vertex);
  96103. }
  96104. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  96105. // To handle the case of degenerated triangle
  96106. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  96107. if (polygon.plane) {
  96108. polygons.push(polygon);
  96109. }
  96110. }
  96111. }
  96112. var csg = CSG.FromPolygons(polygons);
  96113. csg.matrix = matrix;
  96114. csg.position = meshPosition;
  96115. csg.rotation = meshRotation;
  96116. csg.scaling = meshScaling;
  96117. csg.rotationQuaternion = meshRotationQuaternion;
  96118. currentCSGMeshId++;
  96119. return csg;
  96120. };
  96121. /**
  96122. * Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  96123. * @param polygons Polygons used to construct a BABYLON.CSG solid
  96124. */
  96125. CSG.FromPolygons = function (polygons) {
  96126. var csg = new CSG();
  96127. csg.polygons = polygons;
  96128. return csg;
  96129. };
  96130. /**
  96131. * Clones, or makes a deep copy, of the BABYLON.CSG
  96132. * @returns A new BABYLON.CSG
  96133. */
  96134. CSG.prototype.clone = function () {
  96135. var csg = new CSG();
  96136. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  96137. csg.copyTransformAttributes(this);
  96138. return csg;
  96139. };
  96140. /**
  96141. * Unions this CSG with another CSG
  96142. * @param csg The CSG to union against this CSG
  96143. * @returns The unioned CSG
  96144. */
  96145. CSG.prototype.union = function (csg) {
  96146. var a = new Node(this.clone().polygons);
  96147. var b = new Node(csg.clone().polygons);
  96148. a.clipTo(b);
  96149. b.clipTo(a);
  96150. b.invert();
  96151. b.clipTo(a);
  96152. b.invert();
  96153. a.build(b.allPolygons());
  96154. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  96155. };
  96156. /**
  96157. * Unions this CSG with another CSG in place
  96158. * @param csg The CSG to union against this CSG
  96159. */
  96160. CSG.prototype.unionInPlace = function (csg) {
  96161. var a = new Node(this.polygons);
  96162. var b = new Node(csg.polygons);
  96163. a.clipTo(b);
  96164. b.clipTo(a);
  96165. b.invert();
  96166. b.clipTo(a);
  96167. b.invert();
  96168. a.build(b.allPolygons());
  96169. this.polygons = a.allPolygons();
  96170. };
  96171. /**
  96172. * Subtracts this CSG with another CSG
  96173. * @param csg The CSG to subtract against this CSG
  96174. * @returns A new BABYLON.CSG
  96175. */
  96176. CSG.prototype.subtract = function (csg) {
  96177. var a = new Node(this.clone().polygons);
  96178. var b = new Node(csg.clone().polygons);
  96179. a.invert();
  96180. a.clipTo(b);
  96181. b.clipTo(a);
  96182. b.invert();
  96183. b.clipTo(a);
  96184. b.invert();
  96185. a.build(b.allPolygons());
  96186. a.invert();
  96187. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  96188. };
  96189. /**
  96190. * Subtracts this CSG with another CSG in place
  96191. * @param csg The CSG to subtact against this CSG
  96192. */
  96193. CSG.prototype.subtractInPlace = function (csg) {
  96194. var a = new Node(this.polygons);
  96195. var b = new Node(csg.polygons);
  96196. a.invert();
  96197. a.clipTo(b);
  96198. b.clipTo(a);
  96199. b.invert();
  96200. b.clipTo(a);
  96201. b.invert();
  96202. a.build(b.allPolygons());
  96203. a.invert();
  96204. this.polygons = a.allPolygons();
  96205. };
  96206. /**
  96207. * Intersect this CSG with another CSG
  96208. * @param csg The CSG to intersect against this CSG
  96209. * @returns A new BABYLON.CSG
  96210. */
  96211. CSG.prototype.intersect = function (csg) {
  96212. var a = new Node(this.clone().polygons);
  96213. var b = new Node(csg.clone().polygons);
  96214. a.invert();
  96215. b.clipTo(a);
  96216. b.invert();
  96217. a.clipTo(b);
  96218. b.clipTo(a);
  96219. a.build(b.allPolygons());
  96220. a.invert();
  96221. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  96222. };
  96223. /**
  96224. * Intersects this CSG with another CSG in place
  96225. * @param csg The CSG to intersect against this CSG
  96226. */
  96227. CSG.prototype.intersectInPlace = function (csg) {
  96228. var a = new Node(this.polygons);
  96229. var b = new Node(csg.polygons);
  96230. a.invert();
  96231. b.clipTo(a);
  96232. b.invert();
  96233. a.clipTo(b);
  96234. b.clipTo(a);
  96235. a.build(b.allPolygons());
  96236. a.invert();
  96237. this.polygons = a.allPolygons();
  96238. };
  96239. /**
  96240. * Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  96241. * not modified.
  96242. * @returns A new BABYLON.CSG solid with solid and empty space switched
  96243. */
  96244. CSG.prototype.inverse = function () {
  96245. var csg = this.clone();
  96246. csg.inverseInPlace();
  96247. return csg;
  96248. };
  96249. /**
  96250. * Inverses the BABYLON.CSG in place
  96251. */
  96252. CSG.prototype.inverseInPlace = function () {
  96253. this.polygons.map(function (p) { p.flip(); });
  96254. };
  96255. /**
  96256. * This is used to keep meshes transformations so they can be restored
  96257. * when we build back a Babylon Mesh
  96258. * NB : All CSG operations are performed in world coordinates
  96259. * @param csg The BABYLON.CSG to copy the transform attributes from
  96260. * @returns This BABYLON.CSG
  96261. */
  96262. CSG.prototype.copyTransformAttributes = function (csg) {
  96263. this.matrix = csg.matrix;
  96264. this.position = csg.position;
  96265. this.rotation = csg.rotation;
  96266. this.scaling = csg.scaling;
  96267. this.rotationQuaternion = csg.rotationQuaternion;
  96268. return this;
  96269. };
  96270. /**
  96271. * Build Raw mesh from CSG
  96272. * Coordinates here are in world space
  96273. * @param name The name of the mesh geometry
  96274. * @param scene The BABYLON.Scene
  96275. * @param keepSubMeshes Specifies if the submeshes should be kept
  96276. * @returns A new BABYLON.Mesh
  96277. */
  96278. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  96279. var matrix = this.matrix.clone();
  96280. matrix.invert();
  96281. 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;
  96282. if (keepSubMeshes) {
  96283. // Sort Polygons, since subMeshes are indices range
  96284. polygons.sort(function (a, b) {
  96285. if (a.shared.meshId === b.shared.meshId) {
  96286. return a.shared.subMeshId - b.shared.subMeshId;
  96287. }
  96288. else {
  96289. return a.shared.meshId - b.shared.meshId;
  96290. }
  96291. });
  96292. }
  96293. for (var i = 0, il = polygons.length; i < il; i++) {
  96294. polygon = polygons[i];
  96295. // Building SubMeshes
  96296. if (!subMesh_dict[polygon.shared.meshId]) {
  96297. subMesh_dict[polygon.shared.meshId] = {};
  96298. }
  96299. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  96300. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  96301. indexStart: +Infinity,
  96302. indexEnd: -Infinity,
  96303. materialIndex: polygon.shared.materialIndex
  96304. };
  96305. }
  96306. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  96307. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  96308. polygonIndices[0] = 0;
  96309. polygonIndices[1] = j - 1;
  96310. polygonIndices[2] = j;
  96311. for (var k = 0; k < 3; k++) {
  96312. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  96313. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  96314. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  96315. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  96316. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  96317. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  96318. // Check if 2 points can be merged
  96319. if (!(typeof vertex_idx !== 'undefined' &&
  96320. normals[vertex_idx * 3] === localNormal.x &&
  96321. normals[vertex_idx * 3 + 1] === localNormal.y &&
  96322. normals[vertex_idx * 3 + 2] === localNormal.z &&
  96323. uvs[vertex_idx * 2] === uv.x &&
  96324. uvs[vertex_idx * 2 + 1] === uv.y)) {
  96325. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  96326. uvs.push(uv.x, uv.y);
  96327. normals.push(normal.x, normal.y, normal.z);
  96328. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  96329. }
  96330. indices.push(vertex_idx);
  96331. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  96332. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  96333. currentIndex++;
  96334. }
  96335. }
  96336. }
  96337. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  96338. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  96339. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  96340. mesh.setIndices(indices, null);
  96341. if (keepSubMeshes) {
  96342. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  96343. var materialIndexOffset = 0, materialMaxIndex;
  96344. mesh.subMeshes = new Array();
  96345. for (var m in subMesh_dict) {
  96346. materialMaxIndex = -1;
  96347. for (var sm in subMesh_dict[m]) {
  96348. subMesh_obj = subMesh_dict[m][sm];
  96349. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  96350. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  96351. }
  96352. materialIndexOffset += ++materialMaxIndex;
  96353. }
  96354. }
  96355. return mesh;
  96356. };
  96357. /**
  96358. * Build Mesh from CSG taking material and transforms into account
  96359. * @param name The name of the BABYLON.Mesh
  96360. * @param material The material of the BABYLON.Mesh
  96361. * @param scene The BABYLON.Scene
  96362. * @param keepSubMeshes Specifies if submeshes should be kept
  96363. * @returns The new BABYLON.Mesh
  96364. */
  96365. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  96366. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  96367. mesh.material = material;
  96368. mesh.position.copyFrom(this.position);
  96369. mesh.rotation.copyFrom(this.rotation);
  96370. if (this.rotationQuaternion) {
  96371. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  96372. }
  96373. mesh.scaling.copyFrom(this.scaling);
  96374. mesh.computeWorldMatrix(true);
  96375. return mesh;
  96376. };
  96377. return CSG;
  96378. }());
  96379. BABYLON.CSG = CSG;
  96380. })(BABYLON || (BABYLON = {}));
  96381. //# sourceMappingURL=babylon.csg.js.map
  96382. var BABYLON;
  96383. (function (BABYLON) {
  96384. /**
  96385. * This represents one of the lens effect in a `BABYLON.lensFlareSystem`.
  96386. * It controls one of the indiviual texture used in the effect.
  96387. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  96388. */
  96389. var LensFlare = /** @class */ (function () {
  96390. /**
  96391. * Instantiates a new Lens Flare.
  96392. * This represents one of the lens effect in a `BABYLON.lensFlareSystem`.
  96393. * It controls one of the indiviual texture used in the effect.
  96394. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  96395. * @param size Define the size of the lens flare in the system (a floating value between 0 and 1)
  96396. * @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.
  96397. * @param color Define the lens color
  96398. * @param imgUrl Define the lens texture url
  96399. * @param system Define the `lensFlareSystem` this flare is part of
  96400. */
  96401. function LensFlare(
  96402. /**
  96403. * Define the size of the lens flare in the system (a floating value between 0 and 1)
  96404. */
  96405. size,
  96406. /**
  96407. * 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.
  96408. */
  96409. position, color, imgUrl, system) {
  96410. this.size = size;
  96411. this.position = position;
  96412. /**
  96413. * Define the alpha mode to render this particular lens.
  96414. */
  96415. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  96416. this.color = color || new BABYLON.Color3(1, 1, 1);
  96417. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  96418. this._system = system;
  96419. system.lensFlares.push(this);
  96420. }
  96421. /**
  96422. * Creates a new Lens Flare.
  96423. * This represents one of the lens effect in a `BABYLON.lensFlareSystem`.
  96424. * It controls one of the indiviual texture used in the effect.
  96425. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  96426. * @param size Define the size of the lens flare (a floating value between 0 and 1)
  96427. * @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.
  96428. * @param color Define the lens color
  96429. * @param imgUrl Define the lens texture url
  96430. * @param system Define the `lensFlareSystem` this flare is part of
  96431. * @returns The newly created Lens Flare
  96432. */
  96433. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  96434. return new LensFlare(size, position, color, imgUrl, system);
  96435. };
  96436. /**
  96437. * Dispose and release the lens flare with its associated resources.
  96438. */
  96439. LensFlare.prototype.dispose = function () {
  96440. if (this.texture) {
  96441. this.texture.dispose();
  96442. }
  96443. // Remove from scene
  96444. var index = this._system.lensFlares.indexOf(this);
  96445. this._system.lensFlares.splice(index, 1);
  96446. };
  96447. return LensFlare;
  96448. }());
  96449. BABYLON.LensFlare = LensFlare;
  96450. })(BABYLON || (BABYLON = {}));
  96451. //# sourceMappingURL=babylon.lensFlare.js.map
  96452. var BABYLON;
  96453. (function (BABYLON) {
  96454. // Adds the parser to the scene parsers.
  96455. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM, function (parsedData, scene, container, rootUrl) {
  96456. // Lens flares
  96457. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  96458. if (!container.lensFlareSystems) {
  96459. container.lensFlareSystems = new Array();
  96460. }
  96461. for (var index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  96462. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  96463. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  96464. container.lensFlareSystems.push(lf);
  96465. }
  96466. }
  96467. });
  96468. BABYLON.AbstractScene.prototype.getLensFlareSystemByName = function (name) {
  96469. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  96470. if (this.lensFlareSystems[index].name === name) {
  96471. return this.lensFlareSystems[index];
  96472. }
  96473. }
  96474. return null;
  96475. };
  96476. BABYLON.AbstractScene.prototype.getLensFlareSystemByID = function (id) {
  96477. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  96478. if (this.lensFlareSystems[index].id === id) {
  96479. return this.lensFlareSystems[index];
  96480. }
  96481. }
  96482. return null;
  96483. };
  96484. BABYLON.AbstractScene.prototype.removeLensFlareSystem = function (toRemove) {
  96485. var index = this.lensFlareSystems.indexOf(toRemove);
  96486. if (index !== -1) {
  96487. this.lensFlareSystems.splice(index, 1);
  96488. }
  96489. return index;
  96490. };
  96491. BABYLON.AbstractScene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  96492. this.lensFlareSystems.push(newLensFlareSystem);
  96493. };
  96494. /**
  96495. * Defines the lens flare scene component responsible to manage any lens flares
  96496. * in a given scene.
  96497. */
  96498. var LensFlareSystemSceneComponent = /** @class */ (function () {
  96499. /**
  96500. * Creates a new instance of the component for the given scene
  96501. * @param scene Defines the scene to register the component in
  96502. */
  96503. function LensFlareSystemSceneComponent(scene) {
  96504. /**
  96505. * The component name helpfull to identify the component in the list of scene components.
  96506. */
  96507. this.name = BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM;
  96508. this.scene = scene;
  96509. scene.lensFlareSystems = new Array();
  96510. }
  96511. /**
  96512. * Registers the component in a given scene
  96513. */
  96514. LensFlareSystemSceneComponent.prototype.register = function () {
  96515. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM, this, this._draw);
  96516. };
  96517. /**
  96518. * Rebuilds the elements related to this component in case of
  96519. * context lost for instance.
  96520. */
  96521. LensFlareSystemSceneComponent.prototype.rebuild = function () {
  96522. // Nothing to do for lens flare
  96523. };
  96524. /**
  96525. * Adds all the element from the container to the scene
  96526. * @param container the container holding the elements
  96527. */
  96528. LensFlareSystemSceneComponent.prototype.addFromContainer = function (container) {
  96529. var _this = this;
  96530. if (!container.lensFlareSystems) {
  96531. return;
  96532. }
  96533. container.lensFlareSystems.forEach(function (o) {
  96534. _this.scene.addLensFlareSystem(o);
  96535. });
  96536. };
  96537. /**
  96538. * Removes all the elements in the container from the scene
  96539. * @param container contains the elements to remove
  96540. */
  96541. LensFlareSystemSceneComponent.prototype.removeFromContainer = function (container) {
  96542. var _this = this;
  96543. if (!container.lensFlareSystems) {
  96544. return;
  96545. }
  96546. container.lensFlareSystems.forEach(function (o) {
  96547. _this.scene.removeLensFlareSystem(o);
  96548. });
  96549. };
  96550. /**
  96551. * Serializes the component data to the specified json object
  96552. * @param serializationObject The object to serialize to
  96553. */
  96554. LensFlareSystemSceneComponent.prototype.serialize = function (serializationObject) {
  96555. // Lens flares
  96556. serializationObject.lensFlareSystems = [];
  96557. var lensFlareSystems = this.scene.lensFlareSystems;
  96558. for (var _i = 0, lensFlareSystems_1 = lensFlareSystems; _i < lensFlareSystems_1.length; _i++) {
  96559. var lensFlareSystem = lensFlareSystems_1[_i];
  96560. serializationObject.lensFlareSystems.push(lensFlareSystem.serialize());
  96561. }
  96562. };
  96563. /**
  96564. * Disposes the component and the associated ressources.
  96565. */
  96566. LensFlareSystemSceneComponent.prototype.dispose = function () {
  96567. var lensFlareSystems = this.scene.lensFlareSystems;
  96568. while (lensFlareSystems.length) {
  96569. lensFlareSystems[0].dispose();
  96570. }
  96571. };
  96572. LensFlareSystemSceneComponent.prototype._draw = function (camera) {
  96573. // Lens flares
  96574. if (this.scene.lensFlaresEnabled) {
  96575. var lensFlareSystems = this.scene.lensFlareSystems;
  96576. BABYLON.Tools.StartPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
  96577. for (var _i = 0, lensFlareSystems_2 = lensFlareSystems; _i < lensFlareSystems_2.length; _i++) {
  96578. var lensFlareSystem = lensFlareSystems_2[_i];
  96579. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  96580. lensFlareSystem.render();
  96581. }
  96582. }
  96583. BABYLON.Tools.EndPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
  96584. }
  96585. };
  96586. return LensFlareSystemSceneComponent;
  96587. }());
  96588. BABYLON.LensFlareSystemSceneComponent = LensFlareSystemSceneComponent;
  96589. })(BABYLON || (BABYLON = {}));
  96590. //# sourceMappingURL=babylon.lensFlareSystemSceneComponent.js.map
  96591. var BABYLON;
  96592. (function (BABYLON) {
  96593. /**
  96594. * This represents a Lens Flare System or the shiny effect created by the light reflection on the camera lenses.
  96595. * It is usually composed of several `BABYLON.lensFlare`.
  96596. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  96597. */
  96598. var LensFlareSystem = /** @class */ (function () {
  96599. /**
  96600. * Instantiates a lens flare system.
  96601. * This represents a Lens Flare System or the shiny effect created by the light reflection on the camera lenses.
  96602. * It is usually composed of several `BABYLON.lensFlare`.
  96603. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  96604. * @param name Define the name of the lens flare system in the scene
  96605. * @param emitter Define the source (the emitter) of the lens flares (it can be a camera, a light or a mesh).
  96606. * @param scene Define the scene the lens flare system belongs to
  96607. */
  96608. function LensFlareSystem(
  96609. /**
  96610. * Define the name of the lens flare system
  96611. */
  96612. name, emitter, scene) {
  96613. this.name = name;
  96614. /**
  96615. * List of lens flares used in this system.
  96616. */
  96617. this.lensFlares = new Array();
  96618. /**
  96619. * Define a limit from the border the lens flare can be visible.
  96620. */
  96621. this.borderLimit = 300;
  96622. /**
  96623. * Define a viewport border we do not want to see the lens flare in.
  96624. */
  96625. this.viewportBorder = 0;
  96626. /**
  96627. * Restricts the rendering of the effect to only the camera rendering this layer mask.
  96628. */
  96629. this.layerMask = 0x0FFFFFFF;
  96630. this._vertexBuffers = {};
  96631. this._isEnabled = true;
  96632. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  96633. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM);
  96634. if (!component) {
  96635. component = new BABYLON.LensFlareSystemSceneComponent(this._scene);
  96636. scene._addComponent(component);
  96637. }
  96638. this._emitter = emitter;
  96639. this.id = name;
  96640. scene.lensFlareSystems.push(this);
  96641. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  96642. var engine = scene.getEngine();
  96643. // VBO
  96644. var vertices = [];
  96645. vertices.push(1, 1);
  96646. vertices.push(-1, 1);
  96647. vertices.push(-1, -1);
  96648. vertices.push(1, -1);
  96649. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  96650. // Indices
  96651. var indices = [];
  96652. indices.push(0);
  96653. indices.push(1);
  96654. indices.push(2);
  96655. indices.push(0);
  96656. indices.push(2);
  96657. indices.push(3);
  96658. this._indexBuffer = engine.createIndexBuffer(indices);
  96659. // Effects
  96660. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  96661. }
  96662. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  96663. /**
  96664. * Define if the lens flare system is enabled.
  96665. */
  96666. get: function () {
  96667. return this._isEnabled;
  96668. },
  96669. set: function (value) {
  96670. this._isEnabled = value;
  96671. },
  96672. enumerable: true,
  96673. configurable: true
  96674. });
  96675. /**
  96676. * Get the scene the effects belongs to.
  96677. * @returns the scene holding the lens flare system
  96678. */
  96679. LensFlareSystem.prototype.getScene = function () {
  96680. return this._scene;
  96681. };
  96682. /**
  96683. * Get the emitter of the lens flare system.
  96684. * It defines the source of the lens flares (it can be a camera, a light or a mesh).
  96685. * @returns the emitter of the lens flare system
  96686. */
  96687. LensFlareSystem.prototype.getEmitter = function () {
  96688. return this._emitter;
  96689. };
  96690. /**
  96691. * Set the emitter of the lens flare system.
  96692. * It defines the source of the lens flares (it can be a camera, a light or a mesh).
  96693. * @param newEmitter Define the new emitter of the system
  96694. */
  96695. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  96696. this._emitter = newEmitter;
  96697. };
  96698. /**
  96699. * Get the lens flare system emitter position.
  96700. * The emitter defines the source of the lens flares (it can be a camera, a light or a mesh).
  96701. * @returns the position
  96702. */
  96703. LensFlareSystem.prototype.getEmitterPosition = function () {
  96704. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  96705. };
  96706. /**
  96707. * @hidden
  96708. */
  96709. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  96710. var position = this.getEmitterPosition();
  96711. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  96712. this._positionX = position.x;
  96713. this._positionY = position.y;
  96714. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  96715. if (this.viewportBorder > 0) {
  96716. globalViewport.x -= this.viewportBorder;
  96717. globalViewport.y -= this.viewportBorder;
  96718. globalViewport.width += this.viewportBorder * 2;
  96719. globalViewport.height += this.viewportBorder * 2;
  96720. position.x += this.viewportBorder;
  96721. position.y += this.viewportBorder;
  96722. this._positionX += this.viewportBorder;
  96723. this._positionY += this.viewportBorder;
  96724. }
  96725. if (position.z > 0) {
  96726. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  96727. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height)) {
  96728. return true;
  96729. }
  96730. }
  96731. return true;
  96732. }
  96733. return false;
  96734. };
  96735. /** @hidden */
  96736. LensFlareSystem.prototype._isVisible = function () {
  96737. if (!this._isEnabled || !this._scene.activeCamera) {
  96738. return false;
  96739. }
  96740. var emitterPosition = this.getEmitterPosition();
  96741. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  96742. var distance = direction.length();
  96743. direction.normalize();
  96744. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  96745. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  96746. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  96747. };
  96748. /**
  96749. * @hidden
  96750. */
  96751. LensFlareSystem.prototype.render = function () {
  96752. if (!this._effect.isReady() || !this._scene.activeCamera) {
  96753. return false;
  96754. }
  96755. var engine = this._scene.getEngine();
  96756. var viewport = this._scene.activeCamera.viewport;
  96757. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  96758. // Position
  96759. if (!this.computeEffectivePosition(globalViewport)) {
  96760. return false;
  96761. }
  96762. // Visibility
  96763. if (!this._isVisible()) {
  96764. return false;
  96765. }
  96766. // Intensity
  96767. var awayX;
  96768. var awayY;
  96769. if (this._positionX < this.borderLimit + globalViewport.x) {
  96770. awayX = this.borderLimit + globalViewport.x - this._positionX;
  96771. }
  96772. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  96773. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  96774. }
  96775. else {
  96776. awayX = 0;
  96777. }
  96778. if (this._positionY < this.borderLimit + globalViewport.y) {
  96779. awayY = this.borderLimit + globalViewport.y - this._positionY;
  96780. }
  96781. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  96782. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  96783. }
  96784. else {
  96785. awayY = 0;
  96786. }
  96787. var away = (awayX > awayY) ? awayX : awayY;
  96788. away -= this.viewportBorder;
  96789. if (away > this.borderLimit) {
  96790. away = this.borderLimit;
  96791. }
  96792. var intensity = 1.0 - BABYLON.Scalar.Clamp(away / this.borderLimit, 0, 1);
  96793. if (intensity < 0) {
  96794. return false;
  96795. }
  96796. if (intensity > 1.0) {
  96797. intensity = 1.0;
  96798. }
  96799. if (this.viewportBorder > 0) {
  96800. globalViewport.x += this.viewportBorder;
  96801. globalViewport.y += this.viewportBorder;
  96802. globalViewport.width -= this.viewportBorder * 2;
  96803. globalViewport.height -= this.viewportBorder * 2;
  96804. this._positionX -= this.viewportBorder;
  96805. this._positionY -= this.viewportBorder;
  96806. }
  96807. // Position
  96808. var centerX = globalViewport.x + globalViewport.width / 2;
  96809. var centerY = globalViewport.y + globalViewport.height / 2;
  96810. var distX = centerX - this._positionX;
  96811. var distY = centerY - this._positionY;
  96812. // Effects
  96813. engine.enableEffect(this._effect);
  96814. engine.setState(false);
  96815. engine.setDepthBuffer(false);
  96816. // VBOs
  96817. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  96818. // Flares
  96819. for (var index = 0; index < this.lensFlares.length; index++) {
  96820. var flare = this.lensFlares[index];
  96821. engine.setAlphaMode(flare.alphaMode);
  96822. var x = centerX - (distX * flare.position);
  96823. var y = centerY - (distY * flare.position);
  96824. var cw = flare.size;
  96825. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  96826. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  96827. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  96828. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  96829. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  96830. // Texture
  96831. this._effect.setTexture("textureSampler", flare.texture);
  96832. // Color
  96833. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  96834. // Draw order
  96835. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  96836. }
  96837. engine.setDepthBuffer(true);
  96838. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  96839. return true;
  96840. };
  96841. /**
  96842. * Dispose and release the lens flare with its associated resources.
  96843. */
  96844. LensFlareSystem.prototype.dispose = function () {
  96845. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  96846. if (vertexBuffer) {
  96847. vertexBuffer.dispose();
  96848. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  96849. }
  96850. if (this._indexBuffer) {
  96851. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  96852. this._indexBuffer = null;
  96853. }
  96854. while (this.lensFlares.length) {
  96855. this.lensFlares[0].dispose();
  96856. }
  96857. // Remove from scene
  96858. var index = this._scene.lensFlareSystems.indexOf(this);
  96859. this._scene.lensFlareSystems.splice(index, 1);
  96860. };
  96861. /**
  96862. * Parse a lens flare system from a JSON repressentation
  96863. * @param parsedLensFlareSystem Define the JSON to parse
  96864. * @param scene Define the scene the parsed system should be instantiated in
  96865. * @param rootUrl Define the rootUrl of the load sequence to easily find a load relative dependencies such as textures
  96866. * @returns the parsed system
  96867. */
  96868. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  96869. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  96870. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  96871. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  96872. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  96873. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  96874. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  96875. var parsedFlare = parsedLensFlareSystem.flares[index];
  96876. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  96877. }
  96878. return lensFlareSystem;
  96879. };
  96880. /**
  96881. * Serialize the current Lens Flare System into a JSON representation.
  96882. * @returns the serialized JSON
  96883. */
  96884. LensFlareSystem.prototype.serialize = function () {
  96885. var serializationObject = {};
  96886. serializationObject.id = this.id;
  96887. serializationObject.name = this.name;
  96888. serializationObject.emitterId = this.getEmitter().id;
  96889. serializationObject.borderLimit = this.borderLimit;
  96890. serializationObject.flares = [];
  96891. for (var index = 0; index < this.lensFlares.length; index++) {
  96892. var flare = this.lensFlares[index];
  96893. serializationObject.flares.push({
  96894. size: flare.size,
  96895. position: flare.position,
  96896. color: flare.color.asArray(),
  96897. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  96898. });
  96899. }
  96900. return serializationObject;
  96901. };
  96902. return LensFlareSystem;
  96903. }());
  96904. BABYLON.LensFlareSystem = LensFlareSystem;
  96905. })(BABYLON || (BABYLON = {}));
  96906. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  96907. var BABYLON;
  96908. (function (BABYLON) {
  96909. /**
  96910. * This is a holder class for the physics joint created by the physics plugin
  96911. * It holds a set of functions to control the underlying joint
  96912. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  96913. */
  96914. var PhysicsJoint = /** @class */ (function () {
  96915. /**
  96916. * Initializes the physics joint
  96917. * @param type The type of the physics joint
  96918. * @param jointData The data for the physics joint
  96919. */
  96920. function PhysicsJoint(
  96921. /**
  96922. * The type of the physics joint
  96923. */
  96924. type,
  96925. /**
  96926. * The data for the physics joint
  96927. */
  96928. jointData) {
  96929. this.type = type;
  96930. this.jointData = jointData;
  96931. jointData.nativeParams = jointData.nativeParams || {};
  96932. }
  96933. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  96934. /**
  96935. * Gets the physics joint
  96936. */
  96937. get: function () {
  96938. return this._physicsJoint;
  96939. },
  96940. /**
  96941. * Sets the physics joint
  96942. */
  96943. set: function (newJoint) {
  96944. if (this._physicsJoint) {
  96945. //remove from the wolrd
  96946. }
  96947. this._physicsJoint = newJoint;
  96948. },
  96949. enumerable: true,
  96950. configurable: true
  96951. });
  96952. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  96953. /**
  96954. * Sets the physics plugin
  96955. */
  96956. set: function (physicsPlugin) {
  96957. this._physicsPlugin = physicsPlugin;
  96958. },
  96959. enumerable: true,
  96960. configurable: true
  96961. });
  96962. /**
  96963. * Execute a function that is physics-plugin specific.
  96964. * @param {Function} func the function that will be executed.
  96965. * It accepts two parameters: the physics world and the physics joint
  96966. */
  96967. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  96968. func(this._physicsPlugin.world, this._physicsJoint);
  96969. };
  96970. //TODO check if the native joints are the same
  96971. //Joint Types
  96972. /**
  96973. * Distance-Joint type
  96974. */
  96975. PhysicsJoint.DistanceJoint = 0;
  96976. /**
  96977. * Hinge-Joint type
  96978. */
  96979. PhysicsJoint.HingeJoint = 1;
  96980. /**
  96981. * Ball-and-Socket joint type
  96982. */
  96983. PhysicsJoint.BallAndSocketJoint = 2;
  96984. /**
  96985. * Wheel-Joint type
  96986. */
  96987. PhysicsJoint.WheelJoint = 3;
  96988. /**
  96989. * Slider-Joint type
  96990. */
  96991. PhysicsJoint.SliderJoint = 4;
  96992. //OIMO
  96993. /**
  96994. * Prismatic-Joint type
  96995. */
  96996. PhysicsJoint.PrismaticJoint = 5;
  96997. //
  96998. /**
  96999. * Universal-Joint type
  97000. * ENERGY FTW! (compare with this - @see http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  97001. */
  97002. PhysicsJoint.UniversalJoint = 6;
  97003. /**
  97004. * Hinge-Joint 2 type
  97005. */
  97006. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  97007. //Cannon
  97008. /**
  97009. * Point to Point Joint type. Similar to a Ball-Joint. Different in parameters
  97010. */
  97011. PhysicsJoint.PointToPointJoint = 8;
  97012. //Cannon only at the moment
  97013. /**
  97014. * Spring-Joint type
  97015. */
  97016. PhysicsJoint.SpringJoint = 9;
  97017. /**
  97018. * Lock-Joint type
  97019. */
  97020. PhysicsJoint.LockJoint = 10;
  97021. return PhysicsJoint;
  97022. }());
  97023. BABYLON.PhysicsJoint = PhysicsJoint;
  97024. /**
  97025. * A class representing a physics distance joint
  97026. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  97027. */
  97028. var DistanceJoint = /** @class */ (function (_super) {
  97029. __extends(DistanceJoint, _super);
  97030. /**
  97031. *
  97032. * @param jointData The data for the Distance-Joint
  97033. */
  97034. function DistanceJoint(jointData) {
  97035. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  97036. }
  97037. /**
  97038. * Update the predefined distance.
  97039. * @param maxDistance The maximum preferred distance
  97040. * @param minDistance The minimum preferred distance
  97041. */
  97042. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  97043. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  97044. };
  97045. return DistanceJoint;
  97046. }(PhysicsJoint));
  97047. BABYLON.DistanceJoint = DistanceJoint;
  97048. /**
  97049. * Represents a Motor-Enabled Joint
  97050. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  97051. */
  97052. var MotorEnabledJoint = /** @class */ (function (_super) {
  97053. __extends(MotorEnabledJoint, _super);
  97054. /**
  97055. * Initializes the Motor-Enabled Joint
  97056. * @param type The type of the joint
  97057. * @param jointData The physica joint data for the joint
  97058. */
  97059. function MotorEnabledJoint(type, jointData) {
  97060. return _super.call(this, type, jointData) || this;
  97061. }
  97062. /**
  97063. * Set the motor values.
  97064. * Attention, this function is plugin specific. Engines won't react 100% the same.
  97065. * @param force the force to apply
  97066. * @param maxForce max force for this motor.
  97067. */
  97068. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  97069. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  97070. };
  97071. /**
  97072. * Set the motor's limits.
  97073. * Attention, this function is plugin specific. Engines won't react 100% the same.
  97074. * @param upperLimit The upper limit of the motor
  97075. * @param lowerLimit The lower limit of the motor
  97076. */
  97077. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  97078. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  97079. };
  97080. return MotorEnabledJoint;
  97081. }(PhysicsJoint));
  97082. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  97083. /**
  97084. * This class represents a single physics Hinge-Joint
  97085. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  97086. */
  97087. var HingeJoint = /** @class */ (function (_super) {
  97088. __extends(HingeJoint, _super);
  97089. /**
  97090. * Initializes the Hinge-Joint
  97091. * @param jointData The joint data for the Hinge-Joint
  97092. */
  97093. function HingeJoint(jointData) {
  97094. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  97095. }
  97096. /**
  97097. * Set the motor values.
  97098. * Attention, this function is plugin specific. Engines won't react 100% the same.
  97099. * @param {number} force the force to apply
  97100. * @param {number} maxForce max force for this motor.
  97101. */
  97102. HingeJoint.prototype.setMotor = function (force, maxForce) {
  97103. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  97104. };
  97105. /**
  97106. * Set the motor's limits.
  97107. * Attention, this function is plugin specific. Engines won't react 100% the same.
  97108. * @param upperLimit The upper limit of the motor
  97109. * @param lowerLimit The lower limit of the motor
  97110. */
  97111. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  97112. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  97113. };
  97114. return HingeJoint;
  97115. }(MotorEnabledJoint));
  97116. BABYLON.HingeJoint = HingeJoint;
  97117. /**
  97118. * This class represents a dual hinge physics joint (same as wheel joint)
  97119. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  97120. */
  97121. var Hinge2Joint = /** @class */ (function (_super) {
  97122. __extends(Hinge2Joint, _super);
  97123. /**
  97124. * Initializes the Hinge2-Joint
  97125. * @param jointData The joint data for the Hinge2-Joint
  97126. */
  97127. function Hinge2Joint(jointData) {
  97128. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  97129. }
  97130. /**
  97131. * Set the motor values.
  97132. * Attention, this function is plugin specific. Engines won't react 100% the same.
  97133. * @param {number} force the force to apply
  97134. * @param {number} maxForce max force for this motor.
  97135. * @param {motorIndex} the motor's index, 0 or 1.
  97136. */
  97137. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  97138. if (motorIndex === void 0) { motorIndex = 0; }
  97139. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  97140. };
  97141. /**
  97142. * Set the motor limits.
  97143. * Attention, this function is plugin specific. Engines won't react 100% the same.
  97144. * @param {number} upperLimit the upper limit
  97145. * @param {number} lowerLimit lower limit
  97146. * @param {motorIndex} the motor's index, 0 or 1.
  97147. */
  97148. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  97149. if (motorIndex === void 0) { motorIndex = 0; }
  97150. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  97151. };
  97152. return Hinge2Joint;
  97153. }(MotorEnabledJoint));
  97154. BABYLON.Hinge2Joint = Hinge2Joint;
  97155. })(BABYLON || (BABYLON = {}));
  97156. //# sourceMappingURL=babylon.physicsJoint.js.map
  97157. var BABYLON;
  97158. (function (BABYLON) {
  97159. /**
  97160. * Represents a physics imposter
  97161. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  97162. */
  97163. var PhysicsImpostor = /** @class */ (function () {
  97164. /**
  97165. * Initializes the physics imposter
  97166. * @param object The physics-enabled object used as the physics imposter
  97167. * @param type The type of the physics imposter
  97168. * @param _options The options for the physics imposter
  97169. * @param _scene The Babylon scene
  97170. */
  97171. function PhysicsImpostor(
  97172. /**
  97173. * The physics-enabled object used as the physics imposter
  97174. */
  97175. object,
  97176. /**
  97177. * The type of the physics imposter
  97178. */
  97179. type, _options, _scene) {
  97180. if (_options === void 0) { _options = { mass: 0 }; }
  97181. var _this = this;
  97182. this.object = object;
  97183. this.type = type;
  97184. this._options = _options;
  97185. this._scene = _scene;
  97186. this._bodyUpdateRequired = false;
  97187. this._onBeforePhysicsStepCallbacks = new Array();
  97188. this._onAfterPhysicsStepCallbacks = new Array();
  97189. /** @hidden */
  97190. this._onPhysicsCollideCallbacks = [];
  97191. this._deltaPosition = BABYLON.Vector3.Zero();
  97192. this._isDisposed = false;
  97193. //temp variables for parent rotation calculations
  97194. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  97195. this._tmpQuat = new BABYLON.Quaternion();
  97196. this._tmpQuat2 = new BABYLON.Quaternion();
  97197. /**
  97198. * this function is executed by the physics engine.
  97199. */
  97200. this.beforeStep = function () {
  97201. if (!_this._physicsEngine) {
  97202. return;
  97203. }
  97204. _this.object.translate(_this._deltaPosition, -1);
  97205. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  97206. _this.object.computeWorldMatrix(false);
  97207. if (_this.object.parent && _this.object.rotationQuaternion) {
  97208. _this.getParentsRotation();
  97209. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  97210. }
  97211. else {
  97212. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  97213. }
  97214. if (!_this._options.disableBidirectionalTransformation) {
  97215. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePosition(), _this._tmpQuat);
  97216. }
  97217. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  97218. func(_this);
  97219. });
  97220. };
  97221. /**
  97222. * this function is executed by the physics engine
  97223. */
  97224. this.afterStep = function () {
  97225. if (!_this._physicsEngine) {
  97226. return;
  97227. }
  97228. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  97229. func(_this);
  97230. });
  97231. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  97232. // object has now its world rotation. needs to be converted to local.
  97233. if (_this.object.parent && _this.object.rotationQuaternion) {
  97234. _this.getParentsRotation();
  97235. _this._tmpQuat.conjugateInPlace();
  97236. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  97237. }
  97238. // take the position set and make it the absolute position of this object.
  97239. _this.object.setAbsolutePosition(_this.object.position);
  97240. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  97241. _this.object.translate(_this._deltaPosition, 1);
  97242. };
  97243. /**
  97244. * Legacy collision detection event support
  97245. */
  97246. this.onCollideEvent = null;
  97247. /**
  97248. * event and body object due to cannon's event-based architecture.
  97249. */
  97250. this.onCollide = function (e) {
  97251. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  97252. return;
  97253. }
  97254. if (!_this._physicsEngine) {
  97255. return;
  97256. }
  97257. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  97258. if (otherImpostor) {
  97259. // Legacy collision detection event support
  97260. if (_this.onCollideEvent) {
  97261. _this.onCollideEvent(_this, otherImpostor);
  97262. }
  97263. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  97264. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  97265. }).forEach(function (obj) {
  97266. obj.callback(_this, otherImpostor);
  97267. });
  97268. }
  97269. };
  97270. //sanity check!
  97271. if (!this.object) {
  97272. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  97273. return;
  97274. }
  97275. // Legacy support for old syntax.
  97276. if (!this._scene && object.getScene) {
  97277. this._scene = object.getScene();
  97278. }
  97279. if (!this._scene) {
  97280. return;
  97281. }
  97282. this._physicsEngine = this._scene.getPhysicsEngine();
  97283. if (!this._physicsEngine) {
  97284. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  97285. }
  97286. else {
  97287. //set the object's quaternion, if not set
  97288. if (!this.object.rotationQuaternion) {
  97289. if (this.object.rotation) {
  97290. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  97291. }
  97292. else {
  97293. this.object.rotationQuaternion = new BABYLON.Quaternion();
  97294. }
  97295. }
  97296. //default options params
  97297. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  97298. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  97299. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  97300. this._joints = [];
  97301. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  97302. if (!this.object.parent || this._options.ignoreParent) {
  97303. this._init();
  97304. }
  97305. else if (this.object.parent.physicsImpostor) {
  97306. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  97307. }
  97308. }
  97309. }
  97310. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  97311. /**
  97312. * Specifies if the physics imposter is disposed
  97313. */
  97314. get: function () {
  97315. return this._isDisposed;
  97316. },
  97317. enumerable: true,
  97318. configurable: true
  97319. });
  97320. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  97321. /**
  97322. * Gets the mass of the physics imposter
  97323. */
  97324. get: function () {
  97325. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  97326. },
  97327. set: function (value) {
  97328. this.setMass(value);
  97329. },
  97330. enumerable: true,
  97331. configurable: true
  97332. });
  97333. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  97334. /**
  97335. * Gets the coefficient of friction
  97336. */
  97337. get: function () {
  97338. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  97339. },
  97340. /**
  97341. * Sets the coefficient of friction
  97342. */
  97343. set: function (value) {
  97344. if (!this._physicsEngine) {
  97345. return;
  97346. }
  97347. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  97348. },
  97349. enumerable: true,
  97350. configurable: true
  97351. });
  97352. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  97353. /**
  97354. * Gets the coefficient of restitution
  97355. */
  97356. get: function () {
  97357. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  97358. },
  97359. /**
  97360. * Sets the coefficient of restitution
  97361. */
  97362. set: function (value) {
  97363. if (!this._physicsEngine) {
  97364. return;
  97365. }
  97366. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  97367. },
  97368. enumerable: true,
  97369. configurable: true
  97370. });
  97371. /**
  97372. * This function will completly initialize this impostor.
  97373. * It will create a new body - but only if this mesh has no parent.
  97374. * If it has, this impostor will not be used other than to define the impostor
  97375. * of the child mesh.
  97376. * @hidden
  97377. */
  97378. PhysicsImpostor.prototype._init = function () {
  97379. if (!this._physicsEngine) {
  97380. return;
  97381. }
  97382. this._physicsEngine.removeImpostor(this);
  97383. this.physicsBody = null;
  97384. this._parent = this._parent || this._getPhysicsParent();
  97385. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  97386. this._physicsEngine.addImpostor(this);
  97387. }
  97388. };
  97389. PhysicsImpostor.prototype._getPhysicsParent = function () {
  97390. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  97391. var parentMesh = this.object.parent;
  97392. return parentMesh.physicsImpostor;
  97393. }
  97394. return null;
  97395. };
  97396. /**
  97397. * Should a new body be generated.
  97398. * @returns boolean specifying if body initialization is required
  97399. */
  97400. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  97401. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  97402. };
  97403. /**
  97404. * Sets the updated scaling
  97405. * @param updated Specifies if the scaling is updated
  97406. */
  97407. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  97408. this.forceUpdate();
  97409. };
  97410. /**
  97411. * Force a regeneration of this or the parent's impostor's body.
  97412. * Use under cautious - This will remove all joints already implemented.
  97413. */
  97414. PhysicsImpostor.prototype.forceUpdate = function () {
  97415. this._init();
  97416. if (this.parent && !this._options.ignoreParent) {
  97417. this.parent.forceUpdate();
  97418. }
  97419. };
  97420. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  97421. /*public get mesh(): AbstractMesh {
  97422. return this._mesh;
  97423. }*/
  97424. /**
  97425. * Gets the body that holds this impostor. Either its own, or its parent.
  97426. */
  97427. get: function () {
  97428. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  97429. },
  97430. /**
  97431. * Set the physics body. Used mainly by the physics engine/plugin
  97432. */
  97433. set: function (physicsBody) {
  97434. if (this._physicsBody && this._physicsEngine) {
  97435. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  97436. }
  97437. this._physicsBody = physicsBody;
  97438. this.resetUpdateFlags();
  97439. },
  97440. enumerable: true,
  97441. configurable: true
  97442. });
  97443. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  97444. /**
  97445. * Get the parent of the physics imposter
  97446. * @returns Physics imposter or null
  97447. */
  97448. get: function () {
  97449. return !this._options.ignoreParent && this._parent ? this._parent : null;
  97450. },
  97451. /**
  97452. * Sets the parent of the physics imposter
  97453. */
  97454. set: function (value) {
  97455. this._parent = value;
  97456. },
  97457. enumerable: true,
  97458. configurable: true
  97459. });
  97460. /**
  97461. * Resets the update flags
  97462. */
  97463. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  97464. this._bodyUpdateRequired = false;
  97465. };
  97466. /**
  97467. * Gets the object extend size
  97468. * @returns the object extend size
  97469. */
  97470. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  97471. if (this.object.getBoundingInfo) {
  97472. var q = this.object.rotationQuaternion;
  97473. //reset rotation
  97474. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  97475. //calculate the world matrix with no rotation
  97476. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  97477. var boundingInfo = this.object.getBoundingInfo();
  97478. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  97479. //bring back the rotation
  97480. this.object.rotationQuaternion = q;
  97481. //calculate the world matrix with the new rotation
  97482. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  97483. return size;
  97484. }
  97485. else {
  97486. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  97487. }
  97488. };
  97489. /**
  97490. * Gets the object center
  97491. * @returns The object center
  97492. */
  97493. PhysicsImpostor.prototype.getObjectCenter = function () {
  97494. if (this.object.getBoundingInfo) {
  97495. var boundingInfo = this.object.getBoundingInfo();
  97496. return boundingInfo.boundingBox.centerWorld;
  97497. }
  97498. else {
  97499. return this.object.position;
  97500. }
  97501. };
  97502. /**
  97503. * Get a specific parametes from the options parameter
  97504. * @param paramName The object parameter name
  97505. * @returns The object parameter
  97506. */
  97507. PhysicsImpostor.prototype.getParam = function (paramName) {
  97508. return this._options[paramName];
  97509. };
  97510. /**
  97511. * Sets a specific parameter in the options given to the physics plugin
  97512. * @param paramName The parameter name
  97513. * @param value The value of the parameter
  97514. */
  97515. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  97516. this._options[paramName] = value;
  97517. this._bodyUpdateRequired = true;
  97518. };
  97519. /**
  97520. * Specifically change the body's mass option. Won't recreate the physics body object
  97521. * @param mass The mass of the physics imposter
  97522. */
  97523. PhysicsImpostor.prototype.setMass = function (mass) {
  97524. if (this.getParam("mass") !== mass) {
  97525. this.setParam("mass", mass);
  97526. }
  97527. if (this._physicsEngine) {
  97528. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  97529. }
  97530. };
  97531. /**
  97532. * Gets the linear velocity
  97533. * @returns linear velocity or null
  97534. */
  97535. PhysicsImpostor.prototype.getLinearVelocity = function () {
  97536. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  97537. };
  97538. /**
  97539. * Sets the linear velocity
  97540. * @param velocity linear velocity or null
  97541. */
  97542. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  97543. if (this._physicsEngine) {
  97544. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  97545. }
  97546. };
  97547. /**
  97548. * Gets the angular velocity
  97549. * @returns angular velocity or null
  97550. */
  97551. PhysicsImpostor.prototype.getAngularVelocity = function () {
  97552. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  97553. };
  97554. /**
  97555. * Sets the angular velocity
  97556. * @param velocity The velocity or null
  97557. */
  97558. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  97559. if (this._physicsEngine) {
  97560. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  97561. }
  97562. };
  97563. /**
  97564. * Execute a function with the physics plugin native code
  97565. * Provide a function the will have two variables - the world object and the physics body object
  97566. * @param func The function to execute with the physics plugin native code
  97567. */
  97568. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  97569. if (this._physicsEngine) {
  97570. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  97571. }
  97572. };
  97573. /**
  97574. * Register a function that will be executed before the physics world is stepping forward
  97575. * @param func The function to execute before the physics world is stepped forward
  97576. */
  97577. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  97578. this._onBeforePhysicsStepCallbacks.push(func);
  97579. };
  97580. /**
  97581. * Unregister a function that will be executed before the physics world is stepping forward
  97582. * @param func The function to execute before the physics world is stepped forward
  97583. */
  97584. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  97585. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  97586. if (index > -1) {
  97587. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  97588. }
  97589. else {
  97590. BABYLON.Tools.Warn("Function to remove was not found");
  97591. }
  97592. };
  97593. /**
  97594. * Register a function that will be executed after the physics step
  97595. * @param func The function to execute after physics step
  97596. */
  97597. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  97598. this._onAfterPhysicsStepCallbacks.push(func);
  97599. };
  97600. /**
  97601. * Unregisters a function that will be executed after the physics step
  97602. * @param func The function to execute after physics step
  97603. */
  97604. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  97605. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  97606. if (index > -1) {
  97607. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  97608. }
  97609. else {
  97610. BABYLON.Tools.Warn("Function to remove was not found");
  97611. }
  97612. };
  97613. /**
  97614. * register a function that will be executed when this impostor collides against a different body
  97615. * @param collideAgainst Physics imposter, or array of physics imposters to collide against
  97616. * @param func Callback that is executed on collision
  97617. */
  97618. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  97619. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  97620. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  97621. };
  97622. /**
  97623. * Unregisters the physics imposter on contact
  97624. * @param collideAgainst The physics object to collide against
  97625. * @param func Callback to execute on collision
  97626. */
  97627. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  97628. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  97629. var index = -1;
  97630. var found = this._onPhysicsCollideCallbacks.some(function (cbDef, idx) {
  97631. if (cbDef.callback === func && cbDef.otherImpostors.length === collidedAgainstList.length) {
  97632. // chcek the arrays match
  97633. var sameList = cbDef.otherImpostors.every(function (impostor) {
  97634. return collidedAgainstList.indexOf(impostor) > -1;
  97635. });
  97636. if (sameList) {
  97637. index = idx;
  97638. }
  97639. return sameList;
  97640. }
  97641. return false;
  97642. });
  97643. if (found) {
  97644. this._onPhysicsCollideCallbacks.splice(index, 1);
  97645. }
  97646. else {
  97647. BABYLON.Tools.Warn("Function to remove was not found");
  97648. }
  97649. };
  97650. /**
  97651. * Get the parent rotation
  97652. * @returns The parent rotation
  97653. */
  97654. PhysicsImpostor.prototype.getParentsRotation = function () {
  97655. var parent = this.object.parent;
  97656. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  97657. while (parent) {
  97658. if (parent.rotationQuaternion) {
  97659. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  97660. }
  97661. else {
  97662. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  97663. }
  97664. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  97665. parent = parent.parent;
  97666. }
  97667. return this._tmpQuat;
  97668. };
  97669. /**
  97670. * Apply a force
  97671. * @param force The force to apply
  97672. * @param contactPoint The contact point for the force
  97673. * @returns The physics imposter
  97674. */
  97675. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  97676. if (this._physicsEngine) {
  97677. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  97678. }
  97679. return this;
  97680. };
  97681. /**
  97682. * Apply an impulse
  97683. * @param force The impulse force
  97684. * @param contactPoint The contact point for the impulse force
  97685. * @returns The physics imposter
  97686. */
  97687. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  97688. if (this._physicsEngine) {
  97689. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  97690. }
  97691. return this;
  97692. };
  97693. /**
  97694. * A help function to create a joint
  97695. * @param otherImpostor A physics imposter used to create a joint
  97696. * @param jointType The type of joint
  97697. * @param jointData The data for the joint
  97698. * @returns The physics imposter
  97699. */
  97700. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  97701. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  97702. this.addJoint(otherImpostor, joint);
  97703. return this;
  97704. };
  97705. /**
  97706. * Add a joint to this impostor with a different impostor
  97707. * @param otherImpostor A physics imposter used to add a joint
  97708. * @param joint The joint to add
  97709. * @returns The physics imposter
  97710. */
  97711. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  97712. this._joints.push({
  97713. otherImpostor: otherImpostor,
  97714. joint: joint
  97715. });
  97716. if (this._physicsEngine) {
  97717. this._physicsEngine.addJoint(this, otherImpostor, joint);
  97718. }
  97719. return this;
  97720. };
  97721. /**
  97722. * Will keep this body still, in a sleep mode.
  97723. * @returns the physics imposter
  97724. */
  97725. PhysicsImpostor.prototype.sleep = function () {
  97726. if (this._physicsEngine) {
  97727. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  97728. }
  97729. return this;
  97730. };
  97731. /**
  97732. * Wake the body up.
  97733. * @returns The physics imposter
  97734. */
  97735. PhysicsImpostor.prototype.wakeUp = function () {
  97736. if (this._physicsEngine) {
  97737. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  97738. }
  97739. return this;
  97740. };
  97741. /**
  97742. * Clones the physics imposter
  97743. * @param newObject The physics imposter clones to this physics-enabled object
  97744. * @returns A nullable physics imposter
  97745. */
  97746. PhysicsImpostor.prototype.clone = function (newObject) {
  97747. if (!newObject) {
  97748. return null;
  97749. }
  97750. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  97751. };
  97752. /**
  97753. * Disposes the physics imposter
  97754. */
  97755. PhysicsImpostor.prototype.dispose = function ( /*disposeChildren: boolean = true*/) {
  97756. var _this = this;
  97757. //no dispose if no physics engine is available.
  97758. if (!this._physicsEngine) {
  97759. return;
  97760. }
  97761. this._joints.forEach(function (j) {
  97762. if (_this._physicsEngine) {
  97763. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  97764. }
  97765. });
  97766. //dispose the physics body
  97767. this._physicsEngine.removeImpostor(this);
  97768. if (this.parent) {
  97769. this.parent.forceUpdate();
  97770. }
  97771. else {
  97772. /*this._object.getChildMeshes().forEach(function(mesh) {
  97773. if (mesh.physicsImpostor) {
  97774. if (disposeChildren) {
  97775. mesh.physicsImpostor.dispose();
  97776. mesh.physicsImpostor = null;
  97777. }
  97778. }
  97779. })*/
  97780. }
  97781. this._isDisposed = true;
  97782. };
  97783. /**
  97784. * Sets the delta position
  97785. * @param position The delta position amount
  97786. */
  97787. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  97788. this._deltaPosition.copyFrom(position);
  97789. };
  97790. /**
  97791. * Sets the delta rotation
  97792. * @param rotation The delta rotation amount
  97793. */
  97794. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  97795. if (!this._deltaRotation) {
  97796. this._deltaRotation = new BABYLON.Quaternion();
  97797. }
  97798. this._deltaRotation.copyFrom(rotation);
  97799. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  97800. };
  97801. /**
  97802. * Gets the box size of the physics imposter and stores the result in the input parameter
  97803. * @param result Stores the box size
  97804. * @returns The physics imposter
  97805. */
  97806. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  97807. if (this._physicsEngine) {
  97808. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  97809. }
  97810. return this;
  97811. };
  97812. /**
  97813. * Gets the radius of the physics imposter
  97814. * @returns Radius of the physics imposter
  97815. */
  97816. PhysicsImpostor.prototype.getRadius = function () {
  97817. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  97818. };
  97819. /**
  97820. * Sync a bone with this impostor
  97821. * @param bone The bone to sync to the impostor.
  97822. * @param boneMesh The mesh that the bone is influencing.
  97823. * @param jointPivot The pivot of the joint / bone in local space.
  97824. * @param distToJoint Optional distance from the impostor to the joint.
  97825. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  97826. */
  97827. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  97828. var tempVec = PhysicsImpostor._tmpVecs[0];
  97829. var mesh = this.object;
  97830. if (mesh.rotationQuaternion) {
  97831. if (adjustRotation) {
  97832. var tempQuat = PhysicsImpostor._tmpQuat;
  97833. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  97834. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  97835. }
  97836. else {
  97837. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  97838. }
  97839. }
  97840. tempVec.x = 0;
  97841. tempVec.y = 0;
  97842. tempVec.z = 0;
  97843. if (jointPivot) {
  97844. tempVec.x = jointPivot.x;
  97845. tempVec.y = jointPivot.y;
  97846. tempVec.z = jointPivot.z;
  97847. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  97848. if (distToJoint === undefined || distToJoint === null) {
  97849. distToJoint = jointPivot.length();
  97850. }
  97851. tempVec.x *= distToJoint;
  97852. tempVec.y *= distToJoint;
  97853. tempVec.z *= distToJoint;
  97854. }
  97855. if (bone.getParent()) {
  97856. tempVec.addInPlace(mesh.getAbsolutePosition());
  97857. bone.setAbsolutePosition(tempVec, boneMesh);
  97858. }
  97859. else {
  97860. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  97861. boneMesh.position.x -= tempVec.x;
  97862. boneMesh.position.y -= tempVec.y;
  97863. boneMesh.position.z -= tempVec.z;
  97864. }
  97865. };
  97866. /**
  97867. * Sync impostor to a bone
  97868. * @param bone The bone that the impostor will be synced to.
  97869. * @param boneMesh The mesh that the bone is influencing.
  97870. * @param jointPivot The pivot of the joint / bone in local space.
  97871. * @param distToJoint Optional distance from the impostor to the joint.
  97872. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  97873. * @param boneAxis Optional vector3 axis the bone is aligned with
  97874. */
  97875. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  97876. var mesh = this.object;
  97877. if (mesh.rotationQuaternion) {
  97878. if (adjustRotation) {
  97879. var tempQuat = PhysicsImpostor._tmpQuat;
  97880. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  97881. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  97882. }
  97883. else {
  97884. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  97885. }
  97886. }
  97887. var pos = PhysicsImpostor._tmpVecs[0];
  97888. var boneDir = PhysicsImpostor._tmpVecs[1];
  97889. if (!boneAxis) {
  97890. boneAxis = PhysicsImpostor._tmpVecs[2];
  97891. boneAxis.x = 0;
  97892. boneAxis.y = 1;
  97893. boneAxis.z = 0;
  97894. }
  97895. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  97896. bone.getAbsolutePositionToRef(boneMesh, pos);
  97897. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  97898. distToJoint = jointPivot.length();
  97899. }
  97900. if (distToJoint !== undefined && distToJoint !== null) {
  97901. pos.x += boneDir.x * distToJoint;
  97902. pos.y += boneDir.y * distToJoint;
  97903. pos.z += boneDir.z * distToJoint;
  97904. }
  97905. mesh.setAbsolutePosition(pos);
  97906. };
  97907. /**
  97908. * The default object size of the imposter
  97909. */
  97910. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  97911. /**
  97912. * The identity quaternion of the imposter
  97913. */
  97914. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  97915. PhysicsImpostor._tmpVecs = BABYLON.Tools.BuildArray(3, BABYLON.Vector3.Zero);
  97916. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  97917. //Impostor types
  97918. /**
  97919. * No-Imposter type
  97920. */
  97921. PhysicsImpostor.NoImpostor = 0;
  97922. /**
  97923. * Sphere-Imposter type
  97924. */
  97925. PhysicsImpostor.SphereImpostor = 1;
  97926. /**
  97927. * Box-Imposter type
  97928. */
  97929. PhysicsImpostor.BoxImpostor = 2;
  97930. /**
  97931. * Plane-Imposter type
  97932. */
  97933. PhysicsImpostor.PlaneImpostor = 3;
  97934. /**
  97935. * Mesh-imposter type
  97936. */
  97937. PhysicsImpostor.MeshImpostor = 4;
  97938. /**
  97939. * Cylinder-Imposter type
  97940. */
  97941. PhysicsImpostor.CylinderImpostor = 7;
  97942. /**
  97943. * Particle-Imposter type
  97944. */
  97945. PhysicsImpostor.ParticleImpostor = 8;
  97946. /**
  97947. * Heightmap-Imposter type
  97948. */
  97949. PhysicsImpostor.HeightmapImpostor = 9;
  97950. return PhysicsImpostor;
  97951. }());
  97952. BABYLON.PhysicsImpostor = PhysicsImpostor;
  97953. })(BABYLON || (BABYLON = {}));
  97954. //# sourceMappingURL=babylon.physicsImpostor.js.map
  97955. var BABYLON;
  97956. (function (BABYLON) {
  97957. /**
  97958. * Class used to control physics engine
  97959. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  97960. */
  97961. var PhysicsEngine = /** @class */ (function () {
  97962. /**
  97963. * Creates a new Physics Engine
  97964. * @param gravity defines the gravity vector used by the simulation
  97965. * @param _physicsPlugin defines the plugin to use (CannonJS by default)
  97966. */
  97967. function PhysicsEngine(gravity, _physicsPlugin) {
  97968. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  97969. this._physicsPlugin = _physicsPlugin;
  97970. this._impostors = [];
  97971. this._joints = [];
  97972. if (!this._physicsPlugin.isSupported()) {
  97973. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  97974. + "Please make sure it is included.");
  97975. }
  97976. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  97977. this.setGravity(gravity);
  97978. this.setTimeStep();
  97979. }
  97980. /**
  97981. * Sets the gravity vector used by the simulation
  97982. * @param gravity defines the gravity vector to use
  97983. */
  97984. PhysicsEngine.prototype.setGravity = function (gravity) {
  97985. this.gravity = gravity;
  97986. this._physicsPlugin.setGravity(this.gravity);
  97987. };
  97988. /**
  97989. * Set the time step of the physics engine.
  97990. * Default is 1/60.
  97991. * To slow it down, enter 1/600 for example.
  97992. * To speed it up, 1/30
  97993. * @param newTimeStep defines the new timestep to apply to this world.
  97994. */
  97995. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  97996. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  97997. this._physicsPlugin.setTimeStep(newTimeStep);
  97998. };
  97999. /**
  98000. * Get the time step of the physics engine.
  98001. * @returns the current time step
  98002. */
  98003. PhysicsEngine.prototype.getTimeStep = function () {
  98004. return this._physicsPlugin.getTimeStep();
  98005. };
  98006. /**
  98007. * Release all resources
  98008. */
  98009. PhysicsEngine.prototype.dispose = function () {
  98010. this._impostors.forEach(function (impostor) {
  98011. impostor.dispose();
  98012. });
  98013. this._physicsPlugin.dispose();
  98014. };
  98015. /**
  98016. * Gets the name of the current physics plugin
  98017. * @returns the name of the plugin
  98018. */
  98019. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  98020. return this._physicsPlugin.name;
  98021. };
  98022. /**
  98023. * Adding a new impostor for the impostor tracking.
  98024. * This will be done by the impostor itself.
  98025. * @param impostor the impostor to add
  98026. */
  98027. PhysicsEngine.prototype.addImpostor = function (impostor) {
  98028. impostor.uniqueId = this._impostors.push(impostor);
  98029. //if no parent, generate the body
  98030. if (!impostor.parent) {
  98031. this._physicsPlugin.generatePhysicsBody(impostor);
  98032. }
  98033. };
  98034. /**
  98035. * Remove an impostor from the engine.
  98036. * This impostor and its mesh will not longer be updated by the physics engine.
  98037. * @param impostor the impostor to remove
  98038. */
  98039. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  98040. var index = this._impostors.indexOf(impostor);
  98041. if (index > -1) {
  98042. var removed = this._impostors.splice(index, 1);
  98043. //Is it needed?
  98044. if (removed.length) {
  98045. //this will also remove it from the world.
  98046. removed[0].physicsBody = null;
  98047. }
  98048. }
  98049. };
  98050. /**
  98051. * Add a joint to the physics engine
  98052. * @param mainImpostor defines the main impostor to which the joint is added.
  98053. * @param connectedImpostor defines the impostor that is connected to the main impostor using this joint
  98054. * @param joint defines the joint that will connect both impostors.
  98055. */
  98056. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  98057. var impostorJoint = {
  98058. mainImpostor: mainImpostor,
  98059. connectedImpostor: connectedImpostor,
  98060. joint: joint
  98061. };
  98062. joint.physicsPlugin = this._physicsPlugin;
  98063. this._joints.push(impostorJoint);
  98064. this._physicsPlugin.generateJoint(impostorJoint);
  98065. };
  98066. /**
  98067. * Removes a joint from the simulation
  98068. * @param mainImpostor defines the impostor used with the joint
  98069. * @param connectedImpostor defines the other impostor connected to the main one by the joint
  98070. * @param joint defines the joint to remove
  98071. */
  98072. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  98073. var matchingJoints = this._joints.filter(function (impostorJoint) {
  98074. return (impostorJoint.connectedImpostor === connectedImpostor
  98075. && impostorJoint.joint === joint
  98076. && impostorJoint.mainImpostor === mainImpostor);
  98077. });
  98078. if (matchingJoints.length) {
  98079. this._physicsPlugin.removeJoint(matchingJoints[0]);
  98080. //TODO remove it from the list as well
  98081. }
  98082. };
  98083. /**
  98084. * Called by the scene. No need to call it.
  98085. * @param delta defines the timespam between frames
  98086. */
  98087. PhysicsEngine.prototype._step = function (delta) {
  98088. var _this = this;
  98089. //check if any mesh has no body / requires an update
  98090. this._impostors.forEach(function (impostor) {
  98091. if (impostor.isBodyInitRequired()) {
  98092. _this._physicsPlugin.generatePhysicsBody(impostor);
  98093. }
  98094. });
  98095. if (delta > 0.1) {
  98096. delta = 0.1;
  98097. }
  98098. else if (delta <= 0) {
  98099. delta = 1.0 / 60.0;
  98100. }
  98101. this._physicsPlugin.executeStep(delta, this._impostors);
  98102. };
  98103. /**
  98104. * Gets the current plugin used to run the simulation
  98105. * @returns current plugin
  98106. */
  98107. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  98108. return this._physicsPlugin;
  98109. };
  98110. /**
  98111. * Gets the list of physic impostors
  98112. * @returns an array of PhysicsImpostor
  98113. */
  98114. PhysicsEngine.prototype.getImpostors = function () {
  98115. return this._impostors;
  98116. };
  98117. /**
  98118. * Gets the impostor for a physics enabled object
  98119. * @param object defines the object impersonated by the impostor
  98120. * @returns the PhysicsImpostor or null if not found
  98121. */
  98122. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  98123. for (var i = 0; i < this._impostors.length; ++i) {
  98124. if (this._impostors[i].object === object) {
  98125. return this._impostors[i];
  98126. }
  98127. }
  98128. return null;
  98129. };
  98130. /**
  98131. * Gets the impostor for a physics body object
  98132. * @param body defines physics body used by the impostor
  98133. * @returns the PhysicsImpostor or null if not found
  98134. */
  98135. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  98136. for (var i = 0; i < this._impostors.length; ++i) {
  98137. if (this._impostors[i].physicsBody === body) {
  98138. return this._impostors[i];
  98139. }
  98140. }
  98141. return null;
  98142. };
  98143. /**
  98144. * Global value used to control the smallest number supported by the simulation
  98145. */
  98146. PhysicsEngine.Epsilon = 0.001;
  98147. return PhysicsEngine;
  98148. }());
  98149. BABYLON.PhysicsEngine = PhysicsEngine;
  98150. })(BABYLON || (BABYLON = {}));
  98151. //# sourceMappingURL=babylon.physicsEngine.js.map
  98152. var BABYLON;
  98153. (function (BABYLON) {
  98154. /**
  98155. * A helper for physics simulations
  98156. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  98157. */
  98158. var PhysicsHelper = /** @class */ (function () {
  98159. /**
  98160. * Initializes the Physics helper
  98161. * @param scene Babylon.js scene
  98162. */
  98163. function PhysicsHelper(scene) {
  98164. this._scene = scene;
  98165. this._physicsEngine = this._scene.getPhysicsEngine();
  98166. if (!this._physicsEngine) {
  98167. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  98168. }
  98169. }
  98170. /**
  98171. * Applies a radial explosion impulse
  98172. * @param origin the origin of the explosion
  98173. * @param radius the explosion radius
  98174. * @param strength the explosion strength
  98175. * @param falloff possible options: Constant & Linear. Defaults to Constant
  98176. * @returns A physics radial explosion event, or null
  98177. */
  98178. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  98179. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  98180. if (!this._physicsEngine) {
  98181. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  98182. return null;
  98183. }
  98184. var impostors = this._physicsEngine.getImpostors();
  98185. if (impostors.length === 0) {
  98186. return null;
  98187. }
  98188. var event = new PhysicsRadialExplosionEvent(this._scene);
  98189. impostors.forEach(function (impostor) {
  98190. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  98191. if (!impostorForceAndContactPoint) {
  98192. return;
  98193. }
  98194. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  98195. });
  98196. event.dispose(false);
  98197. return event;
  98198. };
  98199. /**
  98200. * Applies a radial explosion force
  98201. * @param origin the origin of the explosion
  98202. * @param radius the explosion radius
  98203. * @param strength the explosion strength
  98204. * @param falloff possible options: Constant & Linear. Defaults to Constant
  98205. * @returns A physics radial explosion event, or null
  98206. */
  98207. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  98208. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  98209. if (!this._physicsEngine) {
  98210. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  98211. return null;
  98212. }
  98213. var impostors = this._physicsEngine.getImpostors();
  98214. if (impostors.length === 0) {
  98215. return null;
  98216. }
  98217. var event = new PhysicsRadialExplosionEvent(this._scene);
  98218. impostors.forEach(function (impostor) {
  98219. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  98220. if (!impostorForceAndContactPoint) {
  98221. return;
  98222. }
  98223. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  98224. });
  98225. event.dispose(false);
  98226. return event;
  98227. };
  98228. /**
  98229. * Creates a gravitational field
  98230. * @param origin the origin of the explosion
  98231. * @param radius the explosion radius
  98232. * @param strength the explosion strength
  98233. * @param falloff possible options: Constant & Linear. Defaults to Constant
  98234. * @returns A physics gravitational field event, or null
  98235. */
  98236. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  98237. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  98238. if (!this._physicsEngine) {
  98239. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  98240. return null;
  98241. }
  98242. var impostors = this._physicsEngine.getImpostors();
  98243. if (impostors.length === 0) {
  98244. return null;
  98245. }
  98246. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  98247. event.dispose(false);
  98248. return event;
  98249. };
  98250. /**
  98251. * Creates a physics updraft event
  98252. * @param origin the origin of the updraft
  98253. * @param radius the radius of the updraft
  98254. * @param strength the strength of the updraft
  98255. * @param height the height of the updraft
  98256. * @param updraftMode possible options: Center & Perpendicular. Defaults to Center
  98257. * @returns A physics updraft event, or null
  98258. */
  98259. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  98260. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  98261. if (!this._physicsEngine) {
  98262. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  98263. return null;
  98264. }
  98265. if (this._physicsEngine.getImpostors().length === 0) {
  98266. return null;
  98267. }
  98268. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  98269. event.dispose(false);
  98270. return event;
  98271. };
  98272. /**
  98273. * Creates a physics vortex event
  98274. * @param origin the of the vortex
  98275. * @param radius the radius of the vortex
  98276. * @param strength the strength of the vortex
  98277. * @param height the height of the vortex
  98278. * @returns a Physics vortex event, or null
  98279. * A physics vortex event or null
  98280. */
  98281. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  98282. if (!this._physicsEngine) {
  98283. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  98284. return null;
  98285. }
  98286. if (this._physicsEngine.getImpostors().length === 0) {
  98287. return null;
  98288. }
  98289. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  98290. event.dispose(false);
  98291. return event;
  98292. };
  98293. return PhysicsHelper;
  98294. }());
  98295. BABYLON.PhysicsHelper = PhysicsHelper;
  98296. /**
  98297. * Represents a physics radial explosion event
  98298. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  98299. */
  98300. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  98301. /**
  98302. * Initializes a radial explosioin event
  98303. * @param scene BabylonJS scene
  98304. */
  98305. function PhysicsRadialExplosionEvent(scene) {
  98306. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  98307. this._rays = [];
  98308. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  98309. this._scene = scene;
  98310. }
  98311. /**
  98312. * Returns the data related to the radial explosion event (sphere & rays).
  98313. * @returns The radial explosion event data
  98314. */
  98315. PhysicsRadialExplosionEvent.prototype.getData = function () {
  98316. this._dataFetched = true;
  98317. return {
  98318. sphere: this._sphere,
  98319. rays: this._rays,
  98320. };
  98321. };
  98322. /**
  98323. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  98324. * @param impostor A physics imposter
  98325. * @param origin the origin of the explosion
  98326. * @param radius the explosion radius
  98327. * @param strength the explosion strength
  98328. * @param falloff possible options: Constant & Linear
  98329. * @returns {Nullable<PhysicsForceAndContactPoint>} A physics force and contact point, or null
  98330. */
  98331. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  98332. if (impostor.mass === 0) {
  98333. return null;
  98334. }
  98335. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  98336. return null;
  98337. }
  98338. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  98339. return null;
  98340. }
  98341. var impostorObjectCenter = impostor.getObjectCenter();
  98342. var direction = impostorObjectCenter.subtract(origin);
  98343. var ray = new BABYLON.Ray(origin, direction, radius);
  98344. this._rays.push(ray);
  98345. var hit = ray.intersectsMesh(impostor.object);
  98346. var contactPoint = hit.pickedPoint;
  98347. if (!contactPoint) {
  98348. return null;
  98349. }
  98350. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  98351. if (distanceFromOrigin > radius) {
  98352. return null;
  98353. }
  98354. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  98355. ? strength
  98356. : strength * (1 - (distanceFromOrigin / radius));
  98357. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  98358. return { force: force, contactPoint: contactPoint };
  98359. };
  98360. /**
  98361. * Disposes the sphere.
  98362. * @param force Specifies if the sphere should be disposed by force
  98363. */
  98364. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  98365. var _this = this;
  98366. if (force === void 0) { force = true; }
  98367. if (force) {
  98368. this._sphere.dispose();
  98369. }
  98370. else {
  98371. setTimeout(function () {
  98372. if (!_this._dataFetched) {
  98373. _this._sphere.dispose();
  98374. }
  98375. }, 0);
  98376. }
  98377. };
  98378. /*** Helpers ***/
  98379. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  98380. if (!this._sphere) {
  98381. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  98382. this._sphere.isVisible = false;
  98383. }
  98384. };
  98385. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  98386. var impostorObject = impostor.object;
  98387. this._prepareSphere();
  98388. this._sphere.position = origin;
  98389. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  98390. this._sphere._updateBoundingInfo();
  98391. this._sphere.computeWorldMatrix(true);
  98392. return this._sphere.intersectsMesh(impostorObject, true);
  98393. };
  98394. return PhysicsRadialExplosionEvent;
  98395. }());
  98396. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  98397. /**
  98398. * Represents a gravitational field event
  98399. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  98400. */
  98401. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  98402. /**
  98403. * Initializes the physics gravitational field event
  98404. * @param physicsHelper A physics helper
  98405. * @param scene BabylonJS scene
  98406. * @param origin The origin position of the gravitational field event
  98407. * @param radius The radius of the gravitational field event
  98408. * @param strength The strength of the gravitational field event
  98409. * @param falloff The falloff for the gravitational field event
  98410. */
  98411. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  98412. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  98413. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  98414. this._physicsHelper = physicsHelper;
  98415. this._scene = scene;
  98416. this._origin = origin;
  98417. this._radius = radius;
  98418. this._strength = strength;
  98419. this._falloff = falloff;
  98420. this._tickCallback = this._tick.bind(this);
  98421. }
  98422. /**
  98423. * Returns the data related to the gravitational field event (sphere).
  98424. * @returns A gravitational field event
  98425. */
  98426. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  98427. this._dataFetched = true;
  98428. return {
  98429. sphere: this._sphere,
  98430. };
  98431. };
  98432. /**
  98433. * Enables the gravitational field.
  98434. */
  98435. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  98436. this._tickCallback.call(this);
  98437. this._scene.registerBeforeRender(this._tickCallback);
  98438. };
  98439. /**
  98440. * Disables the gravitational field.
  98441. */
  98442. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  98443. this._scene.unregisterBeforeRender(this._tickCallback);
  98444. };
  98445. /**
  98446. * Disposes the sphere.
  98447. * @param force The force to dispose from the gravitational field event
  98448. */
  98449. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  98450. var _this = this;
  98451. if (force === void 0) { force = true; }
  98452. if (force) {
  98453. this._sphere.dispose();
  98454. }
  98455. else {
  98456. setTimeout(function () {
  98457. if (!_this._dataFetched) {
  98458. _this._sphere.dispose();
  98459. }
  98460. }, 0);
  98461. }
  98462. };
  98463. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  98464. // Since the params won't change, we fetch the event only once
  98465. if (this._sphere) {
  98466. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  98467. }
  98468. else {
  98469. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  98470. if (radialExplosionEvent) {
  98471. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  98472. }
  98473. }
  98474. };
  98475. return PhysicsGravitationalFieldEvent;
  98476. }());
  98477. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  98478. /**
  98479. * Represents a physics updraft event
  98480. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  98481. */
  98482. var PhysicsUpdraftEvent = /** @class */ (function () {
  98483. /**
  98484. * Initializes the physics updraft event
  98485. * @param _scene BabylonJS scene
  98486. * @param _origin The origin position of the updraft
  98487. * @param _radius The radius of the updraft
  98488. * @param _strength The strength of the updraft
  98489. * @param _height The height of the updraft
  98490. * @param _updraftMode The mode of the updraft
  98491. */
  98492. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  98493. this._scene = _scene;
  98494. this._origin = _origin;
  98495. this._radius = _radius;
  98496. this._strength = _strength;
  98497. this._height = _height;
  98498. this._updraftMode = _updraftMode;
  98499. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  98500. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  98501. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  98502. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  98503. this._physicsEngine = this._scene.getPhysicsEngine();
  98504. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  98505. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  98506. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  98507. this._originDirection = this._origin.subtract(this._originTop).normalize();
  98508. }
  98509. this._tickCallback = this._tick.bind(this);
  98510. this._prepareCylinder();
  98511. }
  98512. /**
  98513. * Returns the data related to the updraft event (cylinder).
  98514. * @returns A physics updraft event
  98515. */
  98516. PhysicsUpdraftEvent.prototype.getData = function () {
  98517. this._dataFetched = true;
  98518. return {
  98519. cylinder: this._cylinder,
  98520. };
  98521. };
  98522. /**
  98523. * Enables the updraft.
  98524. */
  98525. PhysicsUpdraftEvent.prototype.enable = function () {
  98526. this._tickCallback.call(this);
  98527. this._scene.registerBeforeRender(this._tickCallback);
  98528. };
  98529. /**
  98530. * Disables the cortex.
  98531. */
  98532. PhysicsUpdraftEvent.prototype.disable = function () {
  98533. this._scene.unregisterBeforeRender(this._tickCallback);
  98534. };
  98535. /**
  98536. * Disposes the sphere.
  98537. * @param force Specifies if the updraft should be disposed by force
  98538. */
  98539. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  98540. var _this = this;
  98541. if (force === void 0) { force = true; }
  98542. if (!this._cylinder) {
  98543. return;
  98544. }
  98545. if (force) {
  98546. this._cylinder.dispose();
  98547. }
  98548. else {
  98549. setTimeout(function () {
  98550. if (!_this._dataFetched) {
  98551. _this._cylinder.dispose();
  98552. }
  98553. }, 0);
  98554. }
  98555. };
  98556. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  98557. if (impostor.mass === 0) {
  98558. return null;
  98559. }
  98560. if (!this._intersectsWithCylinder(impostor)) {
  98561. return null;
  98562. }
  98563. var impostorObjectCenter = impostor.getObjectCenter();
  98564. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  98565. var direction = this._originDirection;
  98566. }
  98567. else {
  98568. var direction = impostorObjectCenter.subtract(this._originTop);
  98569. }
  98570. var multiplier = this._strength * -1;
  98571. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  98572. return { force: force, contactPoint: impostorObjectCenter };
  98573. };
  98574. PhysicsUpdraftEvent.prototype._tick = function () {
  98575. var _this = this;
  98576. this._physicsEngine.getImpostors().forEach(function (impostor) {
  98577. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  98578. if (!impostorForceAndContactPoint) {
  98579. return;
  98580. }
  98581. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  98582. });
  98583. };
  98584. /*** Helpers ***/
  98585. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  98586. if (!this._cylinder) {
  98587. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  98588. height: this._height,
  98589. diameter: this._radius * 2,
  98590. }, this._scene);
  98591. this._cylinder.isVisible = false;
  98592. }
  98593. };
  98594. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  98595. var impostorObject = impostor.object;
  98596. this._cylinder.position = this._cylinderPosition;
  98597. return this._cylinder.intersectsMesh(impostorObject, true);
  98598. };
  98599. return PhysicsUpdraftEvent;
  98600. }());
  98601. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  98602. /**
  98603. * Represents a physics vortex event
  98604. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  98605. */
  98606. var PhysicsVortexEvent = /** @class */ (function () {
  98607. /**
  98608. * Initializes the physics vortex event
  98609. * @param _scene The BabylonJS scene
  98610. * @param _origin The origin position of the vortex
  98611. * @param _radius The radius of the vortex
  98612. * @param _strength The strength of the vortex
  98613. * @param _height The height of the vortex
  98614. */
  98615. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  98616. this._scene = _scene;
  98617. this._origin = _origin;
  98618. this._radius = _radius;
  98619. this._strength = _strength;
  98620. this._height = _height;
  98621. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  98622. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  98623. this._updraftMultiplier = 0.02;
  98624. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  98625. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  98626. this._physicsEngine = this._scene.getPhysicsEngine();
  98627. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  98628. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  98629. this._tickCallback = this._tick.bind(this);
  98630. this._prepareCylinder();
  98631. }
  98632. /**
  98633. * Returns the data related to the vortex event (cylinder).
  98634. * @returns The physics vortex event data
  98635. */
  98636. PhysicsVortexEvent.prototype.getData = function () {
  98637. this._dataFetched = true;
  98638. return {
  98639. cylinder: this._cylinder,
  98640. };
  98641. };
  98642. /**
  98643. * Enables the vortex.
  98644. */
  98645. PhysicsVortexEvent.prototype.enable = function () {
  98646. this._tickCallback.call(this);
  98647. this._scene.registerBeforeRender(this._tickCallback);
  98648. };
  98649. /**
  98650. * Disables the cortex.
  98651. */
  98652. PhysicsVortexEvent.prototype.disable = function () {
  98653. this._scene.unregisterBeforeRender(this._tickCallback);
  98654. };
  98655. /**
  98656. * Disposes the sphere.
  98657. * @param force
  98658. */
  98659. PhysicsVortexEvent.prototype.dispose = function (force) {
  98660. var _this = this;
  98661. if (force === void 0) { force = true; }
  98662. if (force) {
  98663. this._cylinder.dispose();
  98664. }
  98665. else {
  98666. setTimeout(function () {
  98667. if (!_this._dataFetched) {
  98668. _this._cylinder.dispose();
  98669. }
  98670. }, 0);
  98671. }
  98672. };
  98673. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  98674. if (impostor.mass === 0) {
  98675. return null;
  98676. }
  98677. if (!this._intersectsWithCylinder(impostor)) {
  98678. return null;
  98679. }
  98680. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  98681. return null;
  98682. }
  98683. var impostorObjectCenter = impostor.getObjectCenter();
  98684. 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)
  98685. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  98686. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  98687. var hit = ray.intersectsMesh(impostor.object);
  98688. var contactPoint = hit.pickedPoint;
  98689. if (!contactPoint) {
  98690. return null;
  98691. }
  98692. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  98693. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  98694. var directionToOrigin = contactPoint.normalize();
  98695. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  98696. directionToOrigin = directionToOrigin.negate();
  98697. }
  98698. // TODO: find a more physically based solution
  98699. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  98700. var forceX = directionToOrigin.x * this._strength / 8;
  98701. var forceY = directionToOrigin.y * this._updraftMultiplier;
  98702. var forceZ = directionToOrigin.z * this._strength / 8;
  98703. }
  98704. else {
  98705. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  98706. var forceY = this._originTop.y * this._updraftMultiplier;
  98707. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  98708. }
  98709. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  98710. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  98711. return { force: force, contactPoint: impostorObjectCenter };
  98712. };
  98713. PhysicsVortexEvent.prototype._tick = function () {
  98714. var _this = this;
  98715. this._physicsEngine.getImpostors().forEach(function (impostor) {
  98716. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  98717. if (!impostorForceAndContactPoint) {
  98718. return;
  98719. }
  98720. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  98721. });
  98722. };
  98723. /*** Helpers ***/
  98724. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  98725. if (!this._cylinder) {
  98726. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  98727. height: this._height,
  98728. diameter: this._radius * 2,
  98729. }, this._scene);
  98730. this._cylinder.isVisible = false;
  98731. }
  98732. };
  98733. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  98734. var impostorObject = impostor.object;
  98735. this._cylinder.position = this._cylinderPosition;
  98736. return this._cylinder.intersectsMesh(impostorObject, true);
  98737. };
  98738. return PhysicsVortexEvent;
  98739. }());
  98740. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  98741. /**
  98742. * The strenght of the force in correspondence to the distance of the affected object
  98743. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  98744. */
  98745. var PhysicsRadialImpulseFalloff;
  98746. (function (PhysicsRadialImpulseFalloff) {
  98747. /** Defines that impulse is constant in strength across it's whole radius */
  98748. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  98749. /** DEfines that impulse gets weaker if it's further from the origin */
  98750. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear";
  98751. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  98752. /**
  98753. * The strength of the force in correspondence to the distance of the affected object
  98754. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  98755. */
  98756. var PhysicsUpdraftMode;
  98757. (function (PhysicsUpdraftMode) {
  98758. /** Defines that the upstream forces will pull towards the top center of the cylinder */
  98759. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  98760. /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */
  98761. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular";
  98762. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  98763. })(BABYLON || (BABYLON = {}));
  98764. //# sourceMappingURL=babylon.physicsHelper.js.map
  98765. var BABYLON;
  98766. (function (BABYLON) {
  98767. /** @hidden */
  98768. var CannonJSPlugin = /** @class */ (function () {
  98769. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  98770. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  98771. if (iterations === void 0) { iterations = 10; }
  98772. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  98773. this.name = "CannonJSPlugin";
  98774. this._physicsMaterials = new Array();
  98775. this._fixedTimeStep = 1 / 60;
  98776. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  98777. this.BJSCANNON = CANNON;
  98778. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  98779. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  98780. this._tmpPosition = BABYLON.Vector3.Zero();
  98781. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  98782. this._tmpUnityRotation = new BABYLON.Quaternion();
  98783. if (!this.isSupported()) {
  98784. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  98785. return;
  98786. }
  98787. this._extendNamespace();
  98788. this.world = new this.BJSCANNON.World();
  98789. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  98790. this.world.solver.iterations = iterations;
  98791. }
  98792. CannonJSPlugin.prototype.setGravity = function (gravity) {
  98793. this.world.gravity.copy(gravity);
  98794. };
  98795. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  98796. this._fixedTimeStep = timeStep;
  98797. };
  98798. CannonJSPlugin.prototype.getTimeStep = function () {
  98799. return this._fixedTimeStep;
  98800. };
  98801. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  98802. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  98803. };
  98804. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  98805. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  98806. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  98807. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  98808. };
  98809. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  98810. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  98811. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  98812. impostor.physicsBody.applyForce(impulse, worldPoint);
  98813. };
  98814. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  98815. //parent-child relationship. Does this impostor has a parent impostor?
  98816. if (impostor.parent) {
  98817. if (impostor.physicsBody) {
  98818. this.removePhysicsBody(impostor);
  98819. //TODO is that needed?
  98820. impostor.forceUpdate();
  98821. }
  98822. return;
  98823. }
  98824. //should a new body be created for this impostor?
  98825. if (impostor.isBodyInitRequired()) {
  98826. var shape = this._createShape(impostor);
  98827. //unregister events, if body is being changed
  98828. var oldBody = impostor.physicsBody;
  98829. if (oldBody) {
  98830. this.removePhysicsBody(impostor);
  98831. }
  98832. //create the body and material
  98833. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  98834. var bodyCreationObject = {
  98835. mass: impostor.getParam("mass"),
  98836. material: material
  98837. };
  98838. // A simple extend, in case native options were used.
  98839. var nativeOptions = impostor.getParam("nativeOptions");
  98840. for (var key in nativeOptions) {
  98841. if (nativeOptions.hasOwnProperty(key)) {
  98842. bodyCreationObject[key] = nativeOptions[key];
  98843. }
  98844. }
  98845. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  98846. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  98847. this.world.addEventListener("preStep", impostor.beforeStep);
  98848. this.world.addEventListener("postStep", impostor.afterStep);
  98849. impostor.physicsBody.addShape(shape);
  98850. this.world.add(impostor.physicsBody);
  98851. //try to keep the body moving in the right direction by taking old properties.
  98852. //Should be tested!
  98853. if (oldBody) {
  98854. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  98855. impostor.physicsBody[param].copy(oldBody[param]);
  98856. });
  98857. }
  98858. this._processChildMeshes(impostor);
  98859. }
  98860. //now update the body's transformation
  98861. this._updatePhysicsBodyTransformation(impostor);
  98862. };
  98863. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  98864. var _this = this;
  98865. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  98866. var currentRotation = mainImpostor.object.rotationQuaternion;
  98867. if (meshChildren.length) {
  98868. var processMesh = function (localPosition, mesh) {
  98869. if (!currentRotation || !mesh.rotationQuaternion) {
  98870. return;
  98871. }
  98872. var childImpostor = mesh.getPhysicsImpostor();
  98873. if (childImpostor) {
  98874. var parent = childImpostor.parent;
  98875. if (parent !== mainImpostor) {
  98876. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  98877. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  98878. if (childImpostor.physicsBody) {
  98879. _this.removePhysicsBody(childImpostor);
  98880. childImpostor.physicsBody = null;
  98881. }
  98882. childImpostor.parent = mainImpostor;
  98883. childImpostor.resetUpdateFlags();
  98884. 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));
  98885. //Add the mass of the children.
  98886. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  98887. }
  98888. }
  98889. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  98890. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  98891. };
  98892. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  98893. }
  98894. };
  98895. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  98896. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  98897. this.world.removeEventListener("preStep", impostor.beforeStep);
  98898. this.world.removeEventListener("postStep", impostor.afterStep);
  98899. this.world.remove(impostor.physicsBody);
  98900. };
  98901. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  98902. var mainBody = impostorJoint.mainImpostor.physicsBody;
  98903. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  98904. if (!mainBody || !connectedBody) {
  98905. return;
  98906. }
  98907. var constraint;
  98908. var jointData = impostorJoint.joint.jointData;
  98909. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  98910. var constraintData = {
  98911. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  98912. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  98913. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  98914. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  98915. maxForce: jointData.nativeParams.maxForce,
  98916. collideConnected: !!jointData.collision
  98917. };
  98918. switch (impostorJoint.joint.type) {
  98919. case BABYLON.PhysicsJoint.HingeJoint:
  98920. case BABYLON.PhysicsJoint.Hinge2Joint:
  98921. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  98922. break;
  98923. case BABYLON.PhysicsJoint.DistanceJoint:
  98924. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  98925. break;
  98926. case BABYLON.PhysicsJoint.SpringJoint:
  98927. var springData = jointData;
  98928. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  98929. restLength: springData.length,
  98930. stiffness: springData.stiffness,
  98931. damping: springData.damping,
  98932. localAnchorA: constraintData.pivotA,
  98933. localAnchorB: constraintData.pivotB
  98934. });
  98935. break;
  98936. case BABYLON.PhysicsJoint.LockJoint:
  98937. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  98938. break;
  98939. case BABYLON.PhysicsJoint.PointToPointJoint:
  98940. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  98941. default:
  98942. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  98943. break;
  98944. }
  98945. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  98946. constraint.collideConnected = !!jointData.collision;
  98947. impostorJoint.joint.physicsJoint = constraint;
  98948. //don't add spring as constraint, as it is not one.
  98949. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  98950. this.world.addConstraint(constraint);
  98951. }
  98952. else {
  98953. impostorJoint.joint.jointData.forceApplicationCallback = impostorJoint.joint.jointData.forceApplicationCallback || function () {
  98954. constraint.applyForce();
  98955. };
  98956. impostorJoint.mainImpostor.registerAfterPhysicsStep(impostorJoint.joint.jointData.forceApplicationCallback);
  98957. }
  98958. };
  98959. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  98960. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  98961. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  98962. }
  98963. else {
  98964. impostorJoint.mainImpostor.unregisterAfterPhysicsStep(impostorJoint.joint.jointData.forceApplicationCallback);
  98965. }
  98966. };
  98967. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  98968. var index;
  98969. var mat;
  98970. for (index = 0; index < this._physicsMaterials.length; index++) {
  98971. mat = this._physicsMaterials[index];
  98972. if (mat.friction === friction && mat.restitution === restitution) {
  98973. return mat;
  98974. }
  98975. }
  98976. var currentMat = new this.BJSCANNON.Material(name);
  98977. currentMat.friction = friction;
  98978. currentMat.restitution = restitution;
  98979. this._physicsMaterials.push(currentMat);
  98980. return currentMat;
  98981. };
  98982. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  98983. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  98984. };
  98985. CannonJSPlugin.prototype._createShape = function (impostor) {
  98986. var object = impostor.object;
  98987. var returnValue;
  98988. var extendSize = impostor.getObjectExtendSize();
  98989. switch (impostor.type) {
  98990. case BABYLON.PhysicsImpostor.SphereImpostor:
  98991. var radiusX = extendSize.x;
  98992. var radiusY = extendSize.y;
  98993. var radiusZ = extendSize.z;
  98994. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  98995. break;
  98996. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  98997. case BABYLON.PhysicsImpostor.CylinderImpostor:
  98998. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  98999. break;
  99000. case BABYLON.PhysicsImpostor.BoxImpostor:
  99001. var box = extendSize.scale(0.5);
  99002. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  99003. break;
  99004. case BABYLON.PhysicsImpostor.PlaneImpostor:
  99005. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  99006. returnValue = new this.BJSCANNON.Plane();
  99007. break;
  99008. case BABYLON.PhysicsImpostor.MeshImpostor:
  99009. // should transform the vertex data to world coordinates!!
  99010. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  99011. var rawFaces = object.getIndices ? object.getIndices() : [];
  99012. if (!rawVerts) {
  99013. return;
  99014. }
  99015. // get only scale! so the object could transform correctly.
  99016. var oldPosition = object.position.clone();
  99017. var oldRotation = object.rotation && object.rotation.clone();
  99018. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  99019. object.position.copyFromFloats(0, 0, 0);
  99020. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  99021. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  99022. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  99023. var transform = object.computeWorldMatrix(true);
  99024. // convert rawVerts to object space
  99025. var temp = new Array();
  99026. var index;
  99027. for (index = 0; index < rawVerts.length; index += 3) {
  99028. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  99029. }
  99030. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  99031. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  99032. //now set back the transformation!
  99033. object.position.copyFrom(oldPosition);
  99034. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  99035. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  99036. break;
  99037. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  99038. var oldPosition2 = object.position.clone();
  99039. var oldRotation2 = object.rotation && object.rotation.clone();
  99040. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  99041. object.position.copyFromFloats(0, 0, 0);
  99042. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  99043. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  99044. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  99045. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  99046. returnValue = this._createHeightmap(object);
  99047. object.position.copyFrom(oldPosition2);
  99048. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  99049. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  99050. object.computeWorldMatrix(true);
  99051. break;
  99052. case BABYLON.PhysicsImpostor.ParticleImpostor:
  99053. returnValue = new this.BJSCANNON.Particle();
  99054. break;
  99055. }
  99056. return returnValue;
  99057. };
  99058. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  99059. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  99060. var transform = object.computeWorldMatrix(true);
  99061. // convert rawVerts to object space
  99062. var temp = new Array();
  99063. var index;
  99064. for (index = 0; index < pos.length; index += 3) {
  99065. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  99066. }
  99067. pos = temp;
  99068. var matrix = new Array();
  99069. //For now pointDepth will not be used and will be automatically calculated.
  99070. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  99071. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  99072. var boundingInfo = object.getBoundingInfo();
  99073. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  99074. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  99075. var elementSize = dim * 2 / arraySize;
  99076. for (var i = 0; i < pos.length; i = i + 3) {
  99077. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  99078. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  99079. var y = -pos[i + 2] + minY;
  99080. if (!matrix[x]) {
  99081. matrix[x] = [];
  99082. }
  99083. if (!matrix[x][z]) {
  99084. matrix[x][z] = y;
  99085. }
  99086. matrix[x][z] = Math.max(y, matrix[x][z]);
  99087. }
  99088. for (var x = 0; x <= arraySize; ++x) {
  99089. if (!matrix[x]) {
  99090. var loc = 1;
  99091. while (!matrix[(x + loc) % arraySize]) {
  99092. loc++;
  99093. }
  99094. matrix[x] = matrix[(x + loc) % arraySize].slice();
  99095. //console.log("missing x", x);
  99096. }
  99097. for (var z = 0; z <= arraySize; ++z) {
  99098. if (!matrix[x][z]) {
  99099. var loc = 1;
  99100. var newValue;
  99101. while (newValue === undefined) {
  99102. newValue = matrix[x][(z + loc++) % arraySize];
  99103. }
  99104. matrix[x][z] = newValue;
  99105. }
  99106. }
  99107. }
  99108. var shape = new this.BJSCANNON.Heightfield(matrix, {
  99109. elementSize: elementSize
  99110. });
  99111. //For future reference, needed for body transformation
  99112. shape.minY = minY;
  99113. return shape;
  99114. };
  99115. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  99116. var object = impostor.object;
  99117. //make sure it is updated...
  99118. object.computeWorldMatrix && object.computeWorldMatrix(true);
  99119. // The delta between the mesh position and the mesh bounding box center
  99120. var bInfo = object.getBoundingInfo();
  99121. if (!bInfo) {
  99122. return;
  99123. }
  99124. var center = impostor.getObjectCenter();
  99125. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  99126. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  99127. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  99128. this._tmpPosition.copyFrom(center);
  99129. var quaternion = object.rotationQuaternion;
  99130. if (!quaternion) {
  99131. return;
  99132. }
  99133. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  99134. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  99135. //-90 DEG in X, precalculated
  99136. quaternion = quaternion.multiply(this._minus90X);
  99137. //Invert! (Precalculated, 90 deg in X)
  99138. //No need to clone. this will never change.
  99139. impostor.setDeltaRotation(this._plus90X);
  99140. }
  99141. //If it is a heightfield, if should be centered.
  99142. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  99143. var mesh = object;
  99144. var boundingInfo = mesh.getBoundingInfo();
  99145. //calculate the correct body position:
  99146. var rotationQuaternion = mesh.rotationQuaternion;
  99147. mesh.rotationQuaternion = this._tmpUnityRotation;
  99148. mesh.computeWorldMatrix(true);
  99149. //get original center with no rotation
  99150. var c = center.clone();
  99151. var oldPivot = mesh.getPivotMatrix();
  99152. if (oldPivot) {
  99153. // create a copy the pivot Matrix as it is modified in place
  99154. oldPivot = oldPivot.clone();
  99155. }
  99156. else {
  99157. oldPivot = BABYLON.Matrix.Identity();
  99158. }
  99159. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  99160. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  99161. mesh.setPreTransformMatrix(p);
  99162. mesh.computeWorldMatrix(true);
  99163. //calculate the translation
  99164. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  99165. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  99166. //add it inverted to the delta
  99167. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  99168. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  99169. //rotation is back
  99170. mesh.rotationQuaternion = rotationQuaternion;
  99171. mesh.setPreTransformMatrix(oldPivot);
  99172. mesh.computeWorldMatrix(true);
  99173. }
  99174. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  99175. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  99176. //this._tmpPosition.copyFrom(object.position);
  99177. }
  99178. impostor.setDeltaPosition(this._tmpDeltaPosition);
  99179. //Now update the impostor object
  99180. impostor.physicsBody.position.copy(this._tmpPosition);
  99181. impostor.physicsBody.quaternion.copy(quaternion);
  99182. };
  99183. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  99184. impostor.object.position.copyFrom(impostor.physicsBody.position);
  99185. if (impostor.object.rotationQuaternion) {
  99186. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  99187. }
  99188. };
  99189. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  99190. impostor.physicsBody.position.copy(newPosition);
  99191. impostor.physicsBody.quaternion.copy(newRotation);
  99192. };
  99193. CannonJSPlugin.prototype.isSupported = function () {
  99194. return this.BJSCANNON !== undefined;
  99195. };
  99196. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  99197. impostor.physicsBody.velocity.copy(velocity);
  99198. };
  99199. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  99200. impostor.physicsBody.angularVelocity.copy(velocity);
  99201. };
  99202. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  99203. var v = impostor.physicsBody.velocity;
  99204. if (!v) {
  99205. return null;
  99206. }
  99207. return new BABYLON.Vector3(v.x, v.y, v.z);
  99208. };
  99209. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  99210. var v = impostor.physicsBody.angularVelocity;
  99211. if (!v) {
  99212. return null;
  99213. }
  99214. return new BABYLON.Vector3(v.x, v.y, v.z);
  99215. };
  99216. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  99217. impostor.physicsBody.mass = mass;
  99218. impostor.physicsBody.updateMassProperties();
  99219. };
  99220. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  99221. return impostor.physicsBody.mass;
  99222. };
  99223. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  99224. return impostor.physicsBody.material.friction;
  99225. };
  99226. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  99227. impostor.physicsBody.material.friction = friction;
  99228. };
  99229. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  99230. return impostor.physicsBody.material.restitution;
  99231. };
  99232. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  99233. impostor.physicsBody.material.restitution = restitution;
  99234. };
  99235. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  99236. impostor.physicsBody.sleep();
  99237. };
  99238. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  99239. impostor.physicsBody.wakeUp();
  99240. };
  99241. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  99242. joint.physicsJoint.distance = maxDistance;
  99243. };
  99244. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  99245. // if (!motorIndex) {
  99246. // joint.physicsJoint.enableMotor();
  99247. // }
  99248. // }
  99249. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  99250. // if (!motorIndex) {
  99251. // joint.physicsJoint.disableMotor();
  99252. // }
  99253. // }
  99254. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  99255. if (!motorIndex) {
  99256. joint.physicsJoint.enableMotor();
  99257. joint.physicsJoint.setMotorSpeed(speed);
  99258. if (maxForce) {
  99259. this.setLimit(joint, maxForce);
  99260. }
  99261. }
  99262. };
  99263. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  99264. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  99265. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  99266. };
  99267. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  99268. var body = impostor.physicsBody;
  99269. mesh.position.x = body.position.x;
  99270. mesh.position.y = body.position.y;
  99271. mesh.position.z = body.position.z;
  99272. if (mesh.rotationQuaternion) {
  99273. mesh.rotationQuaternion.x = body.quaternion.x;
  99274. mesh.rotationQuaternion.y = body.quaternion.y;
  99275. mesh.rotationQuaternion.z = body.quaternion.z;
  99276. mesh.rotationQuaternion.w = body.quaternion.w;
  99277. }
  99278. };
  99279. CannonJSPlugin.prototype.getRadius = function (impostor) {
  99280. var shape = impostor.physicsBody.shapes[0];
  99281. return shape.boundingSphereRadius;
  99282. };
  99283. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  99284. var shape = impostor.physicsBody.shapes[0];
  99285. result.x = shape.halfExtents.x * 2;
  99286. result.y = shape.halfExtents.y * 2;
  99287. result.z = shape.halfExtents.z * 2;
  99288. };
  99289. CannonJSPlugin.prototype.dispose = function () {
  99290. };
  99291. CannonJSPlugin.prototype._extendNamespace = function () {
  99292. //this will force cannon to execute at least one step when using interpolation
  99293. var step_tmp1 = new this.BJSCANNON.Vec3();
  99294. var Engine = this.BJSCANNON;
  99295. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  99296. maxSubSteps = maxSubSteps || 10;
  99297. timeSinceLastCalled = timeSinceLastCalled || 0;
  99298. if (timeSinceLastCalled === 0) {
  99299. this.internalStep(dt);
  99300. this.time += dt;
  99301. }
  99302. else {
  99303. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  99304. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  99305. var t0 = performance.now();
  99306. for (var i = 0; i !== internalSteps; i++) {
  99307. this.internalStep(dt);
  99308. if (performance.now() - t0 > dt * 1000) {
  99309. break;
  99310. }
  99311. }
  99312. this.time += timeSinceLastCalled;
  99313. var h = this.time % dt;
  99314. var h_div_dt = h / dt;
  99315. var interpvelo = step_tmp1;
  99316. var bodies = this.bodies;
  99317. for (var j = 0; j !== bodies.length; j++) {
  99318. var b = bodies[j];
  99319. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  99320. b.position.vsub(b.previousPosition, interpvelo);
  99321. interpvelo.scale(h_div_dt, interpvelo);
  99322. b.position.vadd(interpvelo, b.interpolatedPosition);
  99323. }
  99324. else {
  99325. b.interpolatedPosition.copy(b.position);
  99326. b.interpolatedQuaternion.copy(b.quaternion);
  99327. }
  99328. }
  99329. }
  99330. };
  99331. };
  99332. return CannonJSPlugin;
  99333. }());
  99334. BABYLON.CannonJSPlugin = CannonJSPlugin;
  99335. })(BABYLON || (BABYLON = {}));
  99336. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  99337. var BABYLON;
  99338. (function (BABYLON) {
  99339. /**
  99340. * AmmoJS Physics plugin
  99341. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  99342. * @see https://github.com/kripken/ammo.js/
  99343. */
  99344. var AmmoJSPlugin = /** @class */ (function () {
  99345. /**
  99346. * Initializes the ammoJS plugin
  99347. * @param _useDeltaForWorldStep if the time between frames should be used when calculating physics steps (Default: true)
  99348. */
  99349. function AmmoJSPlugin(_useDeltaForWorldStep) {
  99350. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  99351. var _this = this;
  99352. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  99353. /**
  99354. * Name of the plugin
  99355. */
  99356. this.name = "AmmoJSPlugin";
  99357. this._timeStep = 1 / 60;
  99358. this._fixedTimeStep = 1 / 60;
  99359. this._maxSteps = 5;
  99360. this._tmpQuaternion = new BABYLON.Quaternion();
  99361. this._tmpContactCallbackResult = false;
  99362. if (typeof Ammo === "function") {
  99363. Ammo();
  99364. }
  99365. this.bjsAMMO = Ammo;
  99366. if (!this.isSupported()) {
  99367. BABYLON.Tools.Error("AmmoJS is not available. Please make sure you included the js file.");
  99368. return;
  99369. }
  99370. // Initialize the physics world
  99371. this._collisionConfiguration = new this.bjsAMMO.btDefaultCollisionConfiguration();
  99372. this._dispatcher = new this.bjsAMMO.btCollisionDispatcher(this._collisionConfiguration);
  99373. this._overlappingPairCache = new this.bjsAMMO.btDbvtBroadphase();
  99374. this._solver = new this.bjsAMMO.btSequentialImpulseConstraintSolver();
  99375. this.world = new this.bjsAMMO.btDiscreteDynamicsWorld(this._dispatcher, this._overlappingPairCache, this._solver, this._collisionConfiguration);
  99376. this._tmpAmmoConcreteContactResultCallback = new this.bjsAMMO.ConcreteContactResultCallback();
  99377. this._tmpAmmoConcreteContactResultCallback.addSingleResult = function () { _this._tmpContactCallbackResult = true; };
  99378. // Create temp ammo variables
  99379. this._tmpAmmoTransform = new this.bjsAMMO.btTransform();
  99380. this._tmpAmmoTransform.setIdentity();
  99381. this._tmpAmmoQuaternion = new this.bjsAMMO.btQuaternion(0, 0, 0, 1);
  99382. this._tmpAmmoVectorA = new this.bjsAMMO.btVector3(0, 0, 0);
  99383. this._tmpAmmoVectorB = new this.bjsAMMO.btVector3(0, 0, 0);
  99384. this._tmpAmmoVectorC = new this.bjsAMMO.btVector3(0, 0, 0);
  99385. }
  99386. /**
  99387. * Sets the gravity of the physics world (m/(s^2))
  99388. * @param gravity Gravity to set
  99389. */
  99390. AmmoJSPlugin.prototype.setGravity = function (gravity) {
  99391. this._tmpAmmoVectorA.setValue(gravity.x, gravity.y, gravity.z);
  99392. this.world.setGravity(this._tmpAmmoVectorA);
  99393. };
  99394. /**
  99395. * Amount of time to step forward on each frame (only used if useDeltaForWorldStep is false in the constructor)
  99396. * @param timeStep timestep to use in seconds
  99397. */
  99398. AmmoJSPlugin.prototype.setTimeStep = function (timeStep) {
  99399. this._timeStep = timeStep;
  99400. };
  99401. /**
  99402. * Increment to step forward in the physics engine (If timeStep is set to 1/60 and fixedTimeStep is set to 1/120 the physics engine should run 2 steps per frame) (Default: 1/60)
  99403. * @param fixedTimeStep fixedTimeStep to use in seconds
  99404. */
  99405. AmmoJSPlugin.prototype.setFixedTimeStep = function (fixedTimeStep) {
  99406. this._fixedTimeStep = fixedTimeStep;
  99407. };
  99408. /**
  99409. * Sets the maximum number of steps by the physics engine per frame (Default: 5)
  99410. * @param maxSteps the maximum number of steps by the physics engine per frame
  99411. */
  99412. AmmoJSPlugin.prototype.setMaxSteps = function (maxSteps) {
  99413. this._maxSteps = maxSteps;
  99414. };
  99415. /**
  99416. * Gets the current timestep (only used if useDeltaForWorldStep is false in the constructor)
  99417. * @returns the current timestep in seconds
  99418. */
  99419. AmmoJSPlugin.prototype.getTimeStep = function () {
  99420. return this._timeStep;
  99421. };
  99422. // Ammo's contactTest and contactPairTest take a callback that runs synchronously, wrap them so that they are easier to consume
  99423. AmmoJSPlugin.prototype._isImpostorInContact = function (impostor) {
  99424. this._tmpContactCallbackResult = false;
  99425. this.world.contactTest(impostor.physicsBody, this._tmpAmmoConcreteContactResultCallback);
  99426. return this._tmpContactCallbackResult;
  99427. };
  99428. // Ammo's collision events have some weird quirks
  99429. // contactPairTest fires too many events as it fires events even when objects are close together but contactTest does not
  99430. // so only fire event if both contactTest and contactPairTest have a hit
  99431. AmmoJSPlugin.prototype._isImpostorPairInContact = function (impostorA, impostorB) {
  99432. this._tmpContactCallbackResult = false;
  99433. this.world.contactPairTest(impostorA.physicsBody, impostorB.physicsBody, this._tmpAmmoConcreteContactResultCallback);
  99434. return this._tmpContactCallbackResult;
  99435. };
  99436. // Ammo's behavior when maxSteps > 0 does not behave as described in docs
  99437. // @see http://www.bulletphysics.org/mediawiki-1.5.8/index.php/Stepping_The_World
  99438. //
  99439. // When maxSteps is 0 do the entire simulation in one step
  99440. // When maxSteps is > 0, run up to maxStep times, if on the last step the (remaining step - fixedTimeStep) is < fixedTimeStep, the remainder will be used for the step. (eg. if remainder is 1.001 and fixedTimeStep is 1 the last step will be 1.001, if instead it did 2 steps (1, 0.001) issues occuered when having a tiny step in ammo)
  99441. // Note: To get deterministic physics, timeStep would always need to be divisible by fixedTimeStep
  99442. AmmoJSPlugin.prototype._stepSimulation = function (timeStep, maxSteps, fixedTimeStep) {
  99443. if (timeStep === void 0) { timeStep = 1 / 60; }
  99444. if (maxSteps === void 0) { maxSteps = 10; }
  99445. if (fixedTimeStep === void 0) { fixedTimeStep = 1 / 60; }
  99446. if (maxSteps == 0) {
  99447. this.world.stepSimulation(timeStep, 0);
  99448. }
  99449. else {
  99450. while (maxSteps > 0 && timeStep > 0) {
  99451. if (timeStep - fixedTimeStep < fixedTimeStep) {
  99452. this.world.stepSimulation(timeStep, 0);
  99453. timeStep = 0;
  99454. }
  99455. else {
  99456. timeStep -= fixedTimeStep;
  99457. this.world.stepSimulation(fixedTimeStep, 0);
  99458. }
  99459. maxSteps--;
  99460. }
  99461. }
  99462. };
  99463. /**
  99464. * Moves the physics simulation forward delta seconds and updates the given physics imposters
  99465. * Prior to the step the imposters physics location is set to the position of the babylon meshes
  99466. * After the step the babylon meshes are set to the position of the physics imposters
  99467. * @param delta amount of time to step forward
  99468. * @param impostors array of imposters to update before/after the step
  99469. */
  99470. AmmoJSPlugin.prototype.executeStep = function (delta, impostors) {
  99471. for (var _i = 0, impostors_1 = impostors; _i < impostors_1.length; _i++) {
  99472. var impostor = impostors_1[_i];
  99473. // Update physics world objects to match babylon world
  99474. impostor.beforeStep();
  99475. }
  99476. this._stepSimulation(this._useDeltaForWorldStep ? delta : this._timeStep, this._maxSteps, this._fixedTimeStep);
  99477. for (var _a = 0, impostors_2 = impostors; _a < impostors_2.length; _a++) {
  99478. var mainImpostor = impostors_2[_a];
  99479. // After physics update make babylon world objects match physics world objects
  99480. mainImpostor.afterStep();
  99481. // Handle collision event
  99482. if (mainImpostor._onPhysicsCollideCallbacks.length > 0) {
  99483. if (this._isImpostorInContact(mainImpostor)) {
  99484. for (var _b = 0, _c = mainImpostor._onPhysicsCollideCallbacks; _b < _c.length; _b++) {
  99485. var collideCallback = _c[_b];
  99486. for (var _d = 0, _e = collideCallback.otherImpostors; _d < _e.length; _d++) {
  99487. var otherImpostor = _e[_d];
  99488. if (mainImpostor.physicsBody.isActive() || otherImpostor.physicsBody.isActive()) {
  99489. if (this._isImpostorPairInContact(mainImpostor, otherImpostor)) {
  99490. mainImpostor.onCollide({ body: otherImpostor.physicsBody });
  99491. otherImpostor.onCollide({ body: mainImpostor.physicsBody });
  99492. }
  99493. }
  99494. }
  99495. }
  99496. }
  99497. }
  99498. }
  99499. };
  99500. /**
  99501. * Applies an implulse on the imposter
  99502. * @param impostor imposter to apply impulse
  99503. * @param force amount of force to be applied to the imposter
  99504. * @param contactPoint the location to apply the impulse on the imposter
  99505. */
  99506. AmmoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  99507. var worldPoint = this._tmpAmmoVectorA;
  99508. var impulse = this._tmpAmmoVectorB;
  99509. worldPoint.setValue(contactPoint.x, contactPoint.y, contactPoint.z);
  99510. impulse.setValue(force.x, force.y, force.z);
  99511. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  99512. };
  99513. /**
  99514. * Applies a force on the imposter
  99515. * @param impostor imposter to apply force
  99516. * @param force amount of force to be applied to the imposter
  99517. * @param contactPoint the location to apply the force on the imposter
  99518. */
  99519. AmmoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  99520. var worldPoint = this._tmpAmmoVectorA;
  99521. var impulse = this._tmpAmmoVectorB;
  99522. worldPoint.setValue(contactPoint.x, contactPoint.y, contactPoint.z);
  99523. impulse.setValue(force.x, force.y, force.z);
  99524. impostor.physicsBody.applyForce(impulse, worldPoint);
  99525. };
  99526. /**
  99527. * Creates a physics body using the plugin
  99528. * @param impostor the imposter to create the physics body on
  99529. */
  99530. AmmoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  99531. impostor._pluginData = { toDispose: [] };
  99532. //parent-child relationship
  99533. if (impostor.parent) {
  99534. if (impostor.physicsBody) {
  99535. this.removePhysicsBody(impostor);
  99536. impostor.forceUpdate();
  99537. }
  99538. return;
  99539. }
  99540. if (impostor.isBodyInitRequired()) {
  99541. var colShape = this._createShape(impostor);
  99542. var mass = impostor.getParam("mass");
  99543. impostor._pluginData.mass = mass;
  99544. var localInertia = new Ammo.btVector3(0, 0, 0);
  99545. var startTransform = new Ammo.btTransform();
  99546. startTransform.setIdentity();
  99547. if (mass !== 0) {
  99548. colShape.calculateLocalInertia(mass, localInertia);
  99549. }
  99550. this._tmpAmmoVectorA.setValue(impostor.object.position.x, impostor.object.position.y, impostor.object.position.z);
  99551. this._tmpAmmoQuaternion.setValue(impostor.object.rotationQuaternion.x, impostor.object.rotationQuaternion.y, impostor.object.rotationQuaternion.z, impostor.object.rotationQuaternion.w);
  99552. startTransform.setOrigin(this._tmpAmmoVectorA);
  99553. startTransform.setRotation(this._tmpAmmoQuaternion);
  99554. var myMotionState = new Ammo.btDefaultMotionState(startTransform);
  99555. var rbInfo = new Ammo.btRigidBodyConstructionInfo(mass, myMotionState, colShape, localInertia);
  99556. var body = new Ammo.btRigidBody(rbInfo);
  99557. // Make objects kinematic if it's mass is 0
  99558. if (mass === 0) {
  99559. body.setCollisionFlags(body.getCollisionFlags() | AmmoJSPlugin.KINEMATIC_FLAG);
  99560. body.setActivationState(AmmoJSPlugin.DISABLE_DEACTIVATION_FLAG);
  99561. }
  99562. // Disable collision if NoImpostor, but keep collision if shape is btCompoundShape
  99563. if (impostor.type == BABYLON.PhysicsImpostor.NoImpostor && !colShape.getChildShape) {
  99564. body.setCollisionFlags(body.getCollisionFlags() | AmmoJSPlugin.DISABLE_COLLISION_FLAG);
  99565. }
  99566. body.setRestitution(impostor.getParam("restitution"));
  99567. this.world.addRigidBody(body);
  99568. impostor.physicsBody = body;
  99569. impostor._pluginData.toDispose.concat([body, rbInfo, myMotionState, startTransform, localInertia, colShape]);
  99570. }
  99571. };
  99572. /**
  99573. * Removes the physics body from the imposter and disposes of the body's memory
  99574. * @param impostor imposter to remove the physics body from
  99575. */
  99576. AmmoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  99577. var _this = this;
  99578. if (this.world) {
  99579. this.world.removeRigidBody(impostor.physicsBody);
  99580. impostor._pluginData.toDispose.forEach(function (d) {
  99581. _this.bjsAMMO.destroy(d);
  99582. });
  99583. }
  99584. };
  99585. /**
  99586. * Generates a joint
  99587. * @param impostorJoint the imposter joint to create the joint with
  99588. */
  99589. AmmoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  99590. var mainBody = impostorJoint.mainImpostor.physicsBody;
  99591. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  99592. if (!mainBody || !connectedBody) {
  99593. return;
  99594. }
  99595. var jointData = impostorJoint.joint.jointData;
  99596. if (!jointData.mainPivot) {
  99597. jointData.mainPivot = new BABYLON.Vector3(0, 0, 0);
  99598. }
  99599. if (!jointData.connectedPivot) {
  99600. jointData.connectedPivot = new BABYLON.Vector3(0, 0, 0);
  99601. }
  99602. var joint;
  99603. switch (impostorJoint.joint.type) {
  99604. case BABYLON.PhysicsJoint.DistanceJoint:
  99605. var distance = jointData.maxDistance;
  99606. if (distance) {
  99607. jointData.mainPivot = new BABYLON.Vector3(0, -distance / 2, 0);
  99608. jointData.connectedPivot = new BABYLON.Vector3(0, distance / 2, 0);
  99609. }
  99610. joint = new Ammo.btPoint2PointConstraint(mainBody, connectedBody, new Ammo.btVector3(jointData.mainPivot.x, jointData.mainPivot.y, jointData.mainPivot.z), new Ammo.btVector3(jointData.connectedPivot.x, jointData.connectedPivot.y, jointData.connectedPivot.z));
  99611. break;
  99612. case BABYLON.PhysicsJoint.HingeJoint:
  99613. if (!jointData.mainAxis) {
  99614. jointData.mainAxis = new BABYLON.Vector3(0, 0, 0);
  99615. }
  99616. if (!jointData.connectedAxis) {
  99617. jointData.connectedAxis = new BABYLON.Vector3(0, 0, 0);
  99618. }
  99619. var mainAxis = new Ammo.btVector3(jointData.mainAxis.x, jointData.mainAxis.y, jointData.mainAxis.z);
  99620. var connectedAxis = new Ammo.btVector3(jointData.connectedAxis.x, jointData.connectedAxis.y, jointData.connectedAxis.z);
  99621. joint = new Ammo.btHingeConstraint(mainBody, connectedBody, new Ammo.btVector3(jointData.mainPivot.x, jointData.mainPivot.y, jointData.mainPivot.z), new Ammo.btVector3(jointData.connectedPivot.x, jointData.connectedPivot.y, jointData.connectedPivot.z), mainAxis, connectedAxis);
  99622. break;
  99623. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  99624. joint = new Ammo.btPoint2PointConstraint(mainBody, connectedBody, new Ammo.btVector3(jointData.mainPivot.x, jointData.mainPivot.y, jointData.mainPivot.z), new Ammo.btVector3(jointData.connectedPivot.x, jointData.connectedPivot.y, jointData.connectedPivot.z));
  99625. break;
  99626. default:
  99627. BABYLON.Tools.Warn("JointType not currently supported by the Ammo plugin, falling back to PhysicsJoint.BallAndSocketJoint");
  99628. joint = new Ammo.btPoint2PointConstraint(mainBody, connectedBody, new Ammo.btVector3(jointData.mainPivot.x, jointData.mainPivot.y, jointData.mainPivot.z), new Ammo.btVector3(jointData.connectedPivot.x, jointData.connectedPivot.y, jointData.connectedPivot.z));
  99629. break;
  99630. }
  99631. this.world.addConstraint(joint, true);
  99632. impostorJoint.joint.physicsJoint = joint;
  99633. };
  99634. /**
  99635. * Removes a joint
  99636. * @param impostorJoint the imposter joint to remove the joint from
  99637. */
  99638. AmmoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  99639. if (this.world) {
  99640. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  99641. }
  99642. };
  99643. // adds all verticies (including child verticies) to the triangle mesh
  99644. AmmoJSPlugin.prototype._addMeshVerts = function (btTriangleMesh, topLevelObject, object) {
  99645. var _this = this;
  99646. var triangleCount = 0;
  99647. if (object && object.getIndices && object.getWorldMatrix && object.getChildMeshes) {
  99648. var indices = object.getIndices();
  99649. if (!indices) {
  99650. indices = [];
  99651. }
  99652. var vertexPositions = object.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  99653. if (!vertexPositions) {
  99654. vertexPositions = [];
  99655. }
  99656. object.computeWorldMatrix(false);
  99657. var faceCount = indices.length / 3;
  99658. for (var i = 0; i < faceCount; i++) {
  99659. var triPoints = [];
  99660. for (var point = 0; point < 3; point++) {
  99661. var v = new BABYLON.Vector3(vertexPositions[(indices[(i * 3) + point] * 3) + 0], vertexPositions[(indices[(i * 3) + point] * 3) + 1], vertexPositions[(indices[(i * 3) + point] * 3) + 2]);
  99662. v = BABYLON.Vector3.TransformCoordinates(v, object.getWorldMatrix());
  99663. v.subtractInPlace(topLevelObject.position);
  99664. var vec;
  99665. if (point == 0) {
  99666. vec = this._tmpAmmoVectorA;
  99667. }
  99668. else if (point == 1) {
  99669. vec = this._tmpAmmoVectorB;
  99670. }
  99671. else {
  99672. vec = this._tmpAmmoVectorC;
  99673. }
  99674. vec.setValue(v.x, v.y, v.z);
  99675. triPoints.push(vec);
  99676. }
  99677. btTriangleMesh.addTriangle(triPoints[0], triPoints[1], triPoints[2]);
  99678. triangleCount++;
  99679. }
  99680. object.getChildMeshes().forEach(function (m) {
  99681. triangleCount += _this._addMeshVerts(btTriangleMesh, topLevelObject, m);
  99682. });
  99683. }
  99684. return triangleCount;
  99685. };
  99686. AmmoJSPlugin.prototype._createShape = function (impostor, ignoreChildren) {
  99687. var _this = this;
  99688. if (ignoreChildren === void 0) { ignoreChildren = false; }
  99689. var object = impostor.object;
  99690. var returnValue;
  99691. var extendSize = impostor.getObjectExtendSize();
  99692. if (!ignoreChildren) {
  99693. var meshChildren = impostor.object.getChildMeshes ? impostor.object.getChildMeshes(true) : [];
  99694. returnValue = new Ammo.btCompoundShape();
  99695. // Add shape of all children to the compound shape
  99696. var childrenAdded = 0;
  99697. meshChildren.forEach(function (childMesh) {
  99698. var childImpostor = childMesh.getPhysicsImpostor();
  99699. if (childImpostor) {
  99700. var shape = _this._createShape(childImpostor);
  99701. // Position needs to be scaled based on parent's scaling
  99702. var parentMat = childMesh.parent.getWorldMatrix().clone();
  99703. var s = new BABYLON.Vector3();
  99704. parentMat.decompose(s);
  99705. _this._tmpAmmoTransform.getOrigin().setValue(childMesh.position.x * s.x, childMesh.position.y * s.y, childMesh.position.z * s.z);
  99706. _this._tmpAmmoQuaternion.setValue(childMesh.rotationQuaternion.x, childMesh.rotationQuaternion.y, childMesh.rotationQuaternion.z, childMesh.rotationQuaternion.w);
  99707. _this._tmpAmmoTransform.setRotation(_this._tmpAmmoQuaternion);
  99708. returnValue.addChildShape(_this._tmpAmmoTransform, shape);
  99709. childImpostor.dispose();
  99710. childrenAdded++;
  99711. }
  99712. });
  99713. if (childrenAdded > 0) {
  99714. // Add parents shape as a child if present
  99715. if (impostor.type != BABYLON.PhysicsImpostor.NoImpostor) {
  99716. var shape = this._createShape(impostor, true);
  99717. if (shape) {
  99718. this._tmpAmmoTransform.getOrigin().setValue(0, 0, 0);
  99719. this._tmpAmmoQuaternion.setValue(0, 0, 0, 1);
  99720. this._tmpAmmoTransform.setRotation(this._tmpAmmoQuaternion);
  99721. returnValue.addChildShape(this._tmpAmmoTransform, shape);
  99722. }
  99723. }
  99724. return returnValue;
  99725. }
  99726. else {
  99727. // If no children with impostors create the actual shape below instead
  99728. Ammo.destroy(returnValue);
  99729. returnValue = null;
  99730. }
  99731. }
  99732. switch (impostor.type) {
  99733. case BABYLON.PhysicsImpostor.SphereImpostor:
  99734. returnValue = new Ammo.btSphereShape(extendSize.x / 2);
  99735. break;
  99736. case BABYLON.PhysicsImpostor.CylinderImpostor:
  99737. this._tmpAmmoVectorA.setValue(extendSize.x / 2, extendSize.y / 2, extendSize.z / 2);
  99738. returnValue = new Ammo.btCylinderShape(this._tmpAmmoVectorA);
  99739. break;
  99740. case BABYLON.PhysicsImpostor.PlaneImpostor:
  99741. case BABYLON.PhysicsImpostor.BoxImpostor:
  99742. this._tmpAmmoVectorA.setValue(extendSize.x / 2, extendSize.y / 2, extendSize.z / 2);
  99743. returnValue = new Ammo.btBoxShape(this._tmpAmmoVectorA);
  99744. break;
  99745. case BABYLON.PhysicsImpostor.MeshImpostor:
  99746. var tetraMesh = new Ammo.btTriangleMesh();
  99747. impostor._pluginData.toDispose.concat([tetraMesh]);
  99748. var triangeCount = this._addMeshVerts(tetraMesh, object, object);
  99749. if (triangeCount == 0) {
  99750. returnValue = new Ammo.btCompoundShape();
  99751. }
  99752. else {
  99753. returnValue = new Ammo.btBvhTriangleMeshShape(tetraMesh);
  99754. }
  99755. break;
  99756. case BABYLON.PhysicsImpostor.NoImpostor:
  99757. // Fill with sphere but collision is disabled on the rigid body in generatePhysicsBody, using an empty shape caused unexpected movement with joints
  99758. returnValue = new Ammo.btSphereShape(extendSize.x / 2);
  99759. break;
  99760. default:
  99761. BABYLON.Tools.Warn("The impostor type is not currently supported by the ammo plugin.");
  99762. break;
  99763. }
  99764. return returnValue;
  99765. };
  99766. /**
  99767. * Sets the physics body position/rotation from the babylon mesh's position/rotation
  99768. * @param impostor imposter containing the physics body and babylon object
  99769. */
  99770. AmmoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  99771. impostor.physicsBody.getMotionState().getWorldTransform(this._tmpAmmoTransform);
  99772. impostor.object.position.set(this._tmpAmmoTransform.getOrigin().x(), this._tmpAmmoTransform.getOrigin().y(), this._tmpAmmoTransform.getOrigin().z());
  99773. if (!impostor.object.rotationQuaternion) {
  99774. if (impostor.object.rotation) {
  99775. this._tmpQuaternion.set(this._tmpAmmoTransform.getRotation().x(), this._tmpAmmoTransform.getRotation().y(), this._tmpAmmoTransform.getRotation().z(), this._tmpAmmoTransform.getRotation().w());
  99776. this._tmpQuaternion.toEulerAnglesToRef(impostor.object.rotation);
  99777. }
  99778. }
  99779. else {
  99780. impostor.object.rotationQuaternion.set(this._tmpAmmoTransform.getRotation().x(), this._tmpAmmoTransform.getRotation().y(), this._tmpAmmoTransform.getRotation().z(), this._tmpAmmoTransform.getRotation().w());
  99781. }
  99782. };
  99783. /**
  99784. * Sets the babylon object's position/rotation from the physics body's position/rotation
  99785. * @param impostor imposter containing the physics body and babylon object
  99786. * @param newPosition new position
  99787. * @param newRotation new rotation
  99788. */
  99789. AmmoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  99790. var trans = impostor.physicsBody.getWorldTransform();
  99791. // If rotation/position has changed update and activate riged body
  99792. if (trans.getOrigin().x() != newPosition.x ||
  99793. trans.getOrigin().y() != newPosition.y ||
  99794. trans.getOrigin().z() != newPosition.z ||
  99795. trans.getRotation().x() != newRotation.x ||
  99796. trans.getRotation().y() != newRotation.y ||
  99797. trans.getRotation().z() != newRotation.z ||
  99798. trans.getRotation().w() != newRotation.w) {
  99799. this._tmpAmmoVectorA.setValue(newPosition.x, newPosition.y, newPosition.z);
  99800. trans.setOrigin(this._tmpAmmoVectorA);
  99801. this._tmpAmmoQuaternion.setValue(newRotation.x, newRotation.y, newRotation.z, newRotation.w);
  99802. trans.setRotation(this._tmpAmmoQuaternion);
  99803. impostor.physicsBody.setWorldTransform(trans);
  99804. if (impostor.mass == 0) {
  99805. // Kinematic objects must be updated using motion state
  99806. var motionState = impostor.physicsBody.getMotionState();
  99807. if (motionState) {
  99808. motionState.setWorldTransform(trans);
  99809. }
  99810. }
  99811. else {
  99812. impostor.physicsBody.activate();
  99813. }
  99814. }
  99815. };
  99816. /**
  99817. * If this plugin is supported
  99818. * @returns true if its supported
  99819. */
  99820. AmmoJSPlugin.prototype.isSupported = function () {
  99821. return this.bjsAMMO !== undefined;
  99822. };
  99823. /**
  99824. * Sets the linear velocity of the physics body
  99825. * @param impostor imposter to set the velocity on
  99826. * @param velocity velocity to set
  99827. */
  99828. AmmoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  99829. this._tmpAmmoVectorA.setValue(velocity.x, velocity.y, velocity.z);
  99830. impostor.physicsBody.setLinearVelocity(this._tmpAmmoVectorA);
  99831. };
  99832. /**
  99833. * Sets the angular velocity of the physics body
  99834. * @param impostor imposter to set the velocity on
  99835. * @param velocity velocity to set
  99836. */
  99837. AmmoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  99838. this._tmpAmmoVectorA.setValue(velocity.x, velocity.y, velocity.z);
  99839. impostor.physicsBody.setAngularVelocity(this._tmpAmmoVectorA);
  99840. };
  99841. /**
  99842. * gets the linear velocity
  99843. * @param impostor imposter to get linear velocity from
  99844. * @returns linear velocity
  99845. */
  99846. AmmoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  99847. var v = impostor.physicsBody.getLinearVelocity();
  99848. if (!v) {
  99849. return null;
  99850. }
  99851. return new BABYLON.Vector3(v.x(), v.y(), v.z());
  99852. };
  99853. /**
  99854. * gets the angular velocity
  99855. * @param impostor imposter to get angular velocity from
  99856. * @returns angular velocity
  99857. */
  99858. AmmoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  99859. var v = impostor.physicsBody.getAngularVelocity();
  99860. if (!v) {
  99861. return null;
  99862. }
  99863. return new BABYLON.Vector3(v.x(), v.y(), v.z());
  99864. };
  99865. /**
  99866. * Sets the mass of physics body
  99867. * @param impostor imposter to set the mass on
  99868. * @param mass mass to set
  99869. */
  99870. AmmoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  99871. impostor.physicsBody.setMassProps(mass);
  99872. impostor._pluginData.mass = mass;
  99873. };
  99874. /**
  99875. * Gets the mass of the physics body
  99876. * @param impostor imposter to get the mass from
  99877. * @returns mass
  99878. */
  99879. AmmoJSPlugin.prototype.getBodyMass = function (impostor) {
  99880. return impostor._pluginData.mass;
  99881. };
  99882. /**
  99883. * Gets friction of the impostor
  99884. * @param impostor impostor to get friction from
  99885. * @returns friction value
  99886. */
  99887. AmmoJSPlugin.prototype.getBodyFriction = function (impostor) {
  99888. return impostor.physicsBody.getFriction();
  99889. };
  99890. /**
  99891. * Sets friction of the impostor
  99892. * @param impostor impostor to set friction on
  99893. * @param friction friction value
  99894. */
  99895. AmmoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  99896. impostor.physicsBody.setFriction(friction);
  99897. };
  99898. /**
  99899. * Gets restitution of the impostor
  99900. * @param impostor impostor to get restitution from
  99901. * @returns restitution value
  99902. */
  99903. AmmoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  99904. return impostor.physicsBody.getRestitution();
  99905. };
  99906. /**
  99907. * Sets resitution of the impostor
  99908. * @param impostor impostor to set resitution on
  99909. * @param restitution resitution value
  99910. */
  99911. AmmoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  99912. impostor.physicsBody.setRestitution(restitution);
  99913. };
  99914. /**
  99915. * Sleeps the physics body and stops it from being active
  99916. * @param impostor impostor to sleep
  99917. */
  99918. AmmoJSPlugin.prototype.sleepBody = function (impostor) {
  99919. BABYLON.Tools.Warn("sleepBody is not currently supported by the Ammo physics plugin");
  99920. };
  99921. /**
  99922. * Activates the physics body
  99923. * @param impostor impostor to activate
  99924. */
  99925. AmmoJSPlugin.prototype.wakeUpBody = function (impostor) {
  99926. impostor.physicsBody.activate();
  99927. };
  99928. /**
  99929. * Updates the distance parameters of the joint
  99930. * @param joint joint to update
  99931. * @param maxDistance maximum distance of the joint
  99932. * @param minDistance minimum distance of the joint
  99933. */
  99934. AmmoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  99935. BABYLON.Tools.Warn("updateDistanceJoint is not currently supported by the Ammo physics plugin");
  99936. };
  99937. /**
  99938. * Sets a motor on the joint
  99939. * @param joint joint to set motor on
  99940. * @param speed speed of the motor
  99941. * @param maxForce maximum force of the motor
  99942. * @param motorIndex index of the motor
  99943. */
  99944. AmmoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  99945. joint.physicsJoint.enableAngularMotor(true, speed, maxForce);
  99946. };
  99947. /**
  99948. * Sets the motors limit
  99949. * @param joint joint to set limit on
  99950. * @param upperLimit upper limit
  99951. * @param lowerLimit lower limit
  99952. */
  99953. AmmoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  99954. BABYLON.Tools.Warn("setLimit is not currently supported by the Ammo physics plugin");
  99955. };
  99956. /**
  99957. * Syncs the position and rotation of a mesh with the impostor
  99958. * @param mesh mesh to sync
  99959. * @param impostor impostor to update the mesh with
  99960. */
  99961. AmmoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  99962. var body = impostor.physicsBody;
  99963. body.getMotionState().getWorldTransform(this._tmpAmmoTransform);
  99964. mesh.position.x = this._tmpAmmoTransform.getOrigin().x();
  99965. mesh.position.y = this._tmpAmmoTransform.getOrigin().y();
  99966. mesh.position.z = this._tmpAmmoTransform.getOrigin().z();
  99967. if (mesh.rotationQuaternion) {
  99968. mesh.rotationQuaternion.x = this._tmpAmmoTransform.getRotation().x();
  99969. mesh.rotationQuaternion.y = this._tmpAmmoTransform.getRotation().y();
  99970. mesh.rotationQuaternion.z = this._tmpAmmoTransform.getRotation().z();
  99971. mesh.rotationQuaternion.w = this._tmpAmmoTransform.getRotation().w();
  99972. }
  99973. };
  99974. /**
  99975. * Gets the radius of the impostor
  99976. * @param impostor impostor to get radius from
  99977. * @returns the radius
  99978. */
  99979. AmmoJSPlugin.prototype.getRadius = function (impostor) {
  99980. var exntend = impostor.getObjectExtendSize();
  99981. return exntend.x / 2;
  99982. };
  99983. /**
  99984. * Gets the box size of the impostor
  99985. * @param impostor impostor to get box size from
  99986. * @param result the resulting box size
  99987. */
  99988. AmmoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  99989. var exntend = impostor.getObjectExtendSize();
  99990. result.x = exntend.x;
  99991. result.y = exntend.y;
  99992. result.z = exntend.z;
  99993. };
  99994. /**
  99995. * Disposes of the impostor
  99996. */
  99997. AmmoJSPlugin.prototype.dispose = function () {
  99998. // Dispose of world
  99999. Ammo.destroy(this.world);
  100000. Ammo.destroy(this._solver);
  100001. Ammo.destroy(this._overlappingPairCache);
  100002. Ammo.destroy(this._dispatcher);
  100003. Ammo.destroy(this._collisionConfiguration);
  100004. // Dispose of tmp variables
  100005. Ammo.destroy(this._tmpAmmoVectorA);
  100006. Ammo.destroy(this._tmpAmmoVectorB);
  100007. Ammo.destroy(this._tmpAmmoVectorC);
  100008. Ammo.destroy(this._tmpAmmoTransform);
  100009. Ammo.destroy(this._tmpAmmoQuaternion);
  100010. Ammo.destroy(this._tmpAmmoConcreteContactResultCallback);
  100011. this.world = null;
  100012. };
  100013. AmmoJSPlugin.DISABLE_COLLISION_FLAG = 4;
  100014. AmmoJSPlugin.KINEMATIC_FLAG = 2;
  100015. AmmoJSPlugin.DISABLE_DEACTIVATION_FLAG = 4;
  100016. return AmmoJSPlugin;
  100017. }());
  100018. BABYLON.AmmoJSPlugin = AmmoJSPlugin;
  100019. })(BABYLON || (BABYLON = {}));
  100020. //# sourceMappingURL=babylon.ammoJSPlugin.js.map
  100021. var BABYLON;
  100022. (function (BABYLON) {
  100023. /** @hidden */
  100024. var OimoJSPlugin = /** @class */ (function () {
  100025. function OimoJSPlugin(iterations) {
  100026. this.name = "OimoJSPlugin";
  100027. this._tmpImpostorsArray = [];
  100028. this._tmpPositionVector = BABYLON.Vector3.Zero();
  100029. this.BJSOIMO = OIMO;
  100030. this.world = new this.BJSOIMO.World({
  100031. iterations: iterations
  100032. });
  100033. this.world.clear();
  100034. }
  100035. OimoJSPlugin.prototype.setGravity = function (gravity) {
  100036. this.world.gravity.copy(gravity);
  100037. };
  100038. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  100039. this.world.timeStep = timeStep;
  100040. };
  100041. OimoJSPlugin.prototype.getTimeStep = function () {
  100042. return this.world.timeStep;
  100043. };
  100044. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  100045. var _this = this;
  100046. impostors.forEach(function (impostor) {
  100047. impostor.beforeStep();
  100048. });
  100049. this.world.step();
  100050. impostors.forEach(function (impostor) {
  100051. impostor.afterStep();
  100052. //update the ordered impostors array
  100053. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  100054. });
  100055. //check for collisions
  100056. var contact = this.world.contacts;
  100057. while (contact !== null) {
  100058. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  100059. contact = contact.next;
  100060. continue;
  100061. }
  100062. //is this body colliding with any other? get the impostor
  100063. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  100064. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  100065. if (!mainImpostor || !collidingImpostor) {
  100066. contact = contact.next;
  100067. continue;
  100068. }
  100069. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  100070. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  100071. contact = contact.next;
  100072. }
  100073. };
  100074. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  100075. var mass = impostor.physicsBody.mass;
  100076. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  100077. };
  100078. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  100079. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  100080. this.applyImpulse(impostor, force, contactPoint);
  100081. };
  100082. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  100083. var _this = this;
  100084. //parent-child relationship. Does this impostor has a parent impostor?
  100085. if (impostor.parent) {
  100086. if (impostor.physicsBody) {
  100087. this.removePhysicsBody(impostor);
  100088. //TODO is that needed?
  100089. impostor.forceUpdate();
  100090. }
  100091. return;
  100092. }
  100093. if (impostor.isBodyInitRequired()) {
  100094. var bodyConfig = {
  100095. name: impostor.uniqueId,
  100096. //Oimo must have mass, also for static objects.
  100097. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  100098. size: [],
  100099. type: [],
  100100. pos: [],
  100101. posShape: [],
  100102. rot: [],
  100103. rotShape: [],
  100104. move: impostor.getParam("mass") !== 0,
  100105. density: impostor.getParam("mass"),
  100106. friction: impostor.getParam("friction"),
  100107. restitution: impostor.getParam("restitution"),
  100108. //Supporting older versions of Oimo
  100109. world: this.world
  100110. };
  100111. var impostors = [impostor];
  100112. var addToArray = function (parent) {
  100113. if (!parent.getChildMeshes) {
  100114. return;
  100115. }
  100116. parent.getChildMeshes().forEach(function (m) {
  100117. if (m.physicsImpostor) {
  100118. impostors.push(m.physicsImpostor);
  100119. //m.physicsImpostor._init();
  100120. }
  100121. });
  100122. };
  100123. addToArray(impostor.object);
  100124. var checkWithEpsilon_1 = function (value) {
  100125. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  100126. };
  100127. var globalQuaternion_1 = new BABYLON.Quaternion();
  100128. impostors.forEach(function (i) {
  100129. if (!i.object.rotationQuaternion) {
  100130. return;
  100131. }
  100132. //get the correct bounding box
  100133. var oldQuaternion = i.object.rotationQuaternion;
  100134. globalQuaternion_1 = oldQuaternion.clone();
  100135. var rot = oldQuaternion.toEulerAngles();
  100136. var extendSize = i.getObjectExtendSize();
  100137. var radToDeg = 57.295779513082320876;
  100138. if (i === impostor) {
  100139. var center = impostor.getObjectCenter();
  100140. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  100141. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  100142. //Can also use Array.prototype.push.apply
  100143. bodyConfig.pos.push(center.x);
  100144. bodyConfig.pos.push(center.y);
  100145. bodyConfig.pos.push(center.z);
  100146. bodyConfig.posShape.push(0, 0, 0);
  100147. bodyConfig.rotShape.push(0, 0, 0);
  100148. }
  100149. else {
  100150. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  100151. bodyConfig.posShape.push(localPosition.x);
  100152. bodyConfig.posShape.push(localPosition.y);
  100153. bodyConfig.posShape.push(localPosition.z);
  100154. bodyConfig.pos.push(0, 0, 0);
  100155. bodyConfig.rotShape.push(rot.x * radToDeg);
  100156. bodyConfig.rotShape.push(rot.y * radToDeg);
  100157. bodyConfig.rotShape.push(rot.z * radToDeg);
  100158. }
  100159. // register mesh
  100160. switch (i.type) {
  100161. case BABYLON.PhysicsImpostor.ParticleImpostor:
  100162. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  100163. case BABYLON.PhysicsImpostor.SphereImpostor:
  100164. var radiusX = extendSize.x;
  100165. var radiusY = extendSize.y;
  100166. var radiusZ = extendSize.z;
  100167. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  100168. bodyConfig.type.push('sphere');
  100169. //due to the way oimo works with compounds, add 3 times
  100170. bodyConfig.size.push(size);
  100171. bodyConfig.size.push(size);
  100172. bodyConfig.size.push(size);
  100173. break;
  100174. case BABYLON.PhysicsImpostor.CylinderImpostor:
  100175. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  100176. var sizeY = checkWithEpsilon_1(extendSize.y);
  100177. bodyConfig.type.push('cylinder');
  100178. bodyConfig.size.push(sizeX);
  100179. bodyConfig.size.push(sizeY);
  100180. //due to the way oimo works with compounds, add one more value.
  100181. bodyConfig.size.push(sizeY);
  100182. break;
  100183. case BABYLON.PhysicsImpostor.PlaneImpostor:
  100184. case BABYLON.PhysicsImpostor.BoxImpostor:
  100185. default:
  100186. var sizeX = checkWithEpsilon_1(extendSize.x);
  100187. var sizeY = checkWithEpsilon_1(extendSize.y);
  100188. var sizeZ = checkWithEpsilon_1(extendSize.z);
  100189. bodyConfig.type.push('box');
  100190. //if (i === impostor) {
  100191. bodyConfig.size.push(sizeX);
  100192. bodyConfig.size.push(sizeY);
  100193. bodyConfig.size.push(sizeZ);
  100194. //} else {
  100195. // bodyConfig.size.push(0,0,0);
  100196. //}
  100197. break;
  100198. }
  100199. //actually not needed, but hey...
  100200. i.object.rotationQuaternion = oldQuaternion;
  100201. });
  100202. impostor.physicsBody = this.world.add(bodyConfig);
  100203. // set the quaternion, ignoring the previously defined (euler) rotation
  100204. impostor.physicsBody.resetQuaternion(globalQuaternion_1);
  100205. // update with delta 0, so the body will reveive the new rotation.
  100206. impostor.physicsBody.updatePosition(0);
  100207. }
  100208. else {
  100209. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  100210. }
  100211. impostor.setDeltaPosition(this._tmpPositionVector);
  100212. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  100213. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  100214. };
  100215. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  100216. //impostor.physicsBody.dispose();
  100217. //Same as : (older oimo versions)
  100218. this.world.removeRigidBody(impostor.physicsBody);
  100219. };
  100220. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  100221. var mainBody = impostorJoint.mainImpostor.physicsBody;
  100222. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  100223. if (!mainBody || !connectedBody) {
  100224. return;
  100225. }
  100226. var jointData = impostorJoint.joint.jointData;
  100227. var options = jointData.nativeParams || {};
  100228. var type;
  100229. var nativeJointData = {
  100230. body1: mainBody,
  100231. body2: connectedBody,
  100232. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  100233. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  100234. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  100235. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  100236. min: options.min,
  100237. max: options.max,
  100238. collision: options.collision || jointData.collision,
  100239. spring: options.spring,
  100240. //supporting older version of Oimo
  100241. world: this.world
  100242. };
  100243. switch (impostorJoint.joint.type) {
  100244. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  100245. type = "jointBall";
  100246. break;
  100247. case BABYLON.PhysicsJoint.SpringJoint:
  100248. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  100249. var springData = jointData;
  100250. nativeJointData.min = springData.length || nativeJointData.min;
  100251. //Max should also be set, just make sure it is at least min
  100252. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  100253. case BABYLON.PhysicsJoint.DistanceJoint:
  100254. type = "jointDistance";
  100255. nativeJointData.max = jointData.maxDistance;
  100256. break;
  100257. case BABYLON.PhysicsJoint.PrismaticJoint:
  100258. type = "jointPrisme";
  100259. break;
  100260. case BABYLON.PhysicsJoint.SliderJoint:
  100261. type = "jointSlide";
  100262. break;
  100263. case BABYLON.PhysicsJoint.WheelJoint:
  100264. type = "jointWheel";
  100265. break;
  100266. case BABYLON.PhysicsJoint.HingeJoint:
  100267. default:
  100268. type = "jointHinge";
  100269. break;
  100270. }
  100271. nativeJointData.type = type;
  100272. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  100273. };
  100274. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  100275. //Bug in Oimo prevents us from disposing a joint in the playground
  100276. //joint.joint.physicsJoint.dispose();
  100277. //So we will bruteforce it!
  100278. try {
  100279. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  100280. }
  100281. catch (e) {
  100282. BABYLON.Tools.Warn(e);
  100283. }
  100284. };
  100285. OimoJSPlugin.prototype.isSupported = function () {
  100286. return this.BJSOIMO !== undefined;
  100287. };
  100288. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  100289. if (!impostor.physicsBody.sleeping) {
  100290. //TODO check that
  100291. /*if (impostor.physicsBody.shapes.next) {
  100292. var parentShape = this._getLastShape(impostor.physicsBody);
  100293. impostor.object.position.copyFrom(parentShape.position);
  100294. console.log(parentShape.position);
  100295. } else {*/
  100296. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  100297. //}
  100298. if (impostor.object.rotationQuaternion) {
  100299. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  100300. }
  100301. }
  100302. };
  100303. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  100304. var body = impostor.physicsBody;
  100305. body.position.copy(newPosition);
  100306. body.orientation.copy(newRotation);
  100307. body.syncShapes();
  100308. body.awake();
  100309. };
  100310. /*private _getLastShape(body: any): any {
  100311. var lastShape = body.shapes;
  100312. while (lastShape.next) {
  100313. lastShape = lastShape.next;
  100314. }
  100315. return lastShape;
  100316. }*/
  100317. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  100318. impostor.physicsBody.linearVelocity.copy(velocity);
  100319. };
  100320. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  100321. impostor.physicsBody.angularVelocity.copy(velocity);
  100322. };
  100323. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  100324. var v = impostor.physicsBody.linearVelocity;
  100325. if (!v) {
  100326. return null;
  100327. }
  100328. return new BABYLON.Vector3(v.x, v.y, v.z);
  100329. };
  100330. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  100331. var v = impostor.physicsBody.angularVelocity;
  100332. if (!v) {
  100333. return null;
  100334. }
  100335. return new BABYLON.Vector3(v.x, v.y, v.z);
  100336. };
  100337. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  100338. var staticBody = mass === 0;
  100339. //this will actually set the body's density and not its mass.
  100340. //But this is how oimo treats the mass variable.
  100341. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  100342. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  100343. };
  100344. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  100345. return impostor.physicsBody.shapes.density;
  100346. };
  100347. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  100348. return impostor.physicsBody.shapes.friction;
  100349. };
  100350. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  100351. impostor.physicsBody.shapes.friction = friction;
  100352. };
  100353. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  100354. return impostor.physicsBody.shapes.restitution;
  100355. };
  100356. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  100357. impostor.physicsBody.shapes.restitution = restitution;
  100358. };
  100359. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  100360. impostor.physicsBody.sleep();
  100361. };
  100362. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  100363. impostor.physicsBody.awake();
  100364. };
  100365. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  100366. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  100367. if (minDistance !== void 0) {
  100368. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  100369. }
  100370. };
  100371. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  100372. //TODO separate rotational and transational motors.
  100373. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  100374. if (motor) {
  100375. motor.setMotor(speed, maxForce);
  100376. }
  100377. };
  100378. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  100379. //TODO separate rotational and transational motors.
  100380. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  100381. if (motor) {
  100382. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  100383. }
  100384. };
  100385. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  100386. var body = impostor.physicsBody;
  100387. mesh.position.x = body.position.x;
  100388. mesh.position.y = body.position.y;
  100389. mesh.position.z = body.position.z;
  100390. if (mesh.rotationQuaternion) {
  100391. mesh.rotationQuaternion.x = body.orientation.x;
  100392. mesh.rotationQuaternion.y = body.orientation.y;
  100393. mesh.rotationQuaternion.z = body.orientation.z;
  100394. mesh.rotationQuaternion.w = body.orientation.s;
  100395. }
  100396. };
  100397. OimoJSPlugin.prototype.getRadius = function (impostor) {
  100398. return impostor.physicsBody.shapes.radius;
  100399. };
  100400. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  100401. var shape = impostor.physicsBody.shapes;
  100402. result.x = shape.halfWidth * 2;
  100403. result.y = shape.halfHeight * 2;
  100404. result.z = shape.halfDepth * 2;
  100405. };
  100406. OimoJSPlugin.prototype.dispose = function () {
  100407. this.world.clear();
  100408. };
  100409. return OimoJSPlugin;
  100410. }());
  100411. BABYLON.OimoJSPlugin = OimoJSPlugin;
  100412. })(BABYLON || (BABYLON = {}));
  100413. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  100414. var BABYLON;
  100415. (function (BABYLON) {
  100416. /**
  100417. * Gets the current physics engine
  100418. * @returns a IPhysicsEngine or null if none attached
  100419. */
  100420. BABYLON.Scene.prototype.getPhysicsEngine = function () {
  100421. return this._physicsEngine;
  100422. };
  100423. /**
  100424. * Enables physics to the current scene
  100425. * @param gravity defines the scene's gravity for the physics engine
  100426. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  100427. * @return a boolean indicating if the physics engine was initialized
  100428. */
  100429. BABYLON.Scene.prototype.enablePhysics = function (gravity, plugin) {
  100430. if (gravity === void 0) { gravity = null; }
  100431. if (this._physicsEngine) {
  100432. return true;
  100433. }
  100434. // Register the component to the scene
  100435. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_PHYSICSENGINE);
  100436. if (!component) {
  100437. component = new PhysicsEngineSceneComponent(this);
  100438. this._addComponent(component);
  100439. }
  100440. try {
  100441. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  100442. return true;
  100443. }
  100444. catch (e) {
  100445. BABYLON.Tools.Error(e.message);
  100446. return false;
  100447. }
  100448. };
  100449. /**
  100450. * Disables and disposes the physics engine associated with the scene
  100451. */
  100452. BABYLON.Scene.prototype.disablePhysicsEngine = function () {
  100453. if (!this._physicsEngine) {
  100454. return;
  100455. }
  100456. this._physicsEngine.dispose();
  100457. this._physicsEngine = null;
  100458. };
  100459. /**
  100460. * Gets a boolean indicating if there is an active physics engine
  100461. * @returns a boolean indicating if there is an active physics engine
  100462. */
  100463. BABYLON.Scene.prototype.isPhysicsEnabled = function () {
  100464. return this._physicsEngine !== undefined;
  100465. };
  100466. /**
  100467. * Deletes a physics compound impostor
  100468. * @param compound defines the compound to delete
  100469. */
  100470. BABYLON.Scene.prototype.deleteCompoundImpostor = function (compound) {
  100471. var mesh = compound.parts[0].mesh;
  100472. if (mesh.physicsImpostor) {
  100473. mesh.physicsImpostor.dispose( /*true*/);
  100474. mesh.physicsImpostor = null;
  100475. }
  100476. };
  100477. /** @hidden */
  100478. BABYLON.Scene.prototype._advancePhysicsEngineStep = function (step) {
  100479. if (this._physicsEngine) {
  100480. this.onBeforePhysicsObservable.notifyObservers(this);
  100481. this._physicsEngine._step(step / 1000);
  100482. this.onAfterPhysicsObservable.notifyObservers(this);
  100483. }
  100484. };
  100485. Object.defineProperty(BABYLON.AbstractMesh.prototype, "physicsImpostor", {
  100486. get: function () {
  100487. return this._physicsImpostor;
  100488. },
  100489. set: function (value) {
  100490. var _this = this;
  100491. if (this._physicsImpostor === value) {
  100492. return;
  100493. }
  100494. if (this._disposePhysicsObserver) {
  100495. this.onDisposeObservable.remove(this._disposePhysicsObserver);
  100496. }
  100497. this._physicsImpostor = value;
  100498. if (value) {
  100499. this._disposePhysicsObserver = this.onDisposeObservable.add(function () {
  100500. // Physics
  100501. if (_this.physicsImpostor) {
  100502. _this.physicsImpostor.dispose( /*!doNotRecurse*/);
  100503. _this.physicsImpostor = null;
  100504. }
  100505. });
  100506. }
  100507. },
  100508. enumerable: true,
  100509. configurable: true
  100510. });
  100511. /**
  100512. * Gets the current physics impostor
  100513. * @see http://doc.babylonjs.com/features/physics_engine
  100514. * @returns a physics impostor or null
  100515. */
  100516. BABYLON.AbstractMesh.prototype.getPhysicsImpostor = function () {
  100517. return this.physicsImpostor;
  100518. };
  100519. /**
  100520. * Apply a physic impulse to the mesh
  100521. * @param force defines the force to apply
  100522. * @param contactPoint defines where to apply the force
  100523. * @returns the current mesh
  100524. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  100525. */
  100526. BABYLON.AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  100527. if (!this.physicsImpostor) {
  100528. return this;
  100529. }
  100530. this.physicsImpostor.applyImpulse(force, contactPoint);
  100531. return this;
  100532. };
  100533. /**
  100534. * Creates a physic joint between two meshes
  100535. * @param otherMesh defines the other mesh to use
  100536. * @param pivot1 defines the pivot to use on this mesh
  100537. * @param pivot2 defines the pivot to use on the other mesh
  100538. * @param options defines additional options (can be plugin dependent)
  100539. * @returns the current mesh
  100540. * @see https://www.babylonjs-playground.com/#0BS5U0#0
  100541. */
  100542. BABYLON.AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  100543. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  100544. return this;
  100545. }
  100546. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  100547. mainPivot: pivot1,
  100548. connectedPivot: pivot2,
  100549. nativeParams: options
  100550. });
  100551. return this;
  100552. };
  100553. /**
  100554. * Defines the physics engine scene component responsible to manage a physics engine
  100555. */
  100556. var PhysicsEngineSceneComponent = /** @class */ (function () {
  100557. /**
  100558. * Creates a new instance of the component for the given scene
  100559. * @param scene Defines the scene to register the component in
  100560. */
  100561. function PhysicsEngineSceneComponent(scene) {
  100562. var _this = this;
  100563. /**
  100564. * The component name helpful to identify the component in the list of scene components.
  100565. */
  100566. this.name = BABYLON.SceneComponentConstants.NAME_PHYSICSENGINE;
  100567. this.scene = scene;
  100568. this.scene.onBeforePhysicsObservable = new BABYLON.Observable();
  100569. this.scene.onAfterPhysicsObservable = new BABYLON.Observable();
  100570. // Replace the function used to get the deterministic frame time
  100571. this.scene.getDeterministicFrameTime = function () {
  100572. if (_this.scene._physicsEngine) {
  100573. return _this.scene._physicsEngine.getTimeStep() * 1000;
  100574. }
  100575. return 1000.0 / 60.0;
  100576. };
  100577. }
  100578. /**
  100579. * Registers the component in a given scene
  100580. */
  100581. PhysicsEngineSceneComponent.prototype.register = function () {
  100582. };
  100583. /**
  100584. * Rebuilds the elements related to this component in case of
  100585. * context lost for instance.
  100586. */
  100587. PhysicsEngineSceneComponent.prototype.rebuild = function () {
  100588. // Nothing to do for this component
  100589. };
  100590. /**
  100591. * Disposes the component and the associated ressources
  100592. */
  100593. PhysicsEngineSceneComponent.prototype.dispose = function () {
  100594. this.scene.onBeforePhysicsObservable.clear();
  100595. this.scene.onAfterPhysicsObservable.clear();
  100596. if (this.scene._physicsEngine) {
  100597. this.scene.disablePhysicsEngine();
  100598. }
  100599. };
  100600. return PhysicsEngineSceneComponent;
  100601. }());
  100602. BABYLON.PhysicsEngineSceneComponent = PhysicsEngineSceneComponent;
  100603. })(BABYLON || (BABYLON = {}));
  100604. //# sourceMappingURL=babylon.physicsEngineComponent.js.map
  100605. var BABYLON;
  100606. (function (BABYLON) {
  100607. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  100608. // All values and structures referenced from:
  100609. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  100610. var DDS_MAGIC = 0x20534444;
  100611. var
  100612. //DDSD_CAPS = 0x1,
  100613. //DDSD_HEIGHT = 0x2,
  100614. //DDSD_WIDTH = 0x4,
  100615. //DDSD_PITCH = 0x8,
  100616. //DDSD_PIXELFORMAT = 0x1000,
  100617. DDSD_MIPMAPCOUNT = 0x20000;
  100618. //DDSD_LINEARSIZE = 0x80000,
  100619. //DDSD_DEPTH = 0x800000;
  100620. // var DDSCAPS_COMPLEX = 0x8,
  100621. // DDSCAPS_MIPMAP = 0x400000,
  100622. // DDSCAPS_TEXTURE = 0x1000;
  100623. var DDSCAPS2_CUBEMAP = 0x200;
  100624. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  100625. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  100626. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  100627. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  100628. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  100629. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  100630. // DDSCAPS2_VOLUME = 0x200000;
  100631. var
  100632. //DDPF_ALPHAPIXELS = 0x1,
  100633. //DDPF_ALPHA = 0x2,
  100634. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  100635. //DDPF_YUV = 0x200,
  100636. DDPF_LUMINANCE = 0x20000;
  100637. function FourCCToInt32(value) {
  100638. return value.charCodeAt(0) +
  100639. (value.charCodeAt(1) << 8) +
  100640. (value.charCodeAt(2) << 16) +
  100641. (value.charCodeAt(3) << 24);
  100642. }
  100643. function Int32ToFourCC(value) {
  100644. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  100645. }
  100646. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  100647. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  100648. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  100649. var FOURCC_DX10 = FourCCToInt32("DX10");
  100650. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  100651. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  100652. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  100653. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  100654. var headerLengthInt = 31; // The header length in 32 bit ints
  100655. // Offsets into the header array
  100656. var off_magic = 0;
  100657. var off_size = 1;
  100658. var off_flags = 2;
  100659. var off_height = 3;
  100660. var off_width = 4;
  100661. var off_mipmapCount = 7;
  100662. var off_pfFlags = 20;
  100663. var off_pfFourCC = 21;
  100664. var off_RGBbpp = 22;
  100665. var off_RMask = 23;
  100666. var off_GMask = 24;
  100667. var off_BMask = 25;
  100668. var off_AMask = 26;
  100669. // var off_caps1 = 27;
  100670. var off_caps2 = 28;
  100671. // var off_caps3 = 29;
  100672. // var off_caps4 = 30;
  100673. var off_dxgiFormat = 32;
  100674. /**
  100675. * Class used to provide DDS decompression tools
  100676. */
  100677. var DDSTools = /** @class */ (function () {
  100678. function DDSTools() {
  100679. }
  100680. /**
  100681. * Gets DDS information from an array buffer
  100682. * @param arrayBuffer defines the array buffer to read data from
  100683. * @returns the DDS information
  100684. */
  100685. DDSTools.GetDDSInfo = function (arrayBuffer) {
  100686. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  100687. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  100688. var mipmapCount = 1;
  100689. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  100690. mipmapCount = Math.max(1, header[off_mipmapCount]);
  100691. }
  100692. var fourCC = header[off_pfFourCC];
  100693. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  100694. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  100695. switch (fourCC) {
  100696. case FOURCC_D3DFMT_R16G16B16A16F:
  100697. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  100698. break;
  100699. case FOURCC_D3DFMT_R32G32B32A32F:
  100700. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  100701. break;
  100702. case FOURCC_DX10:
  100703. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  100704. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  100705. break;
  100706. }
  100707. }
  100708. return {
  100709. width: header[off_width],
  100710. height: header[off_height],
  100711. mipmapCount: mipmapCount,
  100712. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  100713. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  100714. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  100715. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  100716. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  100717. dxgiFormat: dxgiFormat,
  100718. textureType: textureType
  100719. };
  100720. };
  100721. DDSTools._ToHalfFloat = function (value) {
  100722. if (!DDSTools._FloatView) {
  100723. DDSTools._FloatView = new Float32Array(1);
  100724. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  100725. }
  100726. DDSTools._FloatView[0] = value;
  100727. var x = DDSTools._Int32View[0];
  100728. var bits = (x >> 16) & 0x8000; /* Get the sign */
  100729. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  100730. var e = (x >> 23) & 0xff; /* Using int is faster here */
  100731. /* If zero, or denormal, or exponent underflows too much for a denormal
  100732. * half, return signed zero. */
  100733. if (e < 103) {
  100734. return bits;
  100735. }
  100736. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  100737. if (e > 142) {
  100738. bits |= 0x7c00;
  100739. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  100740. * not Inf, so make sure we set one mantissa bit too. */
  100741. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  100742. return bits;
  100743. }
  100744. /* If exponent underflows but not too much, return a denormal */
  100745. if (e < 113) {
  100746. m |= 0x0800;
  100747. /* Extra rounding may overflow and set mantissa to 0 and exponent
  100748. * to 1, which is OK. */
  100749. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  100750. return bits;
  100751. }
  100752. bits |= ((e - 112) << 10) | (m >> 1);
  100753. bits += m & 1;
  100754. return bits;
  100755. };
  100756. DDSTools._FromHalfFloat = function (value) {
  100757. var s = (value & 0x8000) >> 15;
  100758. var e = (value & 0x7C00) >> 10;
  100759. var f = value & 0x03FF;
  100760. if (e === 0) {
  100761. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  100762. }
  100763. else if (e == 0x1F) {
  100764. return f ? NaN : ((s ? -1 : 1) * Infinity);
  100765. }
  100766. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  100767. };
  100768. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  100769. var destArray = new Float32Array(dataLength);
  100770. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  100771. var index = 0;
  100772. for (var y = 0; y < height; y++) {
  100773. for (var x = 0; x < width; x++) {
  100774. var srcPos = (x + y * width) * 4;
  100775. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  100776. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  100777. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  100778. if (DDSTools.StoreLODInAlphaChannel) {
  100779. destArray[index + 3] = lod;
  100780. }
  100781. else {
  100782. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  100783. }
  100784. index += 4;
  100785. }
  100786. }
  100787. return destArray;
  100788. };
  100789. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  100790. if (DDSTools.StoreLODInAlphaChannel) {
  100791. var destArray = new Uint16Array(dataLength);
  100792. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  100793. var index = 0;
  100794. for (var y = 0; y < height; y++) {
  100795. for (var x = 0; x < width; x++) {
  100796. var srcPos = (x + y * width) * 4;
  100797. destArray[index] = srcData[srcPos];
  100798. destArray[index + 1] = srcData[srcPos + 1];
  100799. destArray[index + 2] = srcData[srcPos + 2];
  100800. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  100801. index += 4;
  100802. }
  100803. }
  100804. return destArray;
  100805. }
  100806. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  100807. };
  100808. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  100809. if (DDSTools.StoreLODInAlphaChannel) {
  100810. var destArray = new Float32Array(dataLength);
  100811. var srcData = new Float32Array(arrayBuffer, dataOffset);
  100812. var index = 0;
  100813. for (var y = 0; y < height; y++) {
  100814. for (var x = 0; x < width; x++) {
  100815. var srcPos = (x + y * width) * 4;
  100816. destArray[index] = srcData[srcPos];
  100817. destArray[index + 1] = srcData[srcPos + 1];
  100818. destArray[index + 2] = srcData[srcPos + 2];
  100819. destArray[index + 3] = lod;
  100820. index += 4;
  100821. }
  100822. }
  100823. return destArray;
  100824. }
  100825. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  100826. };
  100827. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  100828. var destArray = new Uint8Array(dataLength);
  100829. var srcData = new Float32Array(arrayBuffer, dataOffset);
  100830. var index = 0;
  100831. for (var y = 0; y < height; y++) {
  100832. for (var x = 0; x < width; x++) {
  100833. var srcPos = (x + y * width) * 4;
  100834. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  100835. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  100836. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  100837. if (DDSTools.StoreLODInAlphaChannel) {
  100838. destArray[index + 3] = lod;
  100839. }
  100840. else {
  100841. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  100842. }
  100843. index += 4;
  100844. }
  100845. }
  100846. return destArray;
  100847. };
  100848. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  100849. var destArray = new Uint8Array(dataLength);
  100850. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  100851. var index = 0;
  100852. for (var y = 0; y < height; y++) {
  100853. for (var x = 0; x < width; x++) {
  100854. var srcPos = (x + y * width) * 4;
  100855. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  100856. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  100857. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  100858. if (DDSTools.StoreLODInAlphaChannel) {
  100859. destArray[index + 3] = lod;
  100860. }
  100861. else {
  100862. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  100863. }
  100864. index += 4;
  100865. }
  100866. }
  100867. return destArray;
  100868. };
  100869. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  100870. var byteArray = new Uint8Array(dataLength);
  100871. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  100872. var index = 0;
  100873. for (var y = 0; y < height; y++) {
  100874. for (var x = 0; x < width; x++) {
  100875. var srcPos = (x + y * width) * 4;
  100876. byteArray[index] = srcData[srcPos + rOffset];
  100877. byteArray[index + 1] = srcData[srcPos + gOffset];
  100878. byteArray[index + 2] = srcData[srcPos + bOffset];
  100879. byteArray[index + 3] = srcData[srcPos + aOffset];
  100880. index += 4;
  100881. }
  100882. }
  100883. return byteArray;
  100884. };
  100885. DDSTools._ExtractLongWordOrder = function (value) {
  100886. if (value === 0 || value === 255 || value === -16777216) {
  100887. return 0;
  100888. }
  100889. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  100890. };
  100891. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  100892. var byteArray = new Uint8Array(dataLength);
  100893. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  100894. var index = 0;
  100895. for (var y = 0; y < height; y++) {
  100896. for (var x = 0; x < width; x++) {
  100897. var srcPos = (x + y * width) * 3;
  100898. byteArray[index] = srcData[srcPos + rOffset];
  100899. byteArray[index + 1] = srcData[srcPos + gOffset];
  100900. byteArray[index + 2] = srcData[srcPos + bOffset];
  100901. index += 3;
  100902. }
  100903. }
  100904. return byteArray;
  100905. };
  100906. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  100907. var byteArray = new Uint8Array(dataLength);
  100908. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  100909. var index = 0;
  100910. for (var y = 0; y < height; y++) {
  100911. for (var x = 0; x < width; x++) {
  100912. var srcPos = (x + y * width);
  100913. byteArray[index] = srcData[srcPos];
  100914. index++;
  100915. }
  100916. }
  100917. return byteArray;
  100918. };
  100919. /**
  100920. * Uploads DDS Levels to a Babylon Texture
  100921. * @hidden
  100922. */
  100923. DDSTools.UploadDDSLevels = function (engine, texture, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  100924. if (lodIndex === void 0) { lodIndex = -1; }
  100925. var sphericalPolynomialFaces = null;
  100926. if (info.sphericalPolynomial) {
  100927. sphericalPolynomialFaces = new Array();
  100928. }
  100929. var ext = engine.getCaps().s3tc;
  100930. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  100931. var fourCC, width, height, dataLength = 0, dataOffset;
  100932. var byteArray, mipmapCount, mip;
  100933. var internalCompressedFormat = 0;
  100934. var blockBytes = 1;
  100935. if (header[off_magic] !== DDS_MAGIC) {
  100936. BABYLON.Tools.Error("Invalid magic number in DDS header");
  100937. return;
  100938. }
  100939. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  100940. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  100941. return;
  100942. }
  100943. if (info.isCompressed && !ext) {
  100944. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  100945. return;
  100946. }
  100947. var bpp = header[off_RGBbpp];
  100948. dataOffset = header[off_size] + 4;
  100949. var computeFormats = false;
  100950. if (info.isFourCC) {
  100951. fourCC = header[off_pfFourCC];
  100952. switch (fourCC) {
  100953. case FOURCC_DXT1:
  100954. blockBytes = 8;
  100955. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  100956. break;
  100957. case FOURCC_DXT3:
  100958. blockBytes = 16;
  100959. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  100960. break;
  100961. case FOURCC_DXT5:
  100962. blockBytes = 16;
  100963. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  100964. break;
  100965. case FOURCC_D3DFMT_R16G16B16A16F:
  100966. computeFormats = true;
  100967. break;
  100968. case FOURCC_D3DFMT_R32G32B32A32F:
  100969. computeFormats = true;
  100970. break;
  100971. case FOURCC_DX10:
  100972. // There is an additionnal header so dataOffset need to be changed
  100973. dataOffset += 5 * 4; // 5 uints
  100974. var supported = false;
  100975. switch (info.dxgiFormat) {
  100976. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  100977. computeFormats = true;
  100978. supported = true;
  100979. break;
  100980. case DXGI_FORMAT_B8G8R8X8_UNORM:
  100981. info.isRGB = true;
  100982. info.isFourCC = false;
  100983. bpp = 32;
  100984. supported = true;
  100985. break;
  100986. }
  100987. if (supported) {
  100988. break;
  100989. }
  100990. default:
  100991. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  100992. return;
  100993. }
  100994. }
  100995. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  100996. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  100997. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  100998. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  100999. if (computeFormats) {
  101000. internalCompressedFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  101001. }
  101002. mipmapCount = 1;
  101003. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  101004. mipmapCount = Math.max(1, header[off_mipmapCount]);
  101005. }
  101006. for (var face = 0; face < faces; face++) {
  101007. width = header[off_width];
  101008. height = header[off_height];
  101009. for (mip = 0; mip < mipmapCount; ++mip) {
  101010. if (lodIndex === -1 || lodIndex === mip) {
  101011. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  101012. var i = (lodIndex === -1) ? mip : 0;
  101013. if (!info.isCompressed && info.isFourCC) {
  101014. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  101015. dataLength = width * height * 4;
  101016. var floatArray = null;
  101017. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) { // Required because iOS has many issues with float and half float generation
  101018. if (bpp === 128) {
  101019. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  101020. if (sphericalPolynomialFaces && i == 0) {
  101021. sphericalPolynomialFaces.push(DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  101022. }
  101023. }
  101024. else if (bpp === 64) {
  101025. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  101026. if (sphericalPolynomialFaces && i == 0) {
  101027. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  101028. }
  101029. }
  101030. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  101031. }
  101032. else {
  101033. if (bpp === 128) {
  101034. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  101035. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  101036. if (sphericalPolynomialFaces && i == 0) {
  101037. sphericalPolynomialFaces.push(floatArray);
  101038. }
  101039. }
  101040. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  101041. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  101042. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  101043. if (sphericalPolynomialFaces && i == 0) {
  101044. sphericalPolynomialFaces.push(floatArray);
  101045. }
  101046. }
  101047. else { // 64
  101048. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  101049. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  101050. if (sphericalPolynomialFaces && i == 0) {
  101051. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  101052. }
  101053. }
  101054. }
  101055. if (floatArray) {
  101056. engine._uploadDataToTextureDirectly(texture, floatArray, face, i);
  101057. }
  101058. }
  101059. else if (info.isRGB) {
  101060. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  101061. if (bpp === 24) {
  101062. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGB;
  101063. dataLength = width * height * 3;
  101064. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  101065. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  101066. }
  101067. else { // 32
  101068. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  101069. dataLength = width * height * 4;
  101070. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  101071. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  101072. }
  101073. }
  101074. else if (info.isLuminance) {
  101075. var unpackAlignment = engine._getUnpackAlignement();
  101076. var unpaddedRowSize = width;
  101077. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  101078. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  101079. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  101080. texture.format = BABYLON.Engine.TEXTUREFORMAT_LUMINANCE;
  101081. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  101082. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  101083. }
  101084. else {
  101085. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  101086. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  101087. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  101088. engine._uploadCompressedDataToTextureDirectly(texture, internalCompressedFormat, width, height, byteArray, face, i);
  101089. }
  101090. }
  101091. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  101092. width *= 0.5;
  101093. height *= 0.5;
  101094. width = Math.max(1.0, width);
  101095. height = Math.max(1.0, height);
  101096. }
  101097. if (currentFace !== undefined) {
  101098. // Loading a single face
  101099. break;
  101100. }
  101101. }
  101102. if (sphericalPolynomialFaces && sphericalPolynomialFaces.length > 0) {
  101103. info.sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({
  101104. size: header[off_width],
  101105. right: sphericalPolynomialFaces[0],
  101106. left: sphericalPolynomialFaces[1],
  101107. up: sphericalPolynomialFaces[2],
  101108. down: sphericalPolynomialFaces[3],
  101109. front: sphericalPolynomialFaces[4],
  101110. back: sphericalPolynomialFaces[5],
  101111. format: BABYLON.Engine.TEXTUREFORMAT_RGBA,
  101112. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  101113. gammaSpace: false,
  101114. });
  101115. }
  101116. else {
  101117. info.sphericalPolynomial = undefined;
  101118. }
  101119. };
  101120. /**
  101121. * Gets or sets a boolean indicating that LOD info is stored in alpha channel (false by default)
  101122. */
  101123. DDSTools.StoreLODInAlphaChannel = false;
  101124. return DDSTools;
  101125. }());
  101126. BABYLON.DDSTools = DDSTools;
  101127. })(BABYLON || (BABYLON = {}));
  101128. //# sourceMappingURL=babylon.dds.js.map
  101129. var BABYLON;
  101130. (function (BABYLON) {
  101131. /**
  101132. * Implementation of the DDS Texture Loader.
  101133. */
  101134. var DDSTextureLoader = /** @class */ (function () {
  101135. function DDSTextureLoader() {
  101136. /**
  101137. * Defines wether the loader supports cascade loading the different faces.
  101138. */
  101139. this.supportCascades = true;
  101140. }
  101141. /**
  101142. * This returns if the loader support the current file information.
  101143. * @param extension defines the file extension of the file being loaded
  101144. * @param textureFormatInUse defines the current compressed format in use iun the engine
  101145. * @param fallback defines the fallback internal texture if any
  101146. * @param isBase64 defines whether the texture is encoded as a base64
  101147. * @param isBuffer defines whether the texture data are stored as a buffer
  101148. * @returns true if the loader can load the specified file
  101149. */
  101150. DDSTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  101151. return extension.indexOf(".dds") === 0;
  101152. };
  101153. /**
  101154. * Transform the url before loading if required.
  101155. * @param rootUrl the url of the texture
  101156. * @param textureFormatInUse defines the current compressed format in use iun the engine
  101157. * @returns the transformed texture
  101158. */
  101159. DDSTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  101160. return rootUrl;
  101161. };
  101162. /**
  101163. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  101164. * @param rootUrl the url of the texture
  101165. * @param textureFormatInUse defines the current compressed format in use iun the engine
  101166. * @returns the fallback texture
  101167. */
  101168. DDSTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  101169. return null;
  101170. };
  101171. /**
  101172. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  101173. * @param data contains the texture data
  101174. * @param texture defines the BabylonJS internal texture
  101175. * @param createPolynomials will be true if polynomials have been requested
  101176. * @param onLoad defines the callback to trigger once the texture is ready
  101177. * @param onError defines the callback to trigger in case of error
  101178. */
  101179. DDSTextureLoader.prototype.loadCubeData = function (imgs, texture, createPolynomials, onLoad, onError) {
  101180. var engine = texture.getEngine();
  101181. var info;
  101182. var loadMipmap = false;
  101183. if (Array.isArray(imgs)) {
  101184. for (var index = 0; index < imgs.length; index++) {
  101185. var data_1 = imgs[index];
  101186. info = BABYLON.DDSTools.GetDDSInfo(data_1);
  101187. texture.width = info.width;
  101188. texture.height = info.height;
  101189. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;
  101190. engine._unpackFlipY(info.isCompressed);
  101191. BABYLON.DDSTools.UploadDDSLevels(engine, texture, data_1, info, loadMipmap, 6, -1, index);
  101192. if (!info.isFourCC && info.mipmapCount === 1) {
  101193. engine.generateMipMapsForCubemap(texture);
  101194. }
  101195. }
  101196. }
  101197. else {
  101198. var data = imgs;
  101199. info = BABYLON.DDSTools.GetDDSInfo(data);
  101200. texture.width = info.width;
  101201. texture.height = info.height;
  101202. if (createPolynomials) {
  101203. info.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  101204. }
  101205. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;
  101206. engine._unpackFlipY(info.isCompressed);
  101207. BABYLON.DDSTools.UploadDDSLevels(engine, texture, data, info, loadMipmap, 6);
  101208. if (!info.isFourCC && info.mipmapCount === 1) {
  101209. engine.generateMipMapsForCubemap(texture);
  101210. }
  101211. }
  101212. engine._setCubeMapTextureParams(loadMipmap);
  101213. texture.isReady = true;
  101214. if (onLoad) {
  101215. onLoad({ isDDS: true, width: texture.width, info: info, data: imgs, texture: texture });
  101216. }
  101217. };
  101218. /**
  101219. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  101220. * @param data contains the texture data
  101221. * @param texture defines the BabylonJS internal texture
  101222. * @param callback defines the method to call once ready to upload
  101223. */
  101224. DDSTextureLoader.prototype.loadData = function (data, texture, callback) {
  101225. var info = BABYLON.DDSTools.GetDDSInfo(data);
  101226. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps && ((info.width >> (info.mipmapCount - 1)) === 1);
  101227. callback(info.width, info.height, loadMipmap, info.isFourCC, function () {
  101228. BABYLON.DDSTools.UploadDDSLevels(texture.getEngine(), texture, data, info, loadMipmap, 1);
  101229. });
  101230. };
  101231. return DDSTextureLoader;
  101232. }());
  101233. // Register the loader.
  101234. BABYLON.Engine._TextureLoaders.push(new DDSTextureLoader());
  101235. })(BABYLON || (BABYLON = {}));
  101236. //# sourceMappingURL=babylon.ddsTextureLoader.js.map
  101237. var BABYLON;
  101238. (function (BABYLON) {
  101239. /**
  101240. * Based on jsTGALoader - Javascript loader for TGA file
  101241. * By Vincent Thibault
  101242. * @see http://blog.robrowser.com/javascript-tga-loader.html
  101243. */
  101244. var TGATools = /** @class */ (function () {
  101245. function TGATools() {
  101246. }
  101247. /**
  101248. * Gets the header of a TGA file
  101249. * @param data defines the TGA data
  101250. * @returns the header
  101251. */
  101252. TGATools.GetTGAHeader = function (data) {
  101253. var offset = 0;
  101254. var header = {
  101255. id_length: data[offset++],
  101256. colormap_type: data[offset++],
  101257. image_type: data[offset++],
  101258. colormap_index: data[offset++] | data[offset++] << 8,
  101259. colormap_length: data[offset++] | data[offset++] << 8,
  101260. colormap_size: data[offset++],
  101261. origin: [
  101262. data[offset++] | data[offset++] << 8,
  101263. data[offset++] | data[offset++] << 8
  101264. ],
  101265. width: data[offset++] | data[offset++] << 8,
  101266. height: data[offset++] | data[offset++] << 8,
  101267. pixel_size: data[offset++],
  101268. flags: data[offset++]
  101269. };
  101270. return header;
  101271. };
  101272. /**
  101273. * Uploads TGA content to a Babylon Texture
  101274. * @hidden
  101275. */
  101276. TGATools.UploadContent = function (texture, data) {
  101277. // Not enough data to contain header ?
  101278. if (data.length < 19) {
  101279. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  101280. return;
  101281. }
  101282. // Read Header
  101283. var offset = 18;
  101284. var header = TGATools.GetTGAHeader(data);
  101285. // Assume it's a valid Targa file.
  101286. if (header.id_length + offset > data.length) {
  101287. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  101288. return;
  101289. }
  101290. // Skip not needed data
  101291. offset += header.id_length;
  101292. var use_rle = false;
  101293. var use_pal = false;
  101294. var use_grey = false;
  101295. // Get some informations.
  101296. switch (header.image_type) {
  101297. case TGATools._TYPE_RLE_INDEXED:
  101298. use_rle = true;
  101299. case TGATools._TYPE_INDEXED:
  101300. use_pal = true;
  101301. break;
  101302. case TGATools._TYPE_RLE_RGB:
  101303. use_rle = true;
  101304. case TGATools._TYPE_RGB:
  101305. // use_rgb = true;
  101306. break;
  101307. case TGATools._TYPE_RLE_GREY:
  101308. use_rle = true;
  101309. case TGATools._TYPE_GREY:
  101310. use_grey = true;
  101311. break;
  101312. }
  101313. var pixel_data;
  101314. // var numAlphaBits = header.flags & 0xf;
  101315. var pixel_size = header.pixel_size >> 3;
  101316. var pixel_total = header.width * header.height * pixel_size;
  101317. // Read palettes
  101318. var palettes;
  101319. if (use_pal) {
  101320. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  101321. }
  101322. // Read LRE
  101323. if (use_rle) {
  101324. pixel_data = new Uint8Array(pixel_total);
  101325. var c, count, i;
  101326. var localOffset = 0;
  101327. var pixels = new Uint8Array(pixel_size);
  101328. while (offset < pixel_total && localOffset < pixel_total) {
  101329. c = data[offset++];
  101330. count = (c & 0x7f) + 1;
  101331. // RLE pixels
  101332. if (c & 0x80) {
  101333. // Bind pixel tmp array
  101334. for (i = 0; i < pixel_size; ++i) {
  101335. pixels[i] = data[offset++];
  101336. }
  101337. // Copy pixel array
  101338. for (i = 0; i < count; ++i) {
  101339. pixel_data.set(pixels, localOffset + i * pixel_size);
  101340. }
  101341. localOffset += pixel_size * count;
  101342. }
  101343. // Raw pixels
  101344. else {
  101345. count *= pixel_size;
  101346. for (i = 0; i < count; ++i) {
  101347. pixel_data[localOffset + i] = data[offset++];
  101348. }
  101349. localOffset += count;
  101350. }
  101351. }
  101352. }
  101353. // RAW Pixels
  101354. else {
  101355. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  101356. }
  101357. // Load to texture
  101358. var x_start, y_start, x_step, y_step, y_end, x_end;
  101359. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  101360. default:
  101361. case TGATools._ORIGIN_UL:
  101362. x_start = 0;
  101363. x_step = 1;
  101364. x_end = header.width;
  101365. y_start = 0;
  101366. y_step = 1;
  101367. y_end = header.height;
  101368. break;
  101369. case TGATools._ORIGIN_BL:
  101370. x_start = 0;
  101371. x_step = 1;
  101372. x_end = header.width;
  101373. y_start = header.height - 1;
  101374. y_step = -1;
  101375. y_end = -1;
  101376. break;
  101377. case TGATools._ORIGIN_UR:
  101378. x_start = header.width - 1;
  101379. x_step = -1;
  101380. x_end = -1;
  101381. y_start = 0;
  101382. y_step = 1;
  101383. y_end = header.height;
  101384. break;
  101385. case TGATools._ORIGIN_BR:
  101386. x_start = header.width - 1;
  101387. x_step = -1;
  101388. x_end = -1;
  101389. y_start = header.height - 1;
  101390. y_step = -1;
  101391. y_end = -1;
  101392. break;
  101393. }
  101394. // Load the specify method
  101395. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  101396. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  101397. var engine = texture.getEngine();
  101398. engine._uploadDataToTextureDirectly(texture, imageData);
  101399. };
  101400. /** @hidden */
  101401. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  101402. var image = pixel_data, colormap = palettes;
  101403. var width = header.width, height = header.height;
  101404. var color, i = 0, x, y;
  101405. var imageData = new Uint8Array(width * height * 4);
  101406. for (y = y_start; y !== y_end; y += y_step) {
  101407. for (x = x_start; x !== x_end; x += x_step, i++) {
  101408. color = image[i];
  101409. imageData[(x + width * y) * 4 + 3] = 255;
  101410. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  101411. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  101412. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  101413. }
  101414. }
  101415. return imageData;
  101416. };
  101417. /** @hidden */
  101418. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  101419. var image = pixel_data;
  101420. var width = header.width, height = header.height;
  101421. var color, i = 0, x, y;
  101422. var imageData = new Uint8Array(width * height * 4);
  101423. for (y = y_start; y !== y_end; y += y_step) {
  101424. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  101425. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  101426. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  101427. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  101428. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  101429. imageData[(x + width * y) * 4 + 0] = r;
  101430. imageData[(x + width * y) * 4 + 1] = g;
  101431. imageData[(x + width * y) * 4 + 2] = b;
  101432. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  101433. }
  101434. }
  101435. return imageData;
  101436. };
  101437. /** @hidden */
  101438. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  101439. var image = pixel_data;
  101440. var width = header.width, height = header.height;
  101441. var i = 0, x, y;
  101442. var imageData = new Uint8Array(width * height * 4);
  101443. for (y = y_start; y !== y_end; y += y_step) {
  101444. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  101445. imageData[(x + width * y) * 4 + 3] = 255;
  101446. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  101447. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  101448. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  101449. }
  101450. }
  101451. return imageData;
  101452. };
  101453. /** @hidden */
  101454. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  101455. var image = pixel_data;
  101456. var width = header.width, height = header.height;
  101457. var i = 0, x, y;
  101458. var imageData = new Uint8Array(width * height * 4);
  101459. for (y = y_start; y !== y_end; y += y_step) {
  101460. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  101461. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  101462. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  101463. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  101464. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  101465. }
  101466. }
  101467. return imageData;
  101468. };
  101469. /** @hidden */
  101470. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  101471. var image = pixel_data;
  101472. var width = header.width, height = header.height;
  101473. var color, i = 0, x, y;
  101474. var imageData = new Uint8Array(width * height * 4);
  101475. for (y = y_start; y !== y_end; y += y_step) {
  101476. for (x = x_start; x !== x_end; x += x_step, i++) {
  101477. color = image[i];
  101478. imageData[(x + width * y) * 4 + 0] = color;
  101479. imageData[(x + width * y) * 4 + 1] = color;
  101480. imageData[(x + width * y) * 4 + 2] = color;
  101481. imageData[(x + width * y) * 4 + 3] = 255;
  101482. }
  101483. }
  101484. return imageData;
  101485. };
  101486. /** @hidden */
  101487. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  101488. var image = pixel_data;
  101489. var width = header.width, height = header.height;
  101490. var i = 0, x, y;
  101491. var imageData = new Uint8Array(width * height * 4);
  101492. for (y = y_start; y !== y_end; y += y_step) {
  101493. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  101494. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  101495. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  101496. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  101497. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  101498. }
  101499. }
  101500. return imageData;
  101501. };
  101502. //private static _TYPE_NO_DATA = 0;
  101503. TGATools._TYPE_INDEXED = 1;
  101504. TGATools._TYPE_RGB = 2;
  101505. TGATools._TYPE_GREY = 3;
  101506. TGATools._TYPE_RLE_INDEXED = 9;
  101507. TGATools._TYPE_RLE_RGB = 10;
  101508. TGATools._TYPE_RLE_GREY = 11;
  101509. TGATools._ORIGIN_MASK = 0x30;
  101510. TGATools._ORIGIN_SHIFT = 0x04;
  101511. TGATools._ORIGIN_BL = 0x00;
  101512. TGATools._ORIGIN_BR = 0x01;
  101513. TGATools._ORIGIN_UL = 0x02;
  101514. TGATools._ORIGIN_UR = 0x03;
  101515. return TGATools;
  101516. }());
  101517. BABYLON.TGATools = TGATools;
  101518. })(BABYLON || (BABYLON = {}));
  101519. //# sourceMappingURL=babylon.tga.js.map
  101520. var BABYLON;
  101521. (function (BABYLON) {
  101522. /**
  101523. * Implementation of the TGA Texture Loader.
  101524. */
  101525. var TGATextureLoader = /** @class */ (function () {
  101526. function TGATextureLoader() {
  101527. /**
  101528. * Defines wether the loader supports cascade loading the different faces.
  101529. */
  101530. this.supportCascades = false;
  101531. }
  101532. /**
  101533. * This returns if the loader support the current file information.
  101534. * @param extension defines the file extension of the file being loaded
  101535. * @param textureFormatInUse defines the current compressed format in use iun the engine
  101536. * @param fallback defines the fallback internal texture if any
  101537. * @param isBase64 defines whether the texture is encoded as a base64
  101538. * @param isBuffer defines whether the texture data are stored as a buffer
  101539. * @returns true if the loader can load the specified file
  101540. */
  101541. TGATextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  101542. return extension.indexOf(".tga") === 0;
  101543. };
  101544. /**
  101545. * Transform the url before loading if required.
  101546. * @param rootUrl the url of the texture
  101547. * @param textureFormatInUse defines the current compressed format in use iun the engine
  101548. * @returns the transformed texture
  101549. */
  101550. TGATextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  101551. return rootUrl;
  101552. };
  101553. /**
  101554. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  101555. * @param rootUrl the url of the texture
  101556. * @param textureFormatInUse defines the current compressed format in use iun the engine
  101557. * @returns the fallback texture
  101558. */
  101559. TGATextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  101560. return null;
  101561. };
  101562. /**
  101563. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  101564. * @param data contains the texture data
  101565. * @param texture defines the BabylonJS internal texture
  101566. * @param createPolynomials will be true if polynomials have been requested
  101567. * @param onLoad defines the callback to trigger once the texture is ready
  101568. * @param onError defines the callback to trigger in case of error
  101569. */
  101570. TGATextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  101571. throw ".env not supported in Cube.";
  101572. };
  101573. /**
  101574. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  101575. * @param data contains the texture data
  101576. * @param texture defines the BabylonJS internal texture
  101577. * @param callback defines the method to call once ready to upload
  101578. */
  101579. TGATextureLoader.prototype.loadData = function (data, texture, callback) {
  101580. var uintData = new Uint8Array(data);
  101581. var header = BABYLON.TGATools.GetTGAHeader(uintData);
  101582. callback(header.width, header.height, texture.generateMipMaps, false, function () {
  101583. BABYLON.TGATools.UploadContent(texture, uintData);
  101584. });
  101585. };
  101586. return TGATextureLoader;
  101587. }());
  101588. // Register the loader.
  101589. BABYLON.Engine._TextureLoaders.push(new TGATextureLoader());
  101590. })(BABYLON || (BABYLON = {}));
  101591. //# sourceMappingURL=babylon.tgaTextureLoader.js.map
  101592. var BABYLON;
  101593. (function (BABYLON) {
  101594. /**
  101595. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  101596. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  101597. */
  101598. var KhronosTextureContainer = /** @class */ (function () {
  101599. /**
  101600. * Creates a new KhronosTextureContainer
  101601. * @param arrayBuffer contents of the KTX container file
  101602. * @param facesExpected should be either 1 or 6, based whether a cube texture or or
  101603. * @param threeDExpected provision for indicating that data should be a 3D texture, not implemented
  101604. * @param textureArrayExpected provision for indicating that data should be a texture array, not implemented
  101605. */
  101606. function KhronosTextureContainer(
  101607. /** contents of the KTX container file */
  101608. arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  101609. this.arrayBuffer = arrayBuffer;
  101610. /**
  101611. * If the container has been made invalid (eg. constructor failed to correctly load array buffer)
  101612. */
  101613. this.isInvalid = false;
  101614. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  101615. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  101616. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  101617. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  101618. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  101619. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  101620. this.isInvalid = true;
  101621. BABYLON.Tools.Error("texture missing KTX identifier");
  101622. return;
  101623. }
  101624. // load the reset of the header in native 32 bit uint
  101625. var dataSize = Uint32Array.BYTES_PER_ELEMENT;
  101626. var headerDataView = new DataView(this.arrayBuffer, 12, 13 * dataSize);
  101627. var endianness = headerDataView.getUint32(0, true);
  101628. var littleEndian = endianness === 0x04030201;
  101629. this.glType = headerDataView.getUint32(1 * dataSize, littleEndian); // must be 0 for compressed textures
  101630. this.glTypeSize = headerDataView.getUint32(2 * dataSize, littleEndian); // must be 1 for compressed textures
  101631. this.glFormat = headerDataView.getUint32(3 * dataSize, littleEndian); // must be 0 for compressed textures
  101632. this.glInternalFormat = headerDataView.getUint32(4 * dataSize, littleEndian); // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  101633. this.glBaseInternalFormat = headerDataView.getUint32(5 * dataSize, littleEndian); // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  101634. this.pixelWidth = headerDataView.getUint32(6 * dataSize, littleEndian); // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  101635. this.pixelHeight = headerDataView.getUint32(7 * dataSize, littleEndian); // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  101636. this.pixelDepth = headerDataView.getUint32(8 * dataSize, littleEndian); // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  101637. this.numberOfArrayElements = headerDataView.getUint32(9 * dataSize, littleEndian); // used for texture arrays
  101638. this.numberOfFaces = headerDataView.getUint32(10 * dataSize, littleEndian); // used for cubemap textures, should either be 1 or 6
  101639. this.numberOfMipmapLevels = headerDataView.getUint32(11 * dataSize, littleEndian); // number of levels; disregard possibility of 0 for compressed textures
  101640. this.bytesOfKeyValueData = headerDataView.getUint32(12 * dataSize, littleEndian); // the amount of space after the header for meta-data
  101641. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  101642. if (this.glType !== 0) {
  101643. BABYLON.Tools.Error("only compressed formats currently supported");
  101644. return;
  101645. }
  101646. else {
  101647. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  101648. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  101649. }
  101650. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  101651. BABYLON.Tools.Error("only 2D textures currently supported");
  101652. return;
  101653. }
  101654. if (this.numberOfArrayElements !== 0) {
  101655. BABYLON.Tools.Error("texture arrays not currently supported");
  101656. return;
  101657. }
  101658. if (this.numberOfFaces !== facesExpected) {
  101659. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  101660. return;
  101661. }
  101662. // we now have a completely validated file, so could use existence of loadType as success
  101663. // would need to make this more elaborate & adjust checks above to support more than one load type
  101664. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  101665. }
  101666. /**
  101667. * Uploads KTX content to a Babylon Texture.
  101668. * It is assumed that the texture has already been created & is currently bound
  101669. * @hidden
  101670. */
  101671. KhronosTextureContainer.prototype.uploadLevels = function (texture, loadMipmaps) {
  101672. switch (this.loadType) {
  101673. case KhronosTextureContainer.COMPRESSED_2D:
  101674. this._upload2DCompressedLevels(texture, loadMipmaps);
  101675. break;
  101676. case KhronosTextureContainer.TEX_2D:
  101677. case KhronosTextureContainer.COMPRESSED_3D:
  101678. case KhronosTextureContainer.TEX_3D:
  101679. }
  101680. };
  101681. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (texture, loadMipmaps) {
  101682. // initialize width & height for level 1
  101683. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  101684. var width = this.pixelWidth;
  101685. var height = this.pixelHeight;
  101686. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  101687. for (var level = 0; level < mipmapCount; level++) {
  101688. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  101689. dataOffset += 4; //image data starts from next multiple of 4 offset. Each face refers to same imagesize field above.
  101690. for (var face = 0; face < this.numberOfFaces; face++) {
  101691. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset, imageSize);
  101692. var engine = texture.getEngine();
  101693. engine._uploadCompressedDataToTextureDirectly(texture, this.glInternalFormat, width, height, byteArray, face, level);
  101694. dataOffset += imageSize; // add size of the image for the next face/mipmap
  101695. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  101696. }
  101697. width = Math.max(1.0, width * 0.5);
  101698. height = Math.max(1.0, height * 0.5);
  101699. }
  101700. };
  101701. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  101702. // load types
  101703. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  101704. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  101705. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  101706. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  101707. return KhronosTextureContainer;
  101708. }());
  101709. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  101710. })(BABYLON || (BABYLON = {}));
  101711. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  101712. var BABYLON;
  101713. (function (BABYLON) {
  101714. /**
  101715. * Implementation of the KTX Texture Loader.
  101716. */
  101717. var KTXTextureLoader = /** @class */ (function () {
  101718. function KTXTextureLoader() {
  101719. /**
  101720. * Defines wether the loader supports cascade loading the different faces.
  101721. */
  101722. this.supportCascades = false;
  101723. }
  101724. /**
  101725. * This returns if the loader support the current file information.
  101726. * @param extension defines the file extension of the file being loaded
  101727. * @param textureFormatInUse defines the current compressed format in use iun the engine
  101728. * @param fallback defines the fallback internal texture if any
  101729. * @param isBase64 defines whether the texture is encoded as a base64
  101730. * @param isBuffer defines whether the texture data are stored as a buffer
  101731. * @returns true if the loader can load the specified file
  101732. */
  101733. KTXTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  101734. if (textureFormatInUse && !isBase64 && !fallback && !isBuffer) {
  101735. return true;
  101736. }
  101737. return false;
  101738. };
  101739. /**
  101740. * Transform the url before loading if required.
  101741. * @param rootUrl the url of the texture
  101742. * @param textureFormatInUse defines the current compressed format in use iun the engine
  101743. * @returns the transformed texture
  101744. */
  101745. KTXTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  101746. var lastDot = rootUrl.lastIndexOf('.');
  101747. if (lastDot != -1 && rootUrl.substring(lastDot + 1) == "ktx") {
  101748. // Already transformed
  101749. return rootUrl;
  101750. }
  101751. return (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + textureFormatInUse;
  101752. };
  101753. /**
  101754. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  101755. * @param rootUrl the url of the texture
  101756. * @param textureFormatInUse defines the current compressed format in use iun the engine
  101757. * @returns the fallback texture
  101758. */
  101759. KTXTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  101760. // remove the format appended to the rootUrl in the original createCubeTexture call.
  101761. var exp = new RegExp("" + textureFormatInUse + "$");
  101762. return rootUrl.replace(exp, "");
  101763. };
  101764. /**
  101765. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  101766. * @param data contains the texture data
  101767. * @param texture defines the BabylonJS internal texture
  101768. * @param createPolynomials will be true if polynomials have been requested
  101769. * @param onLoad defines the callback to trigger once the texture is ready
  101770. * @param onError defines the callback to trigger in case of error
  101771. */
  101772. KTXTextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  101773. if (Array.isArray(data)) {
  101774. return;
  101775. }
  101776. // Need to invert vScale as invertY via UNPACK_FLIP_Y_WEBGL is not supported by compressed texture
  101777. texture._invertVScale = !texture.invertY;
  101778. var engine = texture.getEngine();
  101779. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  101780. var loadMipmap = ktx.numberOfMipmapLevels > 1 && texture.generateMipMaps;
  101781. engine._unpackFlipY(true);
  101782. ktx.uploadLevels(texture, texture.generateMipMaps);
  101783. texture.width = ktx.pixelWidth;
  101784. texture.height = ktx.pixelHeight;
  101785. engine._setCubeMapTextureParams(loadMipmap);
  101786. texture.isReady = true;
  101787. };
  101788. /**
  101789. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  101790. * @param data contains the texture data
  101791. * @param texture defines the BabylonJS internal texture
  101792. * @param callback defines the method to call once ready to upload
  101793. */
  101794. KTXTextureLoader.prototype.loadData = function (data, texture, callback) {
  101795. // Need to invert vScale as invertY via UNPACK_FLIP_Y_WEBGL is not supported by compressed texture
  101796. texture._invertVScale = !texture.invertY;
  101797. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  101798. callback(ktx.pixelWidth, ktx.pixelHeight, false, true, function () {
  101799. ktx.uploadLevels(texture, texture.generateMipMaps);
  101800. }, ktx.isInvalid);
  101801. };
  101802. return KTXTextureLoader;
  101803. }());
  101804. // Register the loader.
  101805. BABYLON.Engine._TextureLoaders.unshift(new KTXTextureLoader());
  101806. })(BABYLON || (BABYLON = {}));
  101807. //# sourceMappingURL=babylon.ktxTextureLoader.js.map
  101808. var BABYLON;
  101809. (function (BABYLON) {
  101810. /**
  101811. * Sets of helpers addressing the serialization and deserialization of environment texture
  101812. * stored in a BabylonJS env file.
  101813. * Those files are usually stored as .env files.
  101814. */
  101815. var EnvironmentTextureTools = /** @class */ (function () {
  101816. function EnvironmentTextureTools() {
  101817. }
  101818. /**
  101819. * Gets the environment info from an env file.
  101820. * @param data The array buffer containing the .env bytes.
  101821. * @returns the environment file info (the json header) if successfully parsed.
  101822. */
  101823. EnvironmentTextureTools.GetEnvInfo = function (data) {
  101824. var dataView = new DataView(data);
  101825. var pos = 0;
  101826. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  101827. if (dataView.getUint8(pos++) !== EnvironmentTextureTools._MagicBytes[i]) {
  101828. BABYLON.Tools.Error('Not a babylon environment map');
  101829. return null;
  101830. }
  101831. }
  101832. // Read json manifest - collect characters up to null terminator
  101833. var manifestString = '';
  101834. var charCode = 0x00;
  101835. while ((charCode = dataView.getUint8(pos++))) {
  101836. manifestString += String.fromCharCode(charCode);
  101837. }
  101838. var manifest = JSON.parse(manifestString);
  101839. if (manifest.specular) {
  101840. // Extend the header with the position of the payload.
  101841. manifest.specular.specularDataPosition = pos;
  101842. // Fallback to 0.8 exactly if lodGenerationScale is not defined for backward compatibility.
  101843. manifest.specular.lodGenerationScale = manifest.specular.lodGenerationScale || 0.8;
  101844. }
  101845. return manifest;
  101846. };
  101847. /**
  101848. * Creates an environment texture from a loaded cube texture.
  101849. * @param texture defines the cube texture to convert in env file
  101850. * @return a promise containing the environment data if succesfull.
  101851. */
  101852. EnvironmentTextureTools.CreateEnvTextureAsync = function (texture) {
  101853. var _this = this;
  101854. var internalTexture = texture.getInternalTexture();
  101855. if (!internalTexture) {
  101856. return Promise.reject("The cube texture is invalid.");
  101857. }
  101858. if (!texture._prefiltered) {
  101859. return Promise.reject("The cube texture is invalid (not prefiltered).");
  101860. }
  101861. var engine = internalTexture.getEngine();
  101862. if (engine && engine.premultipliedAlpha) {
  101863. return Promise.reject("Env texture can only be created when the engine is created with the premultipliedAlpha option set to false.");
  101864. }
  101865. if (texture.textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  101866. return Promise.reject("The cube texture should allow HDR (Full Float or Half Float).");
  101867. }
  101868. var canvas = engine.getRenderingCanvas();
  101869. if (!canvas) {
  101870. return Promise.reject("Env texture can only be created when the engine is associated to a canvas.");
  101871. }
  101872. var textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  101873. if (!engine.getCaps().textureFloatRender) {
  101874. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  101875. if (!engine.getCaps().textureHalfFloatRender) {
  101876. return Promise.reject("Env texture can only be created when the browser supports half float or full float rendering.");
  101877. }
  101878. }
  101879. var cubeWidth = internalTexture.width;
  101880. var hostingScene = new BABYLON.Scene(engine);
  101881. var specularTextures = {};
  101882. var promises = [];
  101883. // Read and collect all mipmaps data from the cube.
  101884. var mipmapsCount = BABYLON.Scalar.Log2(internalTexture.width);
  101885. mipmapsCount = Math.round(mipmapsCount);
  101886. var _loop_1 = function (i) {
  101887. var faceWidth = Math.pow(2, mipmapsCount - i);
  101888. var _loop_2 = function (face) {
  101889. var data = texture.readPixels(face, i);
  101890. // Creates a temp texture with the face data.
  101891. var tempTexture = engine.createRawTexture(data, faceWidth, faceWidth, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, textureType);
  101892. // And rgbdEncode them.
  101893. var promise = new Promise(function (resolve, reject) {
  101894. 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);
  101895. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  101896. rgbdPostProcess.onApply = function (effect) {
  101897. effect._bindTexture("textureSampler", tempTexture);
  101898. };
  101899. // As the process needs to happen on the main canvas, keep track of the current size
  101900. var currentW = engine.getRenderWidth();
  101901. var currentH = engine.getRenderHeight();
  101902. // Set the desired size for the texture
  101903. engine.setSize(faceWidth, faceWidth);
  101904. hostingScene.postProcessManager.directRender([rgbdPostProcess], null);
  101905. // Reading datas from WebGL
  101906. BABYLON.Tools.ToBlob(canvas, function (blob) {
  101907. var fileReader = new FileReader();
  101908. fileReader.onload = function (event) {
  101909. var arrayBuffer = event.target.result;
  101910. specularTextures[i * 6 + face] = arrayBuffer;
  101911. resolve();
  101912. };
  101913. fileReader.readAsArrayBuffer(blob);
  101914. });
  101915. // Reapply the previous canvas size
  101916. engine.setSize(currentW, currentH);
  101917. });
  101918. });
  101919. promises.push(promise);
  101920. };
  101921. // All faces of the cube.
  101922. for (var face = 0; face < 6; face++) {
  101923. _loop_2(face);
  101924. }
  101925. };
  101926. for (var i = 0; i <= mipmapsCount; i++) {
  101927. _loop_1(i);
  101928. }
  101929. // Once all the textures haves been collected as RGBD stored in PNGs
  101930. return Promise.all(promises).then(function () {
  101931. // We can delete the hosting scene keeping track of all the creation objects
  101932. hostingScene.dispose();
  101933. // Creates the json header for the env texture
  101934. var info = {
  101935. version: 1,
  101936. width: cubeWidth,
  101937. irradiance: _this._CreateEnvTextureIrradiance(texture),
  101938. specular: {
  101939. mipmaps: [],
  101940. lodGenerationScale: texture.lodGenerationScale
  101941. }
  101942. };
  101943. // Sets the specular image data information
  101944. var position = 0;
  101945. for (var i = 0; i <= mipmapsCount; i++) {
  101946. for (var face = 0; face < 6; face++) {
  101947. var byteLength = specularTextures[i * 6 + face].byteLength;
  101948. info.specular.mipmaps.push({
  101949. length: byteLength,
  101950. position: position
  101951. });
  101952. position += byteLength;
  101953. }
  101954. }
  101955. // Encode the JSON as an array buffer
  101956. var infoString = JSON.stringify(info);
  101957. var infoBuffer = new ArrayBuffer(infoString.length + 1);
  101958. var infoView = new Uint8Array(infoBuffer); // Limited to ascii subset matching unicode.
  101959. for (var i = 0, strLen = infoString.length; i < strLen; i++) {
  101960. infoView[i] = infoString.charCodeAt(i);
  101961. }
  101962. // Ends up with a null terminator for easier parsing
  101963. infoView[infoString.length] = 0x00;
  101964. // Computes the final required size and creates the storage
  101965. var totalSize = EnvironmentTextureTools._MagicBytes.length + position + infoBuffer.byteLength;
  101966. var finalBuffer = new ArrayBuffer(totalSize);
  101967. var finalBufferView = new Uint8Array(finalBuffer);
  101968. var dataView = new DataView(finalBuffer);
  101969. // Copy the magic bytes identifying the file in
  101970. var pos = 0;
  101971. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  101972. dataView.setUint8(pos++, EnvironmentTextureTools._MagicBytes[i]);
  101973. }
  101974. // Add the json info
  101975. finalBufferView.set(new Uint8Array(infoBuffer), pos);
  101976. pos += infoBuffer.byteLength;
  101977. // Finally inserts the texture data
  101978. for (var i = 0; i <= mipmapsCount; i++) {
  101979. for (var face = 0; face < 6; face++) {
  101980. var dataBuffer = specularTextures[i * 6 + face];
  101981. finalBufferView.set(new Uint8Array(dataBuffer), pos);
  101982. pos += dataBuffer.byteLength;
  101983. }
  101984. }
  101985. // Voila
  101986. return finalBuffer;
  101987. });
  101988. };
  101989. /**
  101990. * Creates a JSON representation of the spherical data.
  101991. * @param texture defines the texture containing the polynomials
  101992. * @return the JSON representation of the spherical info
  101993. */
  101994. EnvironmentTextureTools._CreateEnvTextureIrradiance = function (texture) {
  101995. var polynmials = texture.sphericalPolynomial;
  101996. if (polynmials == null) {
  101997. return null;
  101998. }
  101999. return {
  102000. x: [polynmials.x.x, polynmials.x.y, polynmials.x.z],
  102001. y: [polynmials.y.x, polynmials.y.y, polynmials.y.z],
  102002. z: [polynmials.z.x, polynmials.z.y, polynmials.z.z],
  102003. xx: [polynmials.xx.x, polynmials.xx.y, polynmials.xx.z],
  102004. yy: [polynmials.yy.x, polynmials.yy.y, polynmials.yy.z],
  102005. zz: [polynmials.zz.x, polynmials.zz.y, polynmials.zz.z],
  102006. yz: [polynmials.yz.x, polynmials.yz.y, polynmials.yz.z],
  102007. zx: [polynmials.zx.x, polynmials.zx.y, polynmials.zx.z],
  102008. xy: [polynmials.xy.x, polynmials.xy.y, polynmials.xy.z]
  102009. };
  102010. };
  102011. /**
  102012. * Uploads the texture info contained in the env file to the GPU.
  102013. * @param texture defines the internal texture to upload to
  102014. * @param arrayBuffer defines the buffer cotaining the data to load
  102015. * @param info defines the texture info retrieved through the GetEnvInfo method
  102016. * @returns a promise
  102017. */
  102018. EnvironmentTextureTools.UploadEnvLevelsAsync = function (texture, arrayBuffer, info) {
  102019. if (info.version !== 1) {
  102020. throw new Error("Unsupported babylon environment map version \"" + info.version + "\"");
  102021. }
  102022. var specularInfo = info.specular;
  102023. if (!specularInfo) {
  102024. // Nothing else parsed so far
  102025. return Promise.resolve();
  102026. }
  102027. // Double checks the enclosed info
  102028. var mipmapsCount = BABYLON.Scalar.Log2(info.width);
  102029. mipmapsCount = Math.round(mipmapsCount) + 1;
  102030. if (specularInfo.mipmaps.length !== 6 * mipmapsCount) {
  102031. throw new Error("Unsupported specular mipmaps number \"" + specularInfo.mipmaps.length + "\"");
  102032. }
  102033. texture._lodGenerationScale = specularInfo.lodGenerationScale;
  102034. var imageData = new Array(mipmapsCount);
  102035. for (var i = 0; i < mipmapsCount; i++) {
  102036. imageData[i] = new Array(6);
  102037. for (var face = 0; face < 6; face++) {
  102038. var imageInfo = specularInfo.mipmaps[i * 6 + face];
  102039. imageData[i][face] = new Uint8Array(arrayBuffer, specularInfo.specularDataPosition + imageInfo.position, imageInfo.length);
  102040. }
  102041. }
  102042. return EnvironmentTextureTools.UploadLevelsAsync(texture, imageData);
  102043. };
  102044. /**
  102045. * Uploads the levels of image data to the GPU.
  102046. * @param texture defines the internal texture to upload to
  102047. * @param imageData defines the array buffer views of image data [mipmap][face]
  102048. * @returns a promise
  102049. */
  102050. EnvironmentTextureTools.UploadLevelsAsync = function (texture, imageData) {
  102051. if (!BABYLON.Tools.IsExponentOfTwo(texture.width)) {
  102052. throw new Error("Texture size must be a power of two");
  102053. }
  102054. var mipmapsCount = Math.round(BABYLON.Scalar.Log2(texture.width)) + 1;
  102055. // Gets everything ready.
  102056. var engine = texture.getEngine();
  102057. var expandTexture = false;
  102058. var generateNonLODTextures = false;
  102059. var rgbdPostProcess = null;
  102060. var cubeRtt = null;
  102061. var lodTextures = null;
  102062. var caps = engine.getCaps();
  102063. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  102064. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  102065. texture.generateMipMaps = true;
  102066. engine.updateTextureSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE, texture);
  102067. // Add extra process if texture lod is not supported
  102068. if (!caps.textureLOD) {
  102069. expandTexture = false;
  102070. generateNonLODTextures = true;
  102071. lodTextures = {};
  102072. }
  102073. // in webgl 1 there are no ways to either render or copy lod level information for float textures.
  102074. else if (engine.webGLVersion < 2) {
  102075. expandTexture = false;
  102076. }
  102077. // If half float available we can uncompress the texture
  102078. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  102079. expandTexture = true;
  102080. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  102081. }
  102082. // If full float available we can uncompress the texture
  102083. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  102084. expandTexture = true;
  102085. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  102086. }
  102087. // Expand the texture if possible
  102088. if (expandTexture) {
  102089. // Simply run through the decode PP
  102090. rgbdPostProcess = new BABYLON.PostProcess("rgbdDecode", "rgbdDecode", null, null, 1, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, engine, false, undefined, texture.type, undefined, null, false);
  102091. texture._isRGBD = false;
  102092. texture.invertY = false;
  102093. cubeRtt = engine.createRenderTargetCubeTexture(texture.width, {
  102094. generateDepthBuffer: false,
  102095. generateMipMaps: true,
  102096. generateStencilBuffer: false,
  102097. samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE,
  102098. type: texture.type,
  102099. format: BABYLON.Engine.TEXTUREFORMAT_RGBA
  102100. });
  102101. }
  102102. else {
  102103. texture._isRGBD = true;
  102104. texture.invertY = true;
  102105. // In case of missing support, applies the same patch than DDS files.
  102106. if (generateNonLODTextures) {
  102107. var mipSlices = 3;
  102108. var scale = texture._lodGenerationScale;
  102109. var offset = texture._lodGenerationOffset;
  102110. for (var i = 0; i < mipSlices; i++) {
  102111. //compute LOD from even spacing in smoothness (matching shader calculation)
  102112. var smoothness = i / (mipSlices - 1);
  102113. var roughness = 1 - smoothness;
  102114. var minLODIndex = offset; // roughness = 0
  102115. var maxLODIndex = (mipmapsCount - 1) * scale + offset; // roughness = 1 (mipmaps start from 0)
  102116. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  102117. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  102118. var glTextureFromLod = new BABYLON.InternalTexture(engine, BABYLON.InternalTexture.DATASOURCE_TEMP);
  102119. glTextureFromLod.isCube = true;
  102120. glTextureFromLod.invertY = true;
  102121. glTextureFromLod.generateMipMaps = false;
  102122. engine.updateTextureSamplingMode(BABYLON.Texture.LINEAR_LINEAR, glTextureFromLod);
  102123. // Wrap in a base texture for easy binding.
  102124. var lodTexture = new BABYLON.BaseTexture(null);
  102125. lodTexture.isCube = true;
  102126. lodTexture._texture = glTextureFromLod;
  102127. lodTextures[mipmapIndex] = lodTexture;
  102128. switch (i) {
  102129. case 0:
  102130. texture._lodTextureLow = lodTexture;
  102131. break;
  102132. case 1:
  102133. texture._lodTextureMid = lodTexture;
  102134. break;
  102135. case 2:
  102136. texture._lodTextureHigh = lodTexture;
  102137. break;
  102138. }
  102139. }
  102140. }
  102141. }
  102142. var promises = [];
  102143. var _loop_3 = function (i) {
  102144. var _loop_4 = function (face) {
  102145. // Constructs an image element from image data
  102146. var bytes = imageData[i][face];
  102147. var blob = new Blob([bytes], { type: 'image/png' });
  102148. var url = URL.createObjectURL(blob);
  102149. var image = new Image();
  102150. image.src = url;
  102151. // Enqueue promise to upload to the texture.
  102152. var promise = new Promise(function (resolve, reject) {
  102153. image.onload = function () {
  102154. if (expandTexture) {
  102155. var tempTexture_1 = engine.createTexture(null, true, true, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, function (message) {
  102156. reject(message);
  102157. }, image);
  102158. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  102159. // Uncompress the data to a RTT
  102160. rgbdPostProcess.onApply = function (effect) {
  102161. effect._bindTexture("textureSampler", tempTexture_1);
  102162. effect.setFloat2("scale", 1, 1);
  102163. };
  102164. engine.scenes[0].postProcessManager.directRender([rgbdPostProcess], cubeRtt, true, face, i);
  102165. // Cleanup
  102166. engine.restoreDefaultFramebuffer();
  102167. tempTexture_1.dispose();
  102168. window.URL.revokeObjectURL(url);
  102169. resolve();
  102170. });
  102171. }
  102172. else {
  102173. engine._uploadImageToTexture(texture, image, face, i);
  102174. // Upload the face to the non lod texture support
  102175. if (generateNonLODTextures) {
  102176. var lodTexture = lodTextures[i];
  102177. if (lodTexture) {
  102178. engine._uploadImageToTexture(lodTexture._texture, image, face, 0);
  102179. }
  102180. }
  102181. resolve();
  102182. }
  102183. };
  102184. image.onerror = function (error) {
  102185. reject(error);
  102186. };
  102187. });
  102188. promises.push(promise);
  102189. };
  102190. // All faces
  102191. for (var face = 0; face < 6; face++) {
  102192. _loop_4(face);
  102193. }
  102194. };
  102195. // All mipmaps up to provided number of images
  102196. for (var i = 0; i < imageData.length; i++) {
  102197. _loop_3(i);
  102198. }
  102199. // Fill remaining mipmaps with black textures.
  102200. if (imageData.length < mipmapsCount) {
  102201. var data = void 0;
  102202. var size = Math.pow(2, mipmapsCount - 1 - imageData.length);
  102203. var dataLength = size * size * 4;
  102204. switch (texture.type) {
  102205. case BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT: {
  102206. data = new Uint8Array(dataLength);
  102207. break;
  102208. }
  102209. case BABYLON.Engine.TEXTURETYPE_HALF_FLOAT: {
  102210. data = new Uint16Array(dataLength);
  102211. break;
  102212. }
  102213. case BABYLON.Engine.TEXTURETYPE_FLOAT: {
  102214. data = new Float32Array(dataLength);
  102215. break;
  102216. }
  102217. }
  102218. for (var i = imageData.length; i < mipmapsCount; i++) {
  102219. for (var face = 0; face < 6; face++) {
  102220. engine._uploadArrayBufferViewToTexture(texture, data, face, i);
  102221. }
  102222. }
  102223. }
  102224. // Once all done, finishes the cleanup and return
  102225. return Promise.all(promises).then(function () {
  102226. // Release temp RTT.
  102227. if (cubeRtt) {
  102228. engine._releaseFramebufferObjects(cubeRtt);
  102229. cubeRtt._swapAndDie(texture);
  102230. }
  102231. // Release temp Post Process.
  102232. if (rgbdPostProcess) {
  102233. rgbdPostProcess.dispose();
  102234. }
  102235. // Flag internal texture as ready in case they are in use.
  102236. if (generateNonLODTextures) {
  102237. if (texture._lodTextureHigh && texture._lodTextureHigh._texture) {
  102238. texture._lodTextureHigh._texture.isReady = true;
  102239. }
  102240. if (texture._lodTextureMid && texture._lodTextureMid._texture) {
  102241. texture._lodTextureMid._texture.isReady = true;
  102242. }
  102243. if (texture._lodTextureLow && texture._lodTextureLow._texture) {
  102244. texture._lodTextureLow._texture.isReady = true;
  102245. }
  102246. }
  102247. });
  102248. };
  102249. /**
  102250. * Uploads spherical polynomials information to the texture.
  102251. * @param texture defines the texture we are trying to upload the information to
  102252. * @param info defines the environment texture info retrieved through the GetEnvInfo method
  102253. */
  102254. EnvironmentTextureTools.UploadEnvSpherical = function (texture, info) {
  102255. if (info.version !== 1) {
  102256. BABYLON.Tools.Warn('Unsupported babylon environment map version "' + info.version + '"');
  102257. }
  102258. var irradianceInfo = info.irradiance;
  102259. if (!irradianceInfo) {
  102260. return;
  102261. }
  102262. var sp = new BABYLON.SphericalPolynomial();
  102263. BABYLON.Vector3.FromArrayToRef(irradianceInfo.x, 0, sp.x);
  102264. BABYLON.Vector3.FromArrayToRef(irradianceInfo.y, 0, sp.y);
  102265. BABYLON.Vector3.FromArrayToRef(irradianceInfo.z, 0, sp.z);
  102266. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xx, 0, sp.xx);
  102267. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yy, 0, sp.yy);
  102268. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zz, 0, sp.zz);
  102269. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yz, 0, sp.yz);
  102270. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zx, 0, sp.zx);
  102271. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xy, 0, sp.xy);
  102272. texture._sphericalPolynomial = sp;
  102273. };
  102274. /**
  102275. * Magic number identifying the env file.
  102276. */
  102277. EnvironmentTextureTools._MagicBytes = [0x86, 0x16, 0x87, 0x96, 0xf6, 0xd6, 0x96, 0x36];
  102278. return EnvironmentTextureTools;
  102279. }());
  102280. BABYLON.EnvironmentTextureTools = EnvironmentTextureTools;
  102281. })(BABYLON || (BABYLON = {}));
  102282. //# sourceMappingURL=babylon.environmentTextureTools.js.map
  102283. var BABYLON;
  102284. (function (BABYLON) {
  102285. /**
  102286. * Implementation of the ENV Texture Loader.
  102287. */
  102288. var ENVTextureLoader = /** @class */ (function () {
  102289. function ENVTextureLoader() {
  102290. /**
  102291. * Defines wether the loader supports cascade loading the different faces.
  102292. */
  102293. this.supportCascades = false;
  102294. }
  102295. /**
  102296. * This returns if the loader support the current file information.
  102297. * @param extension defines the file extension of the file being loaded
  102298. * @param textureFormatInUse defines the current compressed format in use iun the engine
  102299. * @param fallback defines the fallback internal texture if any
  102300. * @param isBase64 defines whether the texture is encoded as a base64
  102301. * @param isBuffer defines whether the texture data are stored as a buffer
  102302. * @returns true if the loader can load the specified file
  102303. */
  102304. ENVTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  102305. return extension.indexOf(".env") === 0;
  102306. };
  102307. /**
  102308. * Transform the url before loading if required.
  102309. * @param rootUrl the url of the texture
  102310. * @param textureFormatInUse defines the current compressed format in use iun the engine
  102311. * @returns the transformed texture
  102312. */
  102313. ENVTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  102314. return rootUrl;
  102315. };
  102316. /**
  102317. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  102318. * @param rootUrl the url of the texture
  102319. * @param textureFormatInUse defines the current compressed format in use iun the engine
  102320. * @returns the fallback texture
  102321. */
  102322. ENVTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  102323. return null;
  102324. };
  102325. /**
  102326. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  102327. * @param data contains the texture data
  102328. * @param texture defines the BabylonJS internal texture
  102329. * @param createPolynomials will be true if polynomials have been requested
  102330. * @param onLoad defines the callback to trigger once the texture is ready
  102331. * @param onError defines the callback to trigger in case of error
  102332. */
  102333. ENVTextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  102334. if (Array.isArray(data)) {
  102335. return;
  102336. }
  102337. data = data;
  102338. var info = BABYLON.EnvironmentTextureTools.GetEnvInfo(data);
  102339. if (info) {
  102340. texture.width = info.width;
  102341. texture.height = info.width;
  102342. BABYLON.EnvironmentTextureTools.UploadEnvSpherical(texture, info);
  102343. BABYLON.EnvironmentTextureTools.UploadEnvLevelsAsync(texture, data, info).then(function () {
  102344. texture.isReady = true;
  102345. if (onLoad) {
  102346. onLoad();
  102347. }
  102348. });
  102349. }
  102350. else if (onError) {
  102351. onError("Can not parse the environment file", null);
  102352. }
  102353. };
  102354. /**
  102355. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  102356. * @param data contains the texture data
  102357. * @param texture defines the BabylonJS internal texture
  102358. * @param callback defines the method to call once ready to upload
  102359. */
  102360. ENVTextureLoader.prototype.loadData = function (data, texture, callback) {
  102361. throw ".env not supported in 2d.";
  102362. };
  102363. return ENVTextureLoader;
  102364. }());
  102365. // Register the loader.
  102366. BABYLON.Engine._TextureLoaders.push(new ENVTextureLoader());
  102367. })(BABYLON || (BABYLON = {}));
  102368. //# sourceMappingURL=babylon.envTextureLoader.js.map
  102369. var BABYLON;
  102370. (function (BABYLON) {
  102371. /**
  102372. * Renders a layer on top of an existing scene
  102373. */
  102374. var UtilityLayerRenderer = /** @class */ (function () {
  102375. /**
  102376. * Instantiates a UtilityLayerRenderer
  102377. * @param originalScene the original scene that will be rendered on top of
  102378. * @param handleEvents boolean indicating if the utility layer should handle events
  102379. */
  102380. function UtilityLayerRenderer(
  102381. /** the original scene that will be rendered on top of */
  102382. originalScene, handleEvents) {
  102383. if (handleEvents === void 0) { handleEvents = true; }
  102384. var _this = this;
  102385. this.originalScene = originalScene;
  102386. this._pointerCaptures = {};
  102387. this._lastPointerEvents = {};
  102388. /**
  102389. * If the picking should be done on the utility layer prior to the actual scene (Default: true)
  102390. */
  102391. this.pickUtilitySceneFirst = true;
  102392. /**
  102393. * If the utility layer should automatically be rendered on top of existing scene
  102394. */
  102395. this.shouldRender = true;
  102396. /**
  102397. * If set to true, only pointer down onPointerObservable events will be blocked when picking is occluded by original scene
  102398. */
  102399. this.onlyCheckPointerDownEvents = true;
  102400. /**
  102401. * If set to false, only pointerUp, pointerDown and pointerMove will be sent to the utilityLayerScene (false by default)
  102402. */
  102403. this.processAllEvents = false;
  102404. /**
  102405. * Observable raised when the pointer move from the utility layer scene to the main scene
  102406. */
  102407. this.onPointerOutObservable = new BABYLON.Observable();
  102408. // Create scene which will be rendered in the foreground and remove it from being referenced by engine to avoid interfering with existing app
  102409. this.utilityLayerScene = new BABYLON.Scene(originalScene.getEngine());
  102410. this.utilityLayerScene.useRightHandedSystem = originalScene.useRightHandedSystem;
  102411. this.utilityLayerScene._allowPostProcessClearColor = false;
  102412. originalScene.getEngine().scenes.pop();
  102413. // Detach controls on utility scene, events will be fired by logic below to handle picking priority
  102414. this.utilityLayerScene.detachControl();
  102415. if (handleEvents) {
  102416. this._originalPointerObserver = originalScene.onPrePointerObservable.add(function (prePointerInfo, eventState) {
  102417. if (!_this.utilityLayerScene.activeCamera) {
  102418. return;
  102419. }
  102420. if (!_this.processAllEvents) {
  102421. if (prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERMOVE
  102422. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERUP
  102423. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERDOWN) {
  102424. return;
  102425. }
  102426. }
  102427. var pointerEvent = (prePointerInfo.event);
  102428. if (originalScene.isPointerCaptured(pointerEvent.pointerId)) {
  102429. _this._pointerCaptures[pointerEvent.pointerId] = false;
  102430. return;
  102431. }
  102432. var utilityScenePick = prePointerInfo.ray ? _this.utilityLayerScene.pickWithRay(prePointerInfo.ray) : _this.utilityLayerScene.pick(originalScene.pointerX, originalScene.pointerY);
  102433. if (!prePointerInfo.ray && utilityScenePick) {
  102434. prePointerInfo.ray = utilityScenePick.ray;
  102435. }
  102436. // always fire the prepointer oversvable
  102437. _this.utilityLayerScene.onPrePointerObservable.notifyObservers(prePointerInfo);
  102438. // allow every non pointer down event to flow to the utility layer
  102439. if (_this.onlyCheckPointerDownEvents && prePointerInfo.type != BABYLON.PointerEventTypes.POINTERDOWN) {
  102440. if (!prePointerInfo.skipOnPointerObservable) {
  102441. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  102442. }
  102443. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent.pointerId]) {
  102444. _this._pointerCaptures[pointerEvent.pointerId] = false;
  102445. }
  102446. return;
  102447. }
  102448. if (_this.utilityLayerScene.autoClearDepthAndStencil || _this.pickUtilitySceneFirst) {
  102449. // If this layer is an overlay, check if this layer was hit and if so, skip pointer events for the main scene
  102450. if (utilityScenePick && utilityScenePick.hit) {
  102451. if (!prePointerInfo.skipOnPointerObservable) {
  102452. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  102453. }
  102454. prePointerInfo.skipOnPointerObservable = true;
  102455. }
  102456. }
  102457. else {
  102458. var originalScenePick = prePointerInfo.ray ? originalScene.pickWithRay(prePointerInfo.ray) : originalScene.pick(originalScene.pointerX, originalScene.pointerY);
  102459. var pointerEvent_1 = (prePointerInfo.event);
  102460. // If the layer can be occluded by the original scene, only fire pointer events to the first layer that hit they ray
  102461. if (originalScenePick && utilityScenePick) {
  102462. // No pick in utility scene
  102463. if (utilityScenePick.distance === 0 && originalScenePick.pickedMesh) {
  102464. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  102465. // We touched an utility mesh present in the main scene
  102466. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  102467. prePointerInfo.skipOnPointerObservable = true;
  102468. }
  102469. else if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  102470. _this._pointerCaptures[pointerEvent_1.pointerId] = true;
  102471. }
  102472. else if (_this._lastPointerEvents[pointerEvent_1.pointerId]) {
  102473. // We need to send a last pointerup to the utilityLayerScene to make sure animations can complete
  102474. _this.onPointerOutObservable.notifyObservers(pointerEvent_1.pointerId);
  102475. delete _this._lastPointerEvents[pointerEvent_1.pointerId];
  102476. }
  102477. }
  102478. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance < originalScenePick.distance || originalScenePick.distance === 0)) {
  102479. // We pick something in utility scene or the pick in utility is closer than the one in main scene
  102480. _this._notifyObservers(prePointerInfo, utilityScenePick, pointerEvent_1);
  102481. // If a previous utility layer set this, do not unset this
  102482. if (!prePointerInfo.skipOnPointerObservable) {
  102483. prePointerInfo.skipOnPointerObservable = utilityScenePick.distance > 0;
  102484. }
  102485. }
  102486. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance > originalScenePick.distance)) {
  102487. // We have a pick in both scenes but main is closer than utility
  102488. // We touched an utility mesh present in the main scene
  102489. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  102490. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  102491. prePointerInfo.skipOnPointerObservable = true;
  102492. }
  102493. else if (_this._lastPointerEvents[pointerEvent_1.pointerId]) {
  102494. // We need to send a last pointerup to the utilityLayerScene to make sure animations can complete
  102495. _this.onPointerOutObservable.notifyObservers(pointerEvent_1.pointerId);
  102496. delete _this._lastPointerEvents[pointerEvent_1.pointerId];
  102497. }
  102498. }
  102499. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent_1.pointerId]) {
  102500. _this._pointerCaptures[pointerEvent_1.pointerId] = false;
  102501. }
  102502. }
  102503. }
  102504. });
  102505. }
  102506. // Render directly on top of existing scene without clearing
  102507. this.utilityLayerScene.autoClear = false;
  102508. this._afterRenderObserver = this.originalScene.onAfterRenderObservable.add(function () {
  102509. if (_this.shouldRender) {
  102510. _this.render();
  102511. }
  102512. });
  102513. this._sceneDisposeObserver = this.originalScene.onDisposeObservable.add(function () {
  102514. _this.dispose();
  102515. });
  102516. this._updateCamera();
  102517. }
  102518. Object.defineProperty(UtilityLayerRenderer, "DefaultUtilityLayer", {
  102519. /**
  102520. * 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)
  102521. */
  102522. get: function () {
  102523. if (UtilityLayerRenderer._DefaultUtilityLayer == null) {
  102524. UtilityLayerRenderer._DefaultUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
  102525. UtilityLayerRenderer._DefaultUtilityLayer.originalScene.onDisposeObservable.addOnce(function () {
  102526. UtilityLayerRenderer._DefaultUtilityLayer = null;
  102527. });
  102528. }
  102529. return UtilityLayerRenderer._DefaultUtilityLayer;
  102530. },
  102531. enumerable: true,
  102532. configurable: true
  102533. });
  102534. Object.defineProperty(UtilityLayerRenderer, "DefaultKeepDepthUtilityLayer", {
  102535. /**
  102536. * 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)
  102537. */
  102538. get: function () {
  102539. if (UtilityLayerRenderer._DefaultKeepDepthUtilityLayer == null) {
  102540. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
  102541. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil = false;
  102542. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.originalScene.onDisposeObservable.addOnce(function () {
  102543. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null;
  102544. });
  102545. }
  102546. return UtilityLayerRenderer._DefaultKeepDepthUtilityLayer;
  102547. },
  102548. enumerable: true,
  102549. configurable: true
  102550. });
  102551. UtilityLayerRenderer.prototype._notifyObservers = function (prePointerInfo, pickInfo, pointerEvent) {
  102552. if (!prePointerInfo.skipOnPointerObservable) {
  102553. this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, pickInfo));
  102554. this._lastPointerEvents[pointerEvent.pointerId] = true;
  102555. }
  102556. };
  102557. /**
  102558. * Renders the utility layers scene on top of the original scene
  102559. */
  102560. UtilityLayerRenderer.prototype.render = function () {
  102561. this._updateCamera();
  102562. if (this.utilityLayerScene.activeCamera) {
  102563. // Set the camera's scene to utility layers scene
  102564. var oldScene = this.utilityLayerScene.activeCamera.getScene();
  102565. var camera = this.utilityLayerScene.activeCamera;
  102566. camera._scene = this.utilityLayerScene;
  102567. if (camera.leftCamera) {
  102568. camera.leftCamera._scene = this.utilityLayerScene;
  102569. }
  102570. if (camera.rightCamera) {
  102571. camera.rightCamera._scene = this.utilityLayerScene;
  102572. }
  102573. this.utilityLayerScene.render(false);
  102574. // Reset camera's scene back to original
  102575. camera._scene = oldScene;
  102576. if (camera.leftCamera) {
  102577. camera.leftCamera._scene = oldScene;
  102578. }
  102579. if (camera.rightCamera) {
  102580. camera.rightCamera._scene = oldScene;
  102581. }
  102582. }
  102583. };
  102584. /**
  102585. * Disposes of the renderer
  102586. */
  102587. UtilityLayerRenderer.prototype.dispose = function () {
  102588. this.onPointerOutObservable.clear();
  102589. if (this._afterRenderObserver) {
  102590. this.originalScene.onAfterRenderObservable.remove(this._afterRenderObserver);
  102591. }
  102592. if (this._sceneDisposeObserver) {
  102593. this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver);
  102594. }
  102595. if (this._originalPointerObserver) {
  102596. this.originalScene.onPrePointerObservable.remove(this._originalPointerObserver);
  102597. }
  102598. this.utilityLayerScene.dispose();
  102599. };
  102600. UtilityLayerRenderer.prototype._updateCamera = function () {
  102601. if (this.originalScene.activeCameras.length > 1) {
  102602. this.utilityLayerScene.activeCamera = this.originalScene.activeCameras[0];
  102603. }
  102604. else {
  102605. this.utilityLayerScene.activeCamera = this.originalScene.activeCamera;
  102606. }
  102607. };
  102608. UtilityLayerRenderer._DefaultUtilityLayer = null;
  102609. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null;
  102610. return UtilityLayerRenderer;
  102611. }());
  102612. BABYLON.UtilityLayerRenderer = UtilityLayerRenderer;
  102613. })(BABYLON || (BABYLON = {}));
  102614. //# sourceMappingURL=babylon.utilityLayerRenderer.js.map
  102615. //# sourceMappingURL=babylon.behavior.js.map
  102616. var BABYLON;
  102617. (function (BABYLON) {
  102618. /**
  102619. * A behavior that when attached to a mesh will allow the mesh to be dragged around the screen based on pointer events
  102620. */
  102621. var PointerDragBehavior = /** @class */ (function () {
  102622. /**
  102623. * Creates a pointer drag behavior that can be attached to a mesh
  102624. * @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)
  102625. */
  102626. function PointerDragBehavior(options) {
  102627. /**
  102628. * 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)
  102629. */
  102630. this.maxDragAngle = 0;
  102631. /**
  102632. * @hidden
  102633. */
  102634. this._useAlternatePickedPointAboveMaxDragAngle = false;
  102635. /**
  102636. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  102637. */
  102638. this.currentDraggingPointerID = -1;
  102639. /**
  102640. * If the behavior is currently in a dragging state
  102641. */
  102642. this.dragging = false;
  102643. /**
  102644. * 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)
  102645. */
  102646. this.dragDeltaRatio = 0.2;
  102647. /**
  102648. * If the drag plane orientation should be updated during the dragging (Default: true)
  102649. */
  102650. this.updateDragPlane = true;
  102651. // Debug mode will display drag planes to help visualize behavior
  102652. this._debugMode = false;
  102653. this._moving = false;
  102654. /**
  102655. * Fires each time the attached mesh is dragged with the pointer
  102656. * * delta between last drag position and current drag position in world space
  102657. * * dragDistance along the drag axis
  102658. * * dragPlaneNormal normal of the current drag plane used during the drag
  102659. * * dragPlanePoint in world space where the drag intersects the drag plane
  102660. */
  102661. this.onDragObservable = new BABYLON.Observable();
  102662. /**
  102663. * Fires each time a drag begins (eg. mouse down on mesh)
  102664. */
  102665. this.onDragStartObservable = new BABYLON.Observable();
  102666. /**
  102667. * Fires each time a drag ends (eg. mouse release after drag)
  102668. */
  102669. this.onDragEndObservable = new BABYLON.Observable();
  102670. /**
  102671. * If the attached mesh should be moved when dragged
  102672. */
  102673. this.moveAttached = true;
  102674. /**
  102675. * If the drag behavior will react to drag events (Default: true)
  102676. */
  102677. this.enabled = true;
  102678. /**
  102679. * If camera controls should be detached during the drag
  102680. */
  102681. this.detachCameraControls = true;
  102682. /**
  102683. * If set, the drag plane/axis will be rotated based on the attached mesh's world rotation (Default: true)
  102684. */
  102685. this.useObjectOrienationForDragging = true;
  102686. /**
  102687. * Predicate to determine if it is valid to move the object to a new position when it is moved
  102688. */
  102689. this.validateDrag = function (targetPosition) { return true; };
  102690. this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  102691. this._alternatePickedPoint = new BABYLON.Vector3(0, 0, 0);
  102692. this._worldDragAxis = new BABYLON.Vector3(0, 0, 0);
  102693. this._targetPosition = new BABYLON.Vector3(0, 0, 0);
  102694. this._attachedElement = null;
  102695. this._startDragRay = new BABYLON.Ray(new BABYLON.Vector3(), new BABYLON.Vector3());
  102696. this._lastPointerRay = {};
  102697. this._dragDelta = new BABYLON.Vector3();
  102698. // Variables to avoid instantiation in the below method
  102699. this._pointA = new BABYLON.Vector3(0, 0, 0);
  102700. this._pointB = new BABYLON.Vector3(0, 0, 0);
  102701. this._pointC = new BABYLON.Vector3(0, 0, 0);
  102702. this._lineA = new BABYLON.Vector3(0, 0, 0);
  102703. this._lineB = new BABYLON.Vector3(0, 0, 0);
  102704. this._localAxis = new BABYLON.Vector3(0, 0, 0);
  102705. this._lookAt = new BABYLON.Vector3(0, 0, 0);
  102706. this._options = options ? options : {};
  102707. var optionCount = 0;
  102708. if (this._options.dragAxis) {
  102709. optionCount++;
  102710. }
  102711. if (this._options.dragPlaneNormal) {
  102712. optionCount++;
  102713. }
  102714. if (optionCount > 1) {
  102715. throw "Multiple drag modes specified in dragBehavior options. Only one expected";
  102716. }
  102717. }
  102718. Object.defineProperty(PointerDragBehavior.prototype, "name", {
  102719. /**
  102720. * The name of the behavior
  102721. */
  102722. get: function () {
  102723. return "PointerDrag";
  102724. },
  102725. enumerable: true,
  102726. configurable: true
  102727. });
  102728. /**
  102729. * Initializes the behavior
  102730. */
  102731. PointerDragBehavior.prototype.init = function () { };
  102732. /**
  102733. * Attaches the drag behavior the passed in mesh
  102734. * @param ownerNode The mesh that will be dragged around once attached
  102735. */
  102736. PointerDragBehavior.prototype.attach = function (ownerNode) {
  102737. var _this = this;
  102738. this._scene = ownerNode.getScene();
  102739. this._attachedNode = ownerNode;
  102740. // Initialize drag plane to not interfere with existing scene
  102741. if (!PointerDragBehavior._planeScene) {
  102742. if (this._debugMode) {
  102743. PointerDragBehavior._planeScene = this._scene;
  102744. }
  102745. else {
  102746. PointerDragBehavior._planeScene = new BABYLON.Scene(this._scene.getEngine());
  102747. PointerDragBehavior._planeScene.detachControl();
  102748. this._scene.getEngine().scenes.pop();
  102749. this._scene.onDisposeObservable.addOnce(function () {
  102750. PointerDragBehavior._planeScene.dispose();
  102751. PointerDragBehavior._planeScene = null;
  102752. });
  102753. }
  102754. }
  102755. this._dragPlane = BABYLON.Mesh.CreatePlane("pointerDragPlane", this._debugMode ? 1 : 10000, PointerDragBehavior._planeScene, false, BABYLON.Mesh.DOUBLESIDE);
  102756. // State of the drag
  102757. this.lastDragPosition = new BABYLON.Vector3(0, 0, 0);
  102758. var pickPredicate = function (m) {
  102759. return _this._attachedNode == m || m.isDescendantOf(_this._attachedNode);
  102760. };
  102761. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  102762. if (!_this.enabled) {
  102763. return;
  102764. }
  102765. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  102766. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.pickedPoint && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  102767. _this._startDrag(pointerInfo.event.pointerId, pointerInfo.pickInfo.ray, pointerInfo.pickInfo.pickedPoint);
  102768. }
  102769. }
  102770. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  102771. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  102772. _this.releaseDrag();
  102773. }
  102774. }
  102775. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  102776. var pointerId = pointerInfo.event.pointerId;
  102777. // If drag was started with anyMouseID specified, set pointerID to the next mouse that moved
  102778. if (_this.currentDraggingPointerID === PointerDragBehavior._AnyMouseID && pointerId !== PointerDragBehavior._AnyMouseID && pointerInfo.event.pointerType == "mouse") {
  102779. if (_this._lastPointerRay[_this.currentDraggingPointerID]) {
  102780. _this._lastPointerRay[pointerId] = _this._lastPointerRay[_this.currentDraggingPointerID];
  102781. delete _this._lastPointerRay[_this.currentDraggingPointerID];
  102782. }
  102783. _this.currentDraggingPointerID = pointerId;
  102784. }
  102785. // Keep track of last pointer ray, this is used simulating the start of a drag in startDrag()
  102786. if (!_this._lastPointerRay[pointerId]) {
  102787. _this._lastPointerRay[pointerId] = new BABYLON.Ray(new BABYLON.Vector3(), new BABYLON.Vector3());
  102788. }
  102789. if (pointerInfo.pickInfo && pointerInfo.pickInfo.ray) {
  102790. _this._lastPointerRay[pointerId].origin.copyFrom(pointerInfo.pickInfo.ray.origin);
  102791. _this._lastPointerRay[pointerId].direction.copyFrom(pointerInfo.pickInfo.ray.direction);
  102792. if (_this.currentDraggingPointerID == pointerId && _this.dragging) {
  102793. _this._moveDrag(pointerInfo.pickInfo.ray);
  102794. }
  102795. }
  102796. }
  102797. });
  102798. this._beforeRenderObserver = this._scene.onBeforeRenderObservable.add(function () {
  102799. if (_this._moving && _this.moveAttached) {
  102800. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(_this._attachedNode);
  102801. // Slowly move mesh to avoid jitter
  102802. _this._targetPosition.subtractToRef((_this._attachedNode).absolutePosition, _this._tmpVector);
  102803. _this._tmpVector.scaleInPlace(_this.dragDeltaRatio);
  102804. (_this._attachedNode).getAbsolutePosition().addToRef(_this._tmpVector, _this._tmpVector);
  102805. if (_this.validateDrag(_this._tmpVector)) {
  102806. (_this._attachedNode).setAbsolutePosition(_this._tmpVector);
  102807. }
  102808. BABYLON.BoundingBoxGizmo._RestorePivotPoint(_this._attachedNode);
  102809. }
  102810. });
  102811. };
  102812. /**
  102813. * Force relase the drag action by code.
  102814. */
  102815. PointerDragBehavior.prototype.releaseDrag = function () {
  102816. this.dragging = false;
  102817. this.onDragEndObservable.notifyObservers({ dragPlanePoint: this.lastDragPosition, pointerId: this.currentDraggingPointerID });
  102818. this.currentDraggingPointerID = -1;
  102819. this._moving = false;
  102820. // Reattach camera controls
  102821. if (this.detachCameraControls && this._attachedElement && this._scene.activeCamera && !this._scene.activeCamera.leftCamera) {
  102822. this._scene.activeCamera.attachControl(this._attachedElement, true);
  102823. }
  102824. };
  102825. /**
  102826. * Simulates the start of a pointer drag event on the behavior
  102827. * @param pointerId pointerID of the pointer that should be simulated (Default: Any mouse pointer ID)
  102828. * @param fromRay initial ray of the pointer to be simulated (Default: Ray from camera to attached mesh)
  102829. * @param startPickedPoint picked point of the pointer to be simulated (Default: attached mesh position)
  102830. */
  102831. PointerDragBehavior.prototype.startDrag = function (pointerId, fromRay, startPickedPoint) {
  102832. if (pointerId === void 0) { pointerId = PointerDragBehavior._AnyMouseID; }
  102833. this._startDrag(pointerId, fromRay, startPickedPoint);
  102834. var lastRay = this._lastPointerRay[pointerId];
  102835. if (pointerId === PointerDragBehavior._AnyMouseID) {
  102836. lastRay = this._lastPointerRay[Object.keys(this._lastPointerRay)[0]];
  102837. }
  102838. if (lastRay) {
  102839. // if there was a last pointer ray drag the object there
  102840. this._moveDrag(lastRay);
  102841. }
  102842. };
  102843. PointerDragBehavior.prototype._startDrag = function (pointerId, fromRay, startPickedPoint) {
  102844. if (!this._scene.activeCamera || this.dragging || !this._attachedNode) {
  102845. return;
  102846. }
  102847. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(this._attachedNode);
  102848. // Create start ray from the camera to the object
  102849. if (fromRay) {
  102850. this._startDragRay.direction.copyFrom(fromRay.direction);
  102851. this._startDragRay.origin.copyFrom(fromRay.origin);
  102852. }
  102853. else {
  102854. this._startDragRay.origin.copyFrom(this._scene.activeCamera.position);
  102855. this._attachedNode.getWorldMatrix().getTranslationToRef(this._tmpVector);
  102856. this._tmpVector.subtractToRef(this._scene.activeCamera.position, this._startDragRay.direction);
  102857. }
  102858. this._updateDragPlanePosition(this._startDragRay, startPickedPoint ? startPickedPoint : this._tmpVector);
  102859. var pickedPoint = this._pickWithRayOnDragPlane(this._startDragRay);
  102860. if (pickedPoint) {
  102861. this.dragging = true;
  102862. this.currentDraggingPointerID = pointerId;
  102863. this.lastDragPosition.copyFrom(pickedPoint);
  102864. this.onDragStartObservable.notifyObservers({ dragPlanePoint: pickedPoint, pointerId: this.currentDraggingPointerID });
  102865. this._targetPosition.copyFrom((this._attachedNode).absolutePosition);
  102866. // Detatch camera controls
  102867. if (this.detachCameraControls && this._scene.activeCamera && !this._scene.activeCamera.leftCamera) {
  102868. if (this._scene.activeCamera.inputs.attachedElement) {
  102869. this._attachedElement = this._scene.activeCamera.inputs.attachedElement;
  102870. this._scene.activeCamera.detachControl(this._scene.activeCamera.inputs.attachedElement);
  102871. }
  102872. else {
  102873. this._attachedElement = null;
  102874. }
  102875. }
  102876. }
  102877. BABYLON.BoundingBoxGizmo._RestorePivotPoint(this._attachedNode);
  102878. };
  102879. PointerDragBehavior.prototype._moveDrag = function (ray) {
  102880. this._moving = true;
  102881. var pickedPoint = this._pickWithRayOnDragPlane(ray);
  102882. if (pickedPoint) {
  102883. if (this.updateDragPlane) {
  102884. this._updateDragPlanePosition(ray, pickedPoint);
  102885. }
  102886. var dragLength = 0;
  102887. // depending on the drag mode option drag accordingly
  102888. if (this._options.dragAxis) {
  102889. // Convert local drag axis to world
  102890. BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._worldDragAxis);
  102891. // Project delta drag from the drag plane onto the drag axis
  102892. pickedPoint.subtractToRef(this.lastDragPosition, this._tmpVector);
  102893. dragLength = BABYLON.Vector3.Dot(this._tmpVector, this._worldDragAxis);
  102894. this._worldDragAxis.scaleToRef(dragLength, this._dragDelta);
  102895. }
  102896. else {
  102897. dragLength = this._dragDelta.length();
  102898. pickedPoint.subtractToRef(this.lastDragPosition, this._dragDelta);
  102899. }
  102900. this._targetPosition.addInPlace(this._dragDelta);
  102901. this.onDragObservable.notifyObservers({ dragDistance: dragLength, delta: this._dragDelta, dragPlanePoint: pickedPoint, dragPlaneNormal: this._dragPlane.forward, pointerId: this.currentDraggingPointerID });
  102902. this.lastDragPosition.copyFrom(pickedPoint);
  102903. }
  102904. };
  102905. PointerDragBehavior.prototype._pickWithRayOnDragPlane = function (ray) {
  102906. var _this = this;
  102907. if (!ray) {
  102908. return null;
  102909. }
  102910. // Calculate angle between plane normal and ray
  102911. var angle = Math.acos(BABYLON.Vector3.Dot(this._dragPlane.forward, ray.direction));
  102912. // Correct if ray is casted from oposite side
  102913. if (angle > Math.PI / 2) {
  102914. angle = Math.PI - angle;
  102915. }
  102916. // If the angle is too perpendicular to the plane pick another point on the plane where it is looking
  102917. if (this.maxDragAngle > 0 && angle > this.maxDragAngle) {
  102918. if (this._useAlternatePickedPointAboveMaxDragAngle) {
  102919. // Invert ray direction along the towards object axis
  102920. this._tmpVector.copyFrom(ray.direction);
  102921. (this._attachedNode).absolutePosition.subtractToRef(ray.origin, this._alternatePickedPoint);
  102922. this._alternatePickedPoint.normalize();
  102923. this._alternatePickedPoint.scaleInPlace(-2 * BABYLON.Vector3.Dot(this._alternatePickedPoint, this._tmpVector));
  102924. this._tmpVector.addInPlace(this._alternatePickedPoint);
  102925. // Project resulting vector onto the drag plane and add it to the attached nodes absolute position to get a picked point
  102926. var dot = BABYLON.Vector3.Dot(this._dragPlane.forward, this._tmpVector);
  102927. this._dragPlane.forward.scaleToRef(-dot, this._alternatePickedPoint);
  102928. this._alternatePickedPoint.addInPlace(this._tmpVector);
  102929. this._alternatePickedPoint.addInPlace((this._attachedNode).absolutePosition);
  102930. return this._alternatePickedPoint;
  102931. }
  102932. else {
  102933. return null;
  102934. }
  102935. }
  102936. var pickResult = PointerDragBehavior._planeScene.pickWithRay(ray, function (m) { return m == _this._dragPlane; });
  102937. if (pickResult && pickResult.hit && pickResult.pickedMesh && pickResult.pickedPoint) {
  102938. return pickResult.pickedPoint;
  102939. }
  102940. else {
  102941. return null;
  102942. }
  102943. };
  102944. // Position the drag plane based on the attached mesh position, for single axis rotate the plane along the axis to face the camera
  102945. PointerDragBehavior.prototype._updateDragPlanePosition = function (ray, dragPlanePosition) {
  102946. this._pointA.copyFrom(dragPlanePosition);
  102947. if (this._options.dragAxis) {
  102948. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragAxis);
  102949. // Calculate plane normal in direction of camera but perpendicular to drag axis
  102950. this._pointA.addToRef(this._localAxis, this._pointB); // towards drag axis
  102951. ray.origin.subtractToRef(this._pointA, this._pointC);
  102952. this._pointA.addToRef(this._pointC.normalize(), this._pointC); // towards camera
  102953. // Get perpendicular line from direction to camera and drag axis
  102954. this._pointB.subtractToRef(this._pointA, this._lineA);
  102955. this._pointC.subtractToRef(this._pointA, this._lineB);
  102956. BABYLON.Vector3.CrossToRef(this._lineA, this._lineB, this._lookAt);
  102957. // Get perpendicular line from previous result and drag axis to adjust lineB to be perpendiculat to camera
  102958. BABYLON.Vector3.CrossToRef(this._lineA, this._lookAt, this._lookAt);
  102959. this._lookAt.normalize();
  102960. this._dragPlane.position.copyFrom(this._pointA);
  102961. this._pointA.addToRef(this._lookAt, this._lookAt);
  102962. this._dragPlane.lookAt(this._lookAt);
  102963. }
  102964. else if (this._options.dragPlaneNormal) {
  102965. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragPlaneNormal, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragPlaneNormal);
  102966. this._dragPlane.position.copyFrom(this._pointA);
  102967. this._pointA.addToRef(this._localAxis, this._lookAt);
  102968. this._dragPlane.lookAt(this._lookAt);
  102969. }
  102970. else {
  102971. this._dragPlane.position.copyFrom(this._pointA);
  102972. this._dragPlane.lookAt(ray.origin);
  102973. }
  102974. this._dragPlane.computeWorldMatrix(true);
  102975. };
  102976. /**
  102977. * Detaches the behavior from the mesh
  102978. */
  102979. PointerDragBehavior.prototype.detach = function () {
  102980. if (this._pointerObserver) {
  102981. this._scene.onPointerObservable.remove(this._pointerObserver);
  102982. }
  102983. if (this._beforeRenderObserver) {
  102984. this._scene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  102985. }
  102986. };
  102987. PointerDragBehavior._AnyMouseID = -2;
  102988. return PointerDragBehavior;
  102989. }());
  102990. BABYLON.PointerDragBehavior = PointerDragBehavior;
  102991. })(BABYLON || (BABYLON = {}));
  102992. //# sourceMappingURL=babylon.pointerDragBehavior.js.map
  102993. var BABYLON;
  102994. (function (BABYLON) {
  102995. /**
  102996. * A behavior that when attached to a mesh will allow the mesh to be scaled
  102997. */
  102998. var MultiPointerScaleBehavior = /** @class */ (function () {
  102999. /**
  103000. * Instantiate a new behavior that when attached to a mesh will allow the mesh to be scaled
  103001. */
  103002. function MultiPointerScaleBehavior() {
  103003. this._startDistance = 0;
  103004. this._initialScale = new BABYLON.Vector3(0, 0, 0);
  103005. this._targetScale = new BABYLON.Vector3(0, 0, 0);
  103006. this._sceneRenderObserver = null;
  103007. this._dragBehaviorA = new BABYLON.PointerDragBehavior({});
  103008. this._dragBehaviorA.moveAttached = false;
  103009. this._dragBehaviorB = new BABYLON.PointerDragBehavior({});
  103010. this._dragBehaviorB.moveAttached = false;
  103011. }
  103012. Object.defineProperty(MultiPointerScaleBehavior.prototype, "name", {
  103013. /**
  103014. * The name of the behavior
  103015. */
  103016. get: function () {
  103017. return "MultiPointerScale";
  103018. },
  103019. enumerable: true,
  103020. configurable: true
  103021. });
  103022. /**
  103023. * Initializes the behavior
  103024. */
  103025. MultiPointerScaleBehavior.prototype.init = function () { };
  103026. MultiPointerScaleBehavior.prototype._getCurrentDistance = function () {
  103027. return this._dragBehaviorA.lastDragPosition.subtract(this._dragBehaviorB.lastDragPosition).length();
  103028. };
  103029. /**
  103030. * Attaches the scale behavior the passed in mesh
  103031. * @param ownerNode The mesh that will be scaled around once attached
  103032. */
  103033. MultiPointerScaleBehavior.prototype.attach = function (ownerNode) {
  103034. var _this = this;
  103035. this._ownerNode = ownerNode;
  103036. // Create 2 drag behaviors such that each will only be triggered by a separate pointer
  103037. this._dragBehaviorA.onDragStartObservable.add(function (e) {
  103038. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  103039. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  103040. _this._dragBehaviorA.releaseDrag();
  103041. }
  103042. else {
  103043. _this._initialScale.copyFrom(ownerNode.scaling);
  103044. _this._startDistance = _this._getCurrentDistance();
  103045. }
  103046. }
  103047. });
  103048. this._dragBehaviorB.onDragStartObservable.add(function (e) {
  103049. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  103050. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  103051. _this._dragBehaviorB.releaseDrag();
  103052. }
  103053. else {
  103054. _this._initialScale.copyFrom(ownerNode.scaling);
  103055. _this._startDistance = _this._getCurrentDistance();
  103056. }
  103057. }
  103058. });
  103059. // Once both drag behaviors are active scale based on the distance between the two pointers
  103060. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  103061. behavior.onDragObservable.add(function () {
  103062. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  103063. var ratio = _this._getCurrentDistance() / _this._startDistance;
  103064. _this._initialScale.scaleToRef(ratio, _this._targetScale);
  103065. }
  103066. });
  103067. });
  103068. ownerNode.addBehavior(this._dragBehaviorA);
  103069. ownerNode.addBehavior(this._dragBehaviorB);
  103070. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  103071. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  103072. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  103073. var change = _this._targetScale.subtract(ownerNode.scaling).scaleInPlace(0.1);
  103074. if (change.length() > 0.01) {
  103075. ownerNode.scaling.addInPlace(change);
  103076. }
  103077. }
  103078. });
  103079. };
  103080. /**
  103081. * Detaches the behavior from the mesh
  103082. */
  103083. MultiPointerScaleBehavior.prototype.detach = function () {
  103084. var _this = this;
  103085. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  103086. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  103087. behavior.onDragStartObservable.clear();
  103088. behavior.onDragObservable.clear();
  103089. _this._ownerNode.removeBehavior(behavior);
  103090. });
  103091. };
  103092. return MultiPointerScaleBehavior;
  103093. }());
  103094. BABYLON.MultiPointerScaleBehavior = MultiPointerScaleBehavior;
  103095. })(BABYLON || (BABYLON = {}));
  103096. //# sourceMappingURL=babylon.multiPointerScaleBehavior.js.map
  103097. var BABYLON;
  103098. (function (BABYLON) {
  103099. /**
  103100. * 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
  103101. */
  103102. var SixDofDragBehavior = /** @class */ (function () {
  103103. /**
  103104. * 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
  103105. */
  103106. function SixDofDragBehavior() {
  103107. this._sceneRenderObserver = null;
  103108. this._targetPosition = new BABYLON.Vector3(0, 0, 0);
  103109. this._moving = false;
  103110. this._startingOrientation = new BABYLON.Quaternion();
  103111. /**
  103112. * 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)
  103113. */
  103114. this.zDragFactor = 3;
  103115. /**
  103116. * If the object should rotate to face the drag origin
  103117. */
  103118. this.rotateDraggedObject = true;
  103119. /**
  103120. * If the behavior is currently in a dragging state
  103121. */
  103122. this.dragging = false;
  103123. /**
  103124. * 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)
  103125. */
  103126. this.dragDeltaRatio = 0.2;
  103127. /**
  103128. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  103129. */
  103130. this.currentDraggingPointerID = -1;
  103131. /**
  103132. * If camera controls should be detached during the drag
  103133. */
  103134. this.detachCameraControls = true;
  103135. /**
  103136. * Fires each time a drag starts
  103137. */
  103138. this.onDragStartObservable = new BABYLON.Observable();
  103139. /**
  103140. * Fires each time a drag ends (eg. mouse release after drag)
  103141. */
  103142. this.onDragEndObservable = new BABYLON.Observable();
  103143. }
  103144. Object.defineProperty(SixDofDragBehavior.prototype, "name", {
  103145. /**
  103146. * The name of the behavior
  103147. */
  103148. get: function () {
  103149. return "SixDofDrag";
  103150. },
  103151. enumerable: true,
  103152. configurable: true
  103153. });
  103154. /**
  103155. * Initializes the behavior
  103156. */
  103157. SixDofDragBehavior.prototype.init = function () { };
  103158. /**
  103159. * Attaches the scale behavior the passed in mesh
  103160. * @param ownerNode The mesh that will be scaled around once attached
  103161. */
  103162. SixDofDragBehavior.prototype.attach = function (ownerNode) {
  103163. var _this = this;
  103164. this._ownerNode = ownerNode;
  103165. this._scene = this._ownerNode.getScene();
  103166. if (!SixDofDragBehavior._virtualScene) {
  103167. SixDofDragBehavior._virtualScene = new BABYLON.Scene(this._scene.getEngine());
  103168. SixDofDragBehavior._virtualScene.detachControl();
  103169. this._scene.getEngine().scenes.pop();
  103170. }
  103171. var pickedMesh = null;
  103172. var lastSixDofOriginPosition = new BABYLON.Vector3(0, 0, 0);
  103173. // Setup virtual meshes to be used for dragging without dirtying the existing scene
  103174. this._virtualOriginMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  103175. this._virtualOriginMesh.rotationQuaternion = new BABYLON.Quaternion();
  103176. this._virtualDragMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  103177. this._virtualDragMesh.rotationQuaternion = new BABYLON.Quaternion();
  103178. var pickPredicate = function (m) {
  103179. return _this._ownerNode == m || m.isDescendantOf(_this._ownerNode);
  103180. };
  103181. var attachedElement = null;
  103182. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  103183. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  103184. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  103185. if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON.Camera.RIG_MODE_NONE) {
  103186. pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.globalPosition);
  103187. }
  103188. pickedMesh = _this._ownerNode;
  103189. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(pickedMesh);
  103190. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  103191. // Set position and orientation of the controller
  103192. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  103193. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.add(pointerInfo.pickInfo.ray.direction));
  103194. // Attach the virtual drag mesh to the virtual origin mesh so it can be dragged
  103195. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  103196. pickedMesh.computeWorldMatrix();
  103197. _this._virtualDragMesh.position.copyFrom(pickedMesh.absolutePosition);
  103198. if (!pickedMesh.rotationQuaternion) {
  103199. pickedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(pickedMesh.rotation.y, pickedMesh.rotation.x, pickedMesh.rotation.z);
  103200. }
  103201. var oldParent = pickedMesh.parent;
  103202. pickedMesh.setParent(null);
  103203. _this._virtualDragMesh.rotationQuaternion.copyFrom(pickedMesh.rotationQuaternion);
  103204. pickedMesh.setParent(oldParent);
  103205. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  103206. // Update state
  103207. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  103208. _this.dragging = true;
  103209. _this.currentDraggingPointerID = pointerInfo.event.pointerId;
  103210. // Detatch camera controls
  103211. if (_this.detachCameraControls && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  103212. if (_this._scene.activeCamera.inputs.attachedElement) {
  103213. attachedElement = _this._scene.activeCamera.inputs.attachedElement;
  103214. _this._scene.activeCamera.detachControl(_this._scene.activeCamera.inputs.attachedElement);
  103215. }
  103216. else {
  103217. attachedElement = null;
  103218. }
  103219. }
  103220. BABYLON.BoundingBoxGizmo._RestorePivotPoint(pickedMesh);
  103221. _this.onDragStartObservable.notifyObservers({});
  103222. }
  103223. }
  103224. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  103225. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  103226. _this.dragging = false;
  103227. _this._moving = false;
  103228. _this.currentDraggingPointerID = -1;
  103229. pickedMesh = null;
  103230. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  103231. // Reattach camera controls
  103232. if (_this.detachCameraControls && attachedElement && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  103233. _this._scene.activeCamera.attachControl(attachedElement, true);
  103234. }
  103235. _this.onDragEndObservable.notifyObservers({});
  103236. }
  103237. }
  103238. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  103239. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId && _this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray && pickedMesh) {
  103240. var zDragFactor = _this.zDragFactor;
  103241. if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON.Camera.RIG_MODE_NONE) {
  103242. pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.globalPosition);
  103243. zDragFactor = 0;
  103244. }
  103245. // Calculate controller drag distance in controller space
  103246. var originDragDifference = pointerInfo.pickInfo.ray.origin.subtract(lastSixDofOriginPosition);
  103247. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  103248. var localOriginDragDifference = -BABYLON.Vector3.Dot(originDragDifference, pointerInfo.pickInfo.ray.direction);
  103249. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  103250. // Determine how much the controller moved to/away towards the dragged object and use this to move the object further when its further away
  103251. _this._virtualDragMesh.position.z -= _this._virtualDragMesh.position.z < 1 ? localOriginDragDifference * _this.zDragFactor : localOriginDragDifference * zDragFactor * _this._virtualDragMesh.position.z;
  103252. if (_this._virtualDragMesh.position.z < 0) {
  103253. _this._virtualDragMesh.position.z = 0;
  103254. }
  103255. // Update the controller position
  103256. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  103257. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.add(pointerInfo.pickInfo.ray.direction));
  103258. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  103259. // Move the virtualObjectsPosition into the picked mesh's space if needed
  103260. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  103261. if (pickedMesh.parent) {
  103262. BABYLON.Vector3.TransformCoordinatesToRef(_this._targetPosition, BABYLON.Matrix.Invert(pickedMesh.parent.getWorldMatrix()), _this._targetPosition);
  103263. }
  103264. if (!_this._moving) {
  103265. _this._startingOrientation.copyFrom(_this._virtualDragMesh.rotationQuaternion);
  103266. }
  103267. _this._moving = true;
  103268. }
  103269. }
  103270. });
  103271. var tmpQuaternion = new BABYLON.Quaternion();
  103272. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  103273. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  103274. if (_this.dragging && _this._moving && pickedMesh) {
  103275. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(pickedMesh);
  103276. // Slowly move mesh to avoid jitter
  103277. pickedMesh.position.addInPlace(_this._targetPosition.subtract(pickedMesh.position).scale(_this.dragDeltaRatio));
  103278. if (_this.rotateDraggedObject) {
  103279. // Get change in rotation
  103280. tmpQuaternion.copyFrom(_this._startingOrientation);
  103281. tmpQuaternion.x = -tmpQuaternion.x;
  103282. tmpQuaternion.y = -tmpQuaternion.y;
  103283. tmpQuaternion.z = -tmpQuaternion.z;
  103284. _this._virtualDragMesh.rotationQuaternion.multiplyToRef(tmpQuaternion, tmpQuaternion);
  103285. // Convert change in rotation to only y axis rotation
  103286. BABYLON.Quaternion.RotationYawPitchRollToRef(tmpQuaternion.toEulerAngles("xyz").y, 0, 0, tmpQuaternion);
  103287. tmpQuaternion.multiplyToRef(_this._startingOrientation, tmpQuaternion);
  103288. // Slowly move mesh to avoid jitter
  103289. var oldParent = pickedMesh.parent;
  103290. pickedMesh.setParent(null);
  103291. BABYLON.Quaternion.SlerpToRef(pickedMesh.rotationQuaternion, tmpQuaternion, _this.dragDeltaRatio, pickedMesh.rotationQuaternion);
  103292. pickedMesh.setParent(oldParent);
  103293. BABYLON.BoundingBoxGizmo._RestorePivotPoint(pickedMesh);
  103294. }
  103295. }
  103296. });
  103297. };
  103298. /**
  103299. * Detaches the behavior from the mesh
  103300. */
  103301. SixDofDragBehavior.prototype.detach = function () {
  103302. if (this._scene) {
  103303. this._scene.onPointerObservable.remove(this._pointerObserver);
  103304. }
  103305. if (this._ownerNode) {
  103306. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  103307. }
  103308. if (this._virtualOriginMesh) {
  103309. this._virtualOriginMesh.dispose();
  103310. }
  103311. if (this._virtualDragMesh) {
  103312. this._virtualDragMesh.dispose();
  103313. }
  103314. this.onDragEndObservable.clear();
  103315. this.onDragStartObservable.clear();
  103316. };
  103317. return SixDofDragBehavior;
  103318. }());
  103319. BABYLON.SixDofDragBehavior = SixDofDragBehavior;
  103320. })(BABYLON || (BABYLON = {}));
  103321. //# sourceMappingURL=babylon.sixDofDragBehavior.js.map
  103322. var BABYLON;
  103323. (function (BABYLON) {
  103324. /**
  103325. * @hidden
  103326. */
  103327. var FaceDirectionInfo = /** @class */ (function () {
  103328. function FaceDirectionInfo(direction, rotatedDirection, diff, ignore) {
  103329. if (rotatedDirection === void 0) { rotatedDirection = new BABYLON.Vector3(); }
  103330. if (diff === void 0) { diff = 0; }
  103331. if (ignore === void 0) { ignore = false; }
  103332. this.direction = direction;
  103333. this.rotatedDirection = rotatedDirection;
  103334. this.diff = diff;
  103335. this.ignore = ignore;
  103336. }
  103337. return FaceDirectionInfo;
  103338. }());
  103339. /**
  103340. * A behavior that when attached to a mesh will will place a specified node on the meshes face pointing towards the camera
  103341. */
  103342. var AttachToBoxBehavior = /** @class */ (function () {
  103343. /**
  103344. * Creates the AttachToBoxBehavior, used to attach UI to the closest face of the box to a camera
  103345. * @param ui The transform node that should be attched to the mesh
  103346. */
  103347. function AttachToBoxBehavior(ui) {
  103348. this.ui = ui;
  103349. /**
  103350. * The name of the behavior
  103351. */
  103352. this.name = "AttachToBoxBehavior";
  103353. /**
  103354. * The distance away from the face of the mesh that the UI should be attached to (default: 0.15)
  103355. */
  103356. this.distanceAwayFromFace = 0.15;
  103357. /**
  103358. * The distance from the bottom of the face that the UI should be attached to (default: 0.15)
  103359. */
  103360. this.distanceAwayFromBottomOfFace = 0.15;
  103361. 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))];
  103362. this._tmpMatrix = new BABYLON.Matrix();
  103363. this._tmpVector = new BABYLON.Vector3();
  103364. this._zeroVector = BABYLON.Vector3.Zero();
  103365. this._lookAtTmpMatrix = new BABYLON.Matrix();
  103366. /* Does nothing */
  103367. }
  103368. /**
  103369. * Initializes the behavior
  103370. */
  103371. AttachToBoxBehavior.prototype.init = function () {
  103372. /* Does nothing */
  103373. };
  103374. AttachToBoxBehavior.prototype._closestFace = function (targetDirection) {
  103375. var _this = this;
  103376. // Go over each face and calculate the angle between the face's normal and targetDirection
  103377. this._faceVectors.forEach(function (v) {
  103378. if (!_this._target.rotationQuaternion) {
  103379. _this._target.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._target.rotation.y, _this._target.rotation.x, _this._target.rotation.z);
  103380. }
  103381. _this._target.rotationQuaternion.toRotationMatrix(_this._tmpMatrix);
  103382. BABYLON.Vector3.TransformCoordinatesToRef(v.direction, _this._tmpMatrix, v.rotatedDirection);
  103383. v.diff = BABYLON.Vector3.GetAngleBetweenVectors(v.rotatedDirection, targetDirection, BABYLON.Vector3.Cross(v.rotatedDirection, targetDirection));
  103384. });
  103385. // Return the face information of the one with the normal closeset to target direction
  103386. return this._faceVectors.reduce(function (min, p) {
  103387. if (min.ignore) {
  103388. return p;
  103389. }
  103390. else if (p.ignore) {
  103391. return min;
  103392. }
  103393. else {
  103394. return min.diff < p.diff ? min : p;
  103395. }
  103396. }, this._faceVectors[0]);
  103397. };
  103398. AttachToBoxBehavior.prototype._lookAtToRef = function (pos, up, ref) {
  103399. if (up === void 0) { up = new BABYLON.Vector3(0, 1, 0); }
  103400. BABYLON.Matrix.LookAtLHToRef(this._zeroVector, pos, up, this._lookAtTmpMatrix);
  103401. this._lookAtTmpMatrix.invert();
  103402. BABYLON.Quaternion.FromRotationMatrixToRef(this._lookAtTmpMatrix, ref);
  103403. };
  103404. /**
  103405. * Attaches the AttachToBoxBehavior to the passed in mesh
  103406. * @param target The mesh that the specified node will be attached to
  103407. */
  103408. AttachToBoxBehavior.prototype.attach = function (target) {
  103409. var _this = this;
  103410. this._target = target;
  103411. this._scene = this._target.getScene();
  103412. // Every frame, update the app bars position
  103413. this._onRenderObserver = this._scene.onBeforeRenderObservable.add(function () {
  103414. if (!_this._scene.activeCamera) {
  103415. return;
  103416. }
  103417. // Find the face closest to the cameras position
  103418. var cameraPos = _this._scene.activeCamera.position;
  103419. if (_this._scene.activeCamera.devicePosition) {
  103420. cameraPos = _this._scene.activeCamera.devicePosition;
  103421. }
  103422. var facing = _this._closestFace(cameraPos.subtract(target.position));
  103423. if (_this._scene.activeCamera.leftCamera) {
  103424. _this._scene.activeCamera.leftCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
  103425. }
  103426. else {
  103427. _this._scene.activeCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
  103428. }
  103429. // Get camera up direction
  103430. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Vector3.Up(), _this._tmpMatrix, _this._tmpVector);
  103431. // Ignore faces to not select a parrelel face for the up vector of the UI
  103432. _this._faceVectors.forEach(function (v) {
  103433. if (facing.direction.x && v.direction.x) {
  103434. v.ignore = true;
  103435. }
  103436. if (facing.direction.y && v.direction.y) {
  103437. v.ignore = true;
  103438. }
  103439. if (facing.direction.z && v.direction.z) {
  103440. v.ignore = true;
  103441. }
  103442. });
  103443. var facingUp = _this._closestFace(_this._tmpVector);
  103444. // Unignore faces
  103445. _this._faceVectors.forEach(function (v) {
  103446. v.ignore = false;
  103447. });
  103448. // Position the app bar on that face
  103449. _this.ui.position.copyFrom(target.position);
  103450. if (facing.direction.x) {
  103451. facing.rotatedDirection.scaleToRef((target.scaling.x / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  103452. _this.ui.position.addInPlace(_this._tmpVector);
  103453. }
  103454. if (facing.direction.y) {
  103455. facing.rotatedDirection.scaleToRef((target.scaling.y / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  103456. _this.ui.position.addInPlace(_this._tmpVector);
  103457. }
  103458. if (facing.direction.z) {
  103459. facing.rotatedDirection.scaleToRef((target.scaling.z / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  103460. _this.ui.position.addInPlace(_this._tmpVector);
  103461. }
  103462. // Rotate to be oriented properly to the camera
  103463. if (!_this.ui.rotationQuaternion) {
  103464. _this.ui.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.ui.rotation.y, _this.ui.rotation.x, _this.ui.rotation.z);
  103465. }
  103466. facing.rotatedDirection.scaleToRef(-1, _this._tmpVector);
  103467. _this._lookAtToRef(_this._tmpVector, facingUp.rotatedDirection, _this.ui.rotationQuaternion);
  103468. // Place ui the correct distance from the bottom of the mesh
  103469. if (facingUp.direction.x) {
  103470. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.x / 2, _this._tmpVector);
  103471. }
  103472. if (facingUp.direction.y) {
  103473. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.y / 2, _this._tmpVector);
  103474. }
  103475. if (facingUp.direction.z) {
  103476. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.z / 2, _this._tmpVector);
  103477. }
  103478. _this.ui.position.addInPlace(_this._tmpVector);
  103479. });
  103480. };
  103481. /**
  103482. * Detaches the behavior from the mesh
  103483. */
  103484. AttachToBoxBehavior.prototype.detach = function () {
  103485. this._scene.onBeforeRenderObservable.remove(this._onRenderObserver);
  103486. };
  103487. return AttachToBoxBehavior;
  103488. }());
  103489. BABYLON.AttachToBoxBehavior = AttachToBoxBehavior;
  103490. })(BABYLON || (BABYLON = {}));
  103491. //# sourceMappingURL=babylon.attachToBoxBehavior.js.map
  103492. var BABYLON;
  103493. (function (BABYLON) {
  103494. /**
  103495. * A behavior that when attached to a mesh will allow the mesh to fade in and out
  103496. */
  103497. var FadeInOutBehavior = /** @class */ (function () {
  103498. /**
  103499. * Instatiates the FadeInOutBehavior
  103500. */
  103501. function FadeInOutBehavior() {
  103502. var _this = this;
  103503. /**
  103504. * Time in milliseconds to delay before fading in (Default: 0)
  103505. */
  103506. this.delay = 0;
  103507. /**
  103508. * Time in milliseconds for the mesh to fade in (Default: 300)
  103509. */
  103510. this.fadeInTime = 300;
  103511. this._millisecondsPerFrame = 1000 / 60;
  103512. this._hovered = false;
  103513. this._hoverValue = 0;
  103514. this._ownerNode = null;
  103515. this._update = function () {
  103516. if (_this._ownerNode) {
  103517. _this._hoverValue += _this._hovered ? _this._millisecondsPerFrame : -_this._millisecondsPerFrame;
  103518. _this._setAllVisibility(_this._ownerNode, (_this._hoverValue - _this.delay) / _this.fadeInTime);
  103519. if (_this._ownerNode.visibility > 1) {
  103520. _this._setAllVisibility(_this._ownerNode, 1);
  103521. _this._hoverValue = _this.fadeInTime + _this.delay;
  103522. return;
  103523. }
  103524. else if (_this._ownerNode.visibility < 0) {
  103525. _this._setAllVisibility(_this._ownerNode, 0);
  103526. if (_this._hoverValue < 0) {
  103527. _this._hoverValue = 0;
  103528. return;
  103529. }
  103530. }
  103531. setTimeout(_this._update, _this._millisecondsPerFrame);
  103532. }
  103533. };
  103534. }
  103535. Object.defineProperty(FadeInOutBehavior.prototype, "name", {
  103536. /**
  103537. * The name of the behavior
  103538. */
  103539. get: function () {
  103540. return "FadeInOut";
  103541. },
  103542. enumerable: true,
  103543. configurable: true
  103544. });
  103545. /**
  103546. * Initializes the behavior
  103547. */
  103548. FadeInOutBehavior.prototype.init = function () {
  103549. };
  103550. /**
  103551. * Attaches the fade behavior on the passed in mesh
  103552. * @param ownerNode The mesh that will be faded in/out once attached
  103553. */
  103554. FadeInOutBehavior.prototype.attach = function (ownerNode) {
  103555. this._ownerNode = ownerNode;
  103556. this._setAllVisibility(this._ownerNode, 0);
  103557. };
  103558. /**
  103559. * Detaches the behavior from the mesh
  103560. */
  103561. FadeInOutBehavior.prototype.detach = function () {
  103562. this._ownerNode = null;
  103563. };
  103564. /**
  103565. * Triggers the mesh to begin fading in or out
  103566. * @param value if the object should fade in or out (true to fade in)
  103567. */
  103568. FadeInOutBehavior.prototype.fadeIn = function (value) {
  103569. this._hovered = value;
  103570. this._update();
  103571. };
  103572. FadeInOutBehavior.prototype._setAllVisibility = function (mesh, value) {
  103573. var _this = this;
  103574. mesh.visibility = value;
  103575. mesh.getChildMeshes().forEach(function (c) {
  103576. _this._setAllVisibility(c, value);
  103577. });
  103578. };
  103579. return FadeInOutBehavior;
  103580. }());
  103581. BABYLON.FadeInOutBehavior = FadeInOutBehavior;
  103582. })(BABYLON || (BABYLON = {}));
  103583. //# sourceMappingURL=babylon.fadeInOutBehavior.js.map
  103584. var BABYLON;
  103585. (function (BABYLON) {
  103586. /**
  103587. * Renders gizmos on top of an existing scene which provide controls for position, rotation, etc.
  103588. */
  103589. var Gizmo = /** @class */ (function () {
  103590. /**
  103591. * Creates a gizmo
  103592. * @param gizmoLayer The utility layer the gizmo will be added to
  103593. */
  103594. function Gizmo(
  103595. /** The utility layer the gizmo will be added to */
  103596. gizmoLayer) {
  103597. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  103598. var _this = this;
  103599. this.gizmoLayer = gizmoLayer;
  103600. /**
  103601. * Ratio for the scale of the gizmo (Default: 1)
  103602. */
  103603. this.scaleRatio = 1;
  103604. this._tmpMatrix = new BABYLON.Matrix();
  103605. /**
  103606. * If a custom mesh has been set (Default: false)
  103607. */
  103608. this._customMeshSet = false;
  103609. /**
  103610. * If set the gizmo's rotation will be updated to match the attached mesh each frame (Default: true)
  103611. */
  103612. this.updateGizmoRotationToMatchAttachedMesh = true;
  103613. /**
  103614. * If set the gizmo's position will be updated to match the attached mesh each frame (Default: true)
  103615. */
  103616. this.updateGizmoPositionToMatchAttachedMesh = true;
  103617. /**
  103618. * When set, the gizmo will always appear the same size no matter where the camera is (default: false)
  103619. */
  103620. this._updateScale = true;
  103621. this._interactionsEnabled = true;
  103622. this._tempVector = new BABYLON.Vector3();
  103623. this._rootMesh = new BABYLON.Mesh("gizmoRootNode", gizmoLayer.utilityLayerScene);
  103624. this._beforeRenderObserver = this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.add(function () {
  103625. _this._update();
  103626. });
  103627. this.attachedMesh = null;
  103628. }
  103629. Object.defineProperty(Gizmo.prototype, "attachedMesh", {
  103630. /**
  103631. * Mesh that the gizmo will be attached to. (eg. on a drag gizmo the mesh that will be dragged)
  103632. * * When set, interactions will be enabled
  103633. */
  103634. get: function () {
  103635. return this._attachedMesh;
  103636. },
  103637. set: function (value) {
  103638. this._attachedMesh = value;
  103639. this._rootMesh.setEnabled(value ? true : false);
  103640. this._attachedMeshChanged(value);
  103641. },
  103642. enumerable: true,
  103643. configurable: true
  103644. });
  103645. /**
  103646. * Disposes and replaces the current meshes in the gizmo with the specified mesh
  103647. * @param mesh The mesh to replace the default mesh of the gizmo
  103648. */
  103649. Gizmo.prototype.setCustomMesh = function (mesh) {
  103650. if (mesh.getScene() != this.gizmoLayer.utilityLayerScene) {
  103651. throw "When setting a custom mesh on a gizmo, the custom meshes scene must be the same as the gizmos (eg. gizmo.gizmoLayer.utilityLayerScene)";
  103652. }
  103653. this._rootMesh.getChildMeshes().forEach(function (c) {
  103654. c.dispose();
  103655. });
  103656. mesh.parent = this._rootMesh;
  103657. this._customMeshSet = true;
  103658. };
  103659. Gizmo.prototype._attachedMeshChanged = function (value) {
  103660. };
  103661. /**
  103662. * @hidden
  103663. * Updates the gizmo to match the attached mesh's position/rotation
  103664. */
  103665. Gizmo.prototype._update = function () {
  103666. if (this.attachedMesh) {
  103667. if (this.updateGizmoRotationToMatchAttachedMesh) {
  103668. if (!this._rootMesh.rotationQuaternion) {
  103669. this._rootMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this._rootMesh.rotation.y, this._rootMesh.rotation.x, this._rootMesh.rotation.z);
  103670. }
  103671. // Remove scaling before getting rotation matrix to get rotation matrix unmodified by scale
  103672. this._tempVector.copyFrom(this.attachedMesh.scaling);
  103673. if (this.attachedMesh.scaling.x < 0) {
  103674. this.attachedMesh.scaling.x *= -1;
  103675. }
  103676. if (this.attachedMesh.scaling.y < 0) {
  103677. this.attachedMesh.scaling.y *= -1;
  103678. }
  103679. if (this.attachedMesh.scaling.z < 0) {
  103680. this.attachedMesh.scaling.z *= -1;
  103681. }
  103682. this.attachedMesh.computeWorldMatrix().getRotationMatrixToRef(this._tmpMatrix);
  103683. this.attachedMesh.scaling.copyFrom(this._tempVector);
  103684. this.attachedMesh.computeWorldMatrix();
  103685. BABYLON.Quaternion.FromRotationMatrixToRef(this._tmpMatrix, this._rootMesh.rotationQuaternion);
  103686. }
  103687. else if (this._rootMesh.rotationQuaternion) {
  103688. this._rootMesh.rotationQuaternion.set(0, 0, 0, 1);
  103689. }
  103690. if (this.updateGizmoPositionToMatchAttachedMesh) {
  103691. this._rootMesh.position.copyFrom(this.attachedMesh.absolutePosition);
  103692. }
  103693. if (this._updateScale && this.gizmoLayer.utilityLayerScene.activeCamera && this.attachedMesh) {
  103694. var cameraPosition = this.gizmoLayer.utilityLayerScene.activeCamera.globalPosition;
  103695. if (this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition) {
  103696. cameraPosition = this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition;
  103697. }
  103698. this._rootMesh.position.subtractToRef(cameraPosition, this._tempVector);
  103699. var dist = this._tempVector.length() * this.scaleRatio;
  103700. this._rootMesh.scaling.set(dist, dist, dist);
  103701. }
  103702. }
  103703. };
  103704. /**
  103705. * Disposes of the gizmo
  103706. */
  103707. Gizmo.prototype.dispose = function () {
  103708. this._rootMesh.dispose();
  103709. if (this._beforeRenderObserver) {
  103710. this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  103711. }
  103712. };
  103713. return Gizmo;
  103714. }());
  103715. BABYLON.Gizmo = Gizmo;
  103716. })(BABYLON || (BABYLON = {}));
  103717. //# sourceMappingURL=babylon.gizmo.js.map
  103718. var BABYLON;
  103719. (function (BABYLON) {
  103720. /**
  103721. * Single axis drag gizmo
  103722. */
  103723. var AxisDragGizmo = /** @class */ (function (_super) {
  103724. __extends(AxisDragGizmo, _super);
  103725. /**
  103726. * Creates an AxisDragGizmo
  103727. * @param gizmoLayer The utility layer the gizmo will be added to
  103728. * @param dragAxis The axis which the gizmo will be able to drag on
  103729. * @param color The color of the gizmo
  103730. */
  103731. function AxisDragGizmo(dragAxis, color, gizmoLayer) {
  103732. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  103733. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  103734. var _this = _super.call(this, gizmoLayer) || this;
  103735. _this._pointerObserver = null;
  103736. /**
  103737. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  103738. */
  103739. _this.snapDistance = 0;
  103740. /**
  103741. * Event that fires each time the gizmo snaps to a new location.
  103742. * * snapDistance is the the change in distance
  103743. */
  103744. _this.onSnapObservable = new BABYLON.Observable();
  103745. // Create Material
  103746. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  103747. coloredMaterial.disableLighting = true;
  103748. coloredMaterial.emissiveColor = color;
  103749. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  103750. hoverMaterial.disableLighting = true;
  103751. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  103752. // Build mesh on root node
  103753. var arrow = AxisDragGizmo._CreateArrow(gizmoLayer.utilityLayerScene, coloredMaterial);
  103754. arrow.lookAt(_this._rootMesh.position.add(dragAxis));
  103755. arrow.scaling.scaleInPlace(1 / 3);
  103756. arrow.parent = _this._rootMesh;
  103757. var currentSnapDragDistance = 0;
  103758. var tmpVector = new BABYLON.Vector3();
  103759. var tmpSnapEvent = { snapDistance: 0 };
  103760. // Add drag behavior to handle events when the gizmo is dragged
  103761. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  103762. _this.dragBehavior.moveAttached = false;
  103763. _this._rootMesh.addBehavior(_this.dragBehavior);
  103764. var localDelta = new BABYLON.Vector3();
  103765. var tmpMatrix = new BABYLON.Matrix();
  103766. _this.dragBehavior.onDragObservable.add(function (event) {
  103767. if (_this.attachedMesh) {
  103768. // Convert delta to local translation if it has a parent
  103769. if (_this.attachedMesh.parent) {
  103770. _this.attachedMesh.parent.computeWorldMatrix().invertToRef(tmpMatrix);
  103771. tmpMatrix.setTranslationFromFloats(0, 0, 0);
  103772. BABYLON.Vector3.TransformCoordinatesToRef(event.delta, tmpMatrix, localDelta);
  103773. }
  103774. else {
  103775. localDelta.copyFrom(event.delta);
  103776. }
  103777. // Snapping logic
  103778. if (_this.snapDistance == 0) {
  103779. _this.attachedMesh.position.addInPlace(localDelta);
  103780. }
  103781. else {
  103782. currentSnapDragDistance += event.dragDistance;
  103783. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  103784. var dragSteps = Math.floor(Math.abs(currentSnapDragDistance) / _this.snapDistance);
  103785. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  103786. localDelta.normalizeToRef(tmpVector);
  103787. tmpVector.scaleInPlace(_this.snapDistance * dragSteps);
  103788. _this.attachedMesh.position.addInPlace(tmpVector);
  103789. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  103790. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  103791. }
  103792. }
  103793. }
  103794. });
  103795. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  103796. if (_this._customMeshSet) {
  103797. return;
  103798. }
  103799. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  103800. var material = isHovered ? hoverMaterial : coloredMaterial;
  103801. _this._rootMesh.getChildMeshes().forEach(function (m) {
  103802. m.material = material;
  103803. if (m.color) {
  103804. m.color = material.emissiveColor;
  103805. }
  103806. });
  103807. });
  103808. return _this;
  103809. }
  103810. /** @hidden */
  103811. AxisDragGizmo._CreateArrow = function (scene, material) {
  103812. var arrow = new BABYLON.TransformNode("arrow", scene);
  103813. var cylinder = BABYLON.MeshBuilder.CreateCylinder("cylinder", { diameterTop: 0, height: 1.5, diameterBottom: 0.75, tessellation: 96 }, scene);
  103814. var line = BABYLON.MeshBuilder.CreateLines("line", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 1.1, 0)] }, scene);
  103815. line.color = material.emissiveColor;
  103816. cylinder.parent = arrow;
  103817. line.parent = arrow;
  103818. // Position arrow pointing in its drag axis
  103819. cylinder.scaling.scaleInPlace(0.05);
  103820. cylinder.material = material;
  103821. cylinder.rotation.x = Math.PI / 2;
  103822. cylinder.position.z += 0.3;
  103823. line.scaling.scaleInPlace(0.26);
  103824. line.rotation.x = Math.PI / 2;
  103825. line.material = material;
  103826. return arrow;
  103827. };
  103828. /** @hidden */
  103829. AxisDragGizmo._CreateArrowInstance = function (scene, arrow) {
  103830. var instance = new BABYLON.TransformNode("arrow", scene);
  103831. for (var _i = 0, _a = arrow.getChildMeshes(); _i < _a.length; _i++) {
  103832. var mesh = _a[_i];
  103833. var childInstance = mesh.createInstance(mesh.name);
  103834. childInstance.parent = instance;
  103835. }
  103836. return instance;
  103837. };
  103838. AxisDragGizmo.prototype._attachedMeshChanged = function (value) {
  103839. if (this.dragBehavior) {
  103840. this.dragBehavior.enabled = value ? true : false;
  103841. }
  103842. };
  103843. /**
  103844. * Disposes of the gizmo
  103845. */
  103846. AxisDragGizmo.prototype.dispose = function () {
  103847. this.onSnapObservable.clear();
  103848. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  103849. this.dragBehavior.detach();
  103850. _super.prototype.dispose.call(this);
  103851. };
  103852. return AxisDragGizmo;
  103853. }(BABYLON.Gizmo));
  103854. BABYLON.AxisDragGizmo = AxisDragGizmo;
  103855. })(BABYLON || (BABYLON = {}));
  103856. //# sourceMappingURL=babylon.axisDragGizmo.js.map
  103857. var BABYLON;
  103858. (function (BABYLON) {
  103859. /**
  103860. * Single axis scale gizmo
  103861. */
  103862. var AxisScaleGizmo = /** @class */ (function (_super) {
  103863. __extends(AxisScaleGizmo, _super);
  103864. /**
  103865. * Creates an AxisScaleGizmo
  103866. * @param gizmoLayer The utility layer the gizmo will be added to
  103867. * @param dragAxis The axis which the gizmo will be able to scale on
  103868. * @param color The color of the gizmo
  103869. */
  103870. function AxisScaleGizmo(dragAxis, color, gizmoLayer) {
  103871. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  103872. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  103873. var _this = _super.call(this, gizmoLayer) || this;
  103874. _this._pointerObserver = null;
  103875. /**
  103876. * Scale distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  103877. */
  103878. _this.snapDistance = 0;
  103879. /**
  103880. * Event that fires each time the gizmo snaps to a new location.
  103881. * * snapDistance is the the change in distance
  103882. */
  103883. _this.onSnapObservable = new BABYLON.Observable();
  103884. /**
  103885. * If the scaling operation should be done on all axis (default: false)
  103886. */
  103887. _this.uniformScaling = false;
  103888. // Create Material
  103889. _this._coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  103890. _this._coloredMaterial.disableLighting = true;
  103891. _this._coloredMaterial.emissiveColor = color;
  103892. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  103893. hoverMaterial.disableLighting = true;
  103894. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  103895. // Build mesh on root node
  103896. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  103897. var arrowMesh = BABYLON.MeshBuilder.CreateBox("yPosMesh", { size: 0.4 }, gizmoLayer.utilityLayerScene);
  103898. var arrowTail = BABYLON.MeshBuilder.CreateLines("yPosMesh", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 1.1, 0)] }, gizmoLayer.utilityLayerScene);
  103899. arrowTail.color = _this._coloredMaterial.emissiveColor;
  103900. arrow.addChild(arrowMesh);
  103901. arrow.addChild(arrowTail);
  103902. // Position arrow pointing in its drag axis
  103903. arrowMesh.scaling.scaleInPlace(0.1);
  103904. arrowMesh.material = _this._coloredMaterial;
  103905. arrowMesh.rotation.x = Math.PI / 2;
  103906. arrowMesh.position.z += 0.3;
  103907. arrowTail.scaling.scaleInPlace(0.26);
  103908. arrowTail.rotation.x = Math.PI / 2;
  103909. arrowTail.material = _this._coloredMaterial;
  103910. arrow.lookAt(_this._rootMesh.position.add(dragAxis));
  103911. _this._rootMesh.addChild(arrow);
  103912. arrow.scaling.scaleInPlace(1 / 3);
  103913. // Add drag behavior to handle events when the gizmo is dragged
  103914. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  103915. _this.dragBehavior.moveAttached = false;
  103916. _this._rootMesh.addBehavior(_this.dragBehavior);
  103917. var currentSnapDragDistance = 0;
  103918. var tmpVector = new BABYLON.Vector3();
  103919. var tmpSnapEvent = { snapDistance: 0 };
  103920. _this.dragBehavior.onDragObservable.add(function (event) {
  103921. if (_this.attachedMesh) {
  103922. // Snapping logic
  103923. var snapped = false;
  103924. var dragSteps = 0;
  103925. if (_this.uniformScaling) {
  103926. _this.attachedMesh.scaling.normalizeToRef(tmpVector);
  103927. if (tmpVector.y < 0) {
  103928. tmpVector.scaleInPlace(-1);
  103929. }
  103930. }
  103931. else {
  103932. tmpVector.copyFrom(dragAxis);
  103933. }
  103934. if (_this.snapDistance == 0) {
  103935. tmpVector.scaleToRef(event.dragDistance, tmpVector);
  103936. }
  103937. else {
  103938. currentSnapDragDistance += event.dragDistance;
  103939. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  103940. dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  103941. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  103942. tmpVector.scaleToRef(_this.snapDistance * dragSteps, tmpVector);
  103943. snapped = true;
  103944. }
  103945. else {
  103946. tmpVector.scaleInPlace(0);
  103947. }
  103948. }
  103949. _this.attachedMesh.scaling.addInPlace(tmpVector);
  103950. if (snapped) {
  103951. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  103952. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  103953. }
  103954. }
  103955. });
  103956. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  103957. if (_this._customMeshSet) {
  103958. return;
  103959. }
  103960. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  103961. var material = isHovered ? hoverMaterial : _this._coloredMaterial;
  103962. _this._rootMesh.getChildMeshes().forEach(function (m) {
  103963. m.material = material;
  103964. if (m.color) {
  103965. m.color = material.emissiveColor;
  103966. }
  103967. });
  103968. });
  103969. return _this;
  103970. }
  103971. AxisScaleGizmo.prototype._attachedMeshChanged = function (value) {
  103972. if (this.dragBehavior) {
  103973. this.dragBehavior.enabled = value ? true : false;
  103974. }
  103975. };
  103976. /**
  103977. * Disposes of the gizmo
  103978. */
  103979. AxisScaleGizmo.prototype.dispose = function () {
  103980. this.onSnapObservable.clear();
  103981. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  103982. this.dragBehavior.detach();
  103983. _super.prototype.dispose.call(this);
  103984. };
  103985. /**
  103986. * Disposes and replaces the current meshes in the gizmo with the specified mesh
  103987. * @param mesh The mesh to replace the default mesh of the gizmo
  103988. * @param useGizmoMaterial If the gizmo's default material should be used (default: false)
  103989. */
  103990. AxisScaleGizmo.prototype.setCustomMesh = function (mesh, useGizmoMaterial) {
  103991. var _this = this;
  103992. if (useGizmoMaterial === void 0) { useGizmoMaterial = false; }
  103993. _super.prototype.setCustomMesh.call(this, mesh);
  103994. if (useGizmoMaterial) {
  103995. this._rootMesh.getChildMeshes().forEach(function (m) {
  103996. m.material = _this._coloredMaterial;
  103997. if (m.color) {
  103998. m.color = _this._coloredMaterial.emissiveColor;
  103999. }
  104000. });
  104001. this._customMeshSet = false;
  104002. }
  104003. };
  104004. return AxisScaleGizmo;
  104005. }(BABYLON.Gizmo));
  104006. BABYLON.AxisScaleGizmo = AxisScaleGizmo;
  104007. })(BABYLON || (BABYLON = {}));
  104008. //# sourceMappingURL=babylon.axisScaleGizmo.js.map
  104009. var BABYLON;
  104010. (function (BABYLON) {
  104011. /**
  104012. * Single plane rotation gizmo
  104013. */
  104014. var PlaneRotationGizmo = /** @class */ (function (_super) {
  104015. __extends(PlaneRotationGizmo, _super);
  104016. /**
  104017. * Creates a PlaneRotationGizmo
  104018. * @param gizmoLayer The utility layer the gizmo will be added to
  104019. * @param planeNormal The normal of the plane which the gizmo will be able to rotate on
  104020. * @param color The color of the gizmo
  104021. * @param tessellation Amount of tessellation to be used when creating rotation circles
  104022. */
  104023. function PlaneRotationGizmo(planeNormal, color, gizmoLayer, tessellation) {
  104024. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  104025. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  104026. if (tessellation === void 0) { tessellation = 32; }
  104027. var _this = _super.call(this, gizmoLayer) || this;
  104028. _this._pointerObserver = null;
  104029. /**
  104030. * Rotation distance in radians that the gizmo will snap to (Default: 0)
  104031. */
  104032. _this.snapDistance = 0;
  104033. /**
  104034. * Event that fires each time the gizmo snaps to a new location.
  104035. * * snapDistance is the the change in distance
  104036. */
  104037. _this.onSnapObservable = new BABYLON.Observable();
  104038. // Create Material
  104039. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  104040. coloredMaterial.disableLighting = true;
  104041. coloredMaterial.emissiveColor = color;
  104042. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  104043. hoverMaterial.disableLighting = true;
  104044. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  104045. // Build mesh on root node
  104046. var parentMesh = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  104047. // Create circle out of lines
  104048. var radius = 0.8;
  104049. var points = new Array();
  104050. for (var i = 0; i < tessellation; i++) {
  104051. var radian = (2 * Math.PI) * (i / (tessellation - 1));
  104052. points.push(new BABYLON.Vector3(radius * Math.sin(radian), 0, radius * Math.cos(radian)));
  104053. }
  104054. var rotationMesh = BABYLON.Mesh.CreateLines("", points, gizmoLayer.utilityLayerScene);
  104055. rotationMesh.color = coloredMaterial.emissiveColor;
  104056. // Position arrow pointing in its drag axis
  104057. rotationMesh.scaling.scaleInPlace(0.26);
  104058. rotationMesh.material = coloredMaterial;
  104059. rotationMesh.rotation.x = Math.PI / 2;
  104060. parentMesh.addChild(rotationMesh);
  104061. parentMesh.lookAt(_this._rootMesh.position.add(planeNormal));
  104062. _this._rootMesh.addChild(parentMesh);
  104063. parentMesh.scaling.scaleInPlace(1 / 3);
  104064. // Add drag behavior to handle events when the gizmo is dragged
  104065. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragPlaneNormal: planeNormal });
  104066. _this.dragBehavior.moveAttached = false;
  104067. _this.dragBehavior.maxDragAngle = Math.PI * 9 / 20;
  104068. _this.dragBehavior._useAlternatePickedPointAboveMaxDragAngle = true;
  104069. _this._rootMesh.addBehavior(_this.dragBehavior);
  104070. var lastDragPosition = new BABYLON.Vector3();
  104071. _this.dragBehavior.onDragStartObservable.add(function (e) {
  104072. if (_this.attachedMesh) {
  104073. lastDragPosition.copyFrom(e.dragPlanePoint);
  104074. }
  104075. });
  104076. var rotationMatrix = new BABYLON.Matrix();
  104077. var planeNormalTowardsCamera = new BABYLON.Vector3();
  104078. var localPlaneNormalTowardsCamera = new BABYLON.Vector3();
  104079. var tmpSnapEvent = { snapDistance: 0 };
  104080. var currentSnapDragDistance = 0;
  104081. var tmpMatrix = new BABYLON.Matrix();
  104082. var tmpVector = new BABYLON.Vector3();
  104083. var amountToRotate = new BABYLON.Quaternion();
  104084. _this.dragBehavior.onDragObservable.add(function (event) {
  104085. if (_this.attachedMesh) {
  104086. if (!_this.attachedMesh.rotationQuaternion) {
  104087. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  104088. }
  104089. // Calc angle over full 360 degree (https://stackoverflow.com/questions/43493711/the-angle-between-two-3d-vectors-with-a-result-range-0-360)
  104090. var newVector = event.dragPlanePoint.subtract(_this.attachedMesh.absolutePosition).normalize();
  104091. var originalVector = lastDragPosition.subtract(_this.attachedMesh.absolutePosition).normalize();
  104092. var cross = BABYLON.Vector3.Cross(newVector, originalVector);
  104093. var dot = BABYLON.Vector3.Dot(newVector, originalVector);
  104094. var angle = Math.atan2(cross.length(), dot);
  104095. planeNormalTowardsCamera.copyFrom(planeNormal);
  104096. localPlaneNormalTowardsCamera.copyFrom(planeNormal);
  104097. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  104098. _this.attachedMesh.rotationQuaternion.toRotationMatrix(rotationMatrix);
  104099. localPlaneNormalTowardsCamera = BABYLON.Vector3.TransformCoordinates(planeNormalTowardsCamera, rotationMatrix);
  104100. }
  104101. // Flip up vector depending on which side the camera is on
  104102. if (gizmoLayer.utilityLayerScene.activeCamera) {
  104103. var camVec = gizmoLayer.utilityLayerScene.activeCamera.position.subtract(_this.attachedMesh.position);
  104104. if (BABYLON.Vector3.Dot(camVec, localPlaneNormalTowardsCamera) > 0) {
  104105. planeNormalTowardsCamera.scaleInPlace(-1);
  104106. localPlaneNormalTowardsCamera.scaleInPlace(-1);
  104107. }
  104108. }
  104109. var halfCircleSide = BABYLON.Vector3.Dot(localPlaneNormalTowardsCamera, cross) > 0.0;
  104110. if (halfCircleSide) {
  104111. angle = -angle;
  104112. }
  104113. // Snapping logic
  104114. var snapped = false;
  104115. if (_this.snapDistance != 0) {
  104116. currentSnapDragDistance += angle;
  104117. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  104118. var dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  104119. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  104120. angle = _this.snapDistance * dragSteps;
  104121. snapped = true;
  104122. }
  104123. else {
  104124. angle = 0;
  104125. }
  104126. }
  104127. // If the mesh has a parent, convert needed world rotation to local rotation
  104128. tmpMatrix.reset();
  104129. if (_this.attachedMesh.parent) {
  104130. _this.attachedMesh.parent.computeWorldMatrix().invertToRef(tmpMatrix);
  104131. tmpMatrix.getRotationMatrixToRef(tmpMatrix);
  104132. BABYLON.Vector3.TransformCoordinatesToRef(planeNormalTowardsCamera, tmpMatrix, planeNormalTowardsCamera);
  104133. }
  104134. // Convert angle and axis to quaternion (http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm)
  104135. var quaternionCoefficient = Math.sin(angle / 2);
  104136. amountToRotate.set(planeNormalTowardsCamera.x * quaternionCoefficient, planeNormalTowardsCamera.y * quaternionCoefficient, planeNormalTowardsCamera.z * quaternionCoefficient, Math.cos(angle / 2));
  104137. // 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
  104138. if (tmpMatrix.determinant() > 0) {
  104139. amountToRotate.toEulerAnglesToRef(tmpVector);
  104140. BABYLON.Quaternion.RotationYawPitchRollToRef(tmpVector.y, -tmpVector.x, -tmpVector.z, amountToRotate);
  104141. }
  104142. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  104143. // Rotate selected mesh quaternion over fixed axis
  104144. _this.attachedMesh.rotationQuaternion.multiplyToRef(amountToRotate, _this.attachedMesh.rotationQuaternion);
  104145. }
  104146. else {
  104147. // Rotate selected mesh quaternion over rotated axis
  104148. amountToRotate.multiplyToRef(_this.attachedMesh.rotationQuaternion, _this.attachedMesh.rotationQuaternion);
  104149. }
  104150. lastDragPosition.copyFrom(event.dragPlanePoint);
  104151. if (snapped) {
  104152. tmpSnapEvent.snapDistance = angle;
  104153. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  104154. }
  104155. }
  104156. });
  104157. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  104158. if (_this._customMeshSet) {
  104159. return;
  104160. }
  104161. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  104162. var material = isHovered ? hoverMaterial : coloredMaterial;
  104163. _this._rootMesh.getChildMeshes().forEach(function (m) {
  104164. m.material = material;
  104165. if (m.color) {
  104166. m.color = material.emissiveColor;
  104167. }
  104168. });
  104169. });
  104170. return _this;
  104171. }
  104172. PlaneRotationGizmo.prototype._attachedMeshChanged = function (value) {
  104173. if (this.dragBehavior) {
  104174. this.dragBehavior.enabled = value ? true : false;
  104175. }
  104176. };
  104177. /**
  104178. * Disposes of the gizmo
  104179. */
  104180. PlaneRotationGizmo.prototype.dispose = function () {
  104181. this.onSnapObservable.clear();
  104182. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  104183. this.dragBehavior.detach();
  104184. _super.prototype.dispose.call(this);
  104185. };
  104186. return PlaneRotationGizmo;
  104187. }(BABYLON.Gizmo));
  104188. BABYLON.PlaneRotationGizmo = PlaneRotationGizmo;
  104189. })(BABYLON || (BABYLON = {}));
  104190. //# sourceMappingURL=babylon.planeRotationGizmo.js.map
  104191. var BABYLON;
  104192. (function (BABYLON) {
  104193. /**
  104194. * Gizmo that enables dragging a mesh along 3 axis
  104195. */
  104196. var PositionGizmo = /** @class */ (function (_super) {
  104197. __extends(PositionGizmo, _super);
  104198. /**
  104199. * Creates a PositionGizmo
  104200. * @param gizmoLayer The utility layer the gizmo will be added to
  104201. */
  104202. function PositionGizmo(gizmoLayer) {
  104203. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  104204. var _this = _super.call(this, gizmoLayer) || this;
  104205. /** Fires an event when any of it's sub gizmos are dragged */
  104206. _this.onDragStartObservable = new BABYLON.Observable();
  104207. /** Fires an event when any of it's sub gizmos are released from dragging */
  104208. _this.onDragEndObservable = new BABYLON.Observable();
  104209. _this.xGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  104210. _this.yGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  104211. _this.zGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  104212. // Relay drag events
  104213. [_this.xGizmo, _this.yGizmo, _this.zGizmo].forEach(function (gizmo) {
  104214. gizmo.dragBehavior.onDragStartObservable.add(function () {
  104215. _this.onDragStartObservable.notifyObservers({});
  104216. });
  104217. gizmo.dragBehavior.onDragEndObservable.add(function () {
  104218. _this.onDragEndObservable.notifyObservers({});
  104219. });
  104220. });
  104221. _this.attachedMesh = null;
  104222. return _this;
  104223. }
  104224. Object.defineProperty(PositionGizmo.prototype, "attachedMesh", {
  104225. set: function (mesh) {
  104226. if (this.xGizmo) {
  104227. this.xGizmo.attachedMesh = mesh;
  104228. this.yGizmo.attachedMesh = mesh;
  104229. this.zGizmo.attachedMesh = mesh;
  104230. }
  104231. },
  104232. enumerable: true,
  104233. configurable: true
  104234. });
  104235. Object.defineProperty(PositionGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  104236. get: function () {
  104237. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  104238. },
  104239. set: function (value) {
  104240. if (this.xGizmo) {
  104241. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  104242. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  104243. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  104244. }
  104245. },
  104246. enumerable: true,
  104247. configurable: true
  104248. });
  104249. Object.defineProperty(PositionGizmo.prototype, "snapDistance", {
  104250. get: function () {
  104251. return this.xGizmo.snapDistance;
  104252. },
  104253. /**
  104254. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  104255. */
  104256. set: function (value) {
  104257. if (this.xGizmo) {
  104258. this.xGizmo.snapDistance = value;
  104259. this.yGizmo.snapDistance = value;
  104260. this.zGizmo.snapDistance = value;
  104261. }
  104262. },
  104263. enumerable: true,
  104264. configurable: true
  104265. });
  104266. Object.defineProperty(PositionGizmo.prototype, "scaleRatio", {
  104267. get: function () {
  104268. return this.xGizmo.scaleRatio;
  104269. },
  104270. /**
  104271. * Ratio for the scale of the gizmo (Default: 1)
  104272. */
  104273. set: function (value) {
  104274. if (this.xGizmo) {
  104275. this.xGizmo.scaleRatio = value;
  104276. this.yGizmo.scaleRatio = value;
  104277. this.zGizmo.scaleRatio = value;
  104278. }
  104279. },
  104280. enumerable: true,
  104281. configurable: true
  104282. });
  104283. /**
  104284. * Disposes of the gizmo
  104285. */
  104286. PositionGizmo.prototype.dispose = function () {
  104287. this.xGizmo.dispose();
  104288. this.yGizmo.dispose();
  104289. this.zGizmo.dispose();
  104290. this.onDragStartObservable.clear();
  104291. this.onDragEndObservable.clear();
  104292. };
  104293. /**
  104294. * CustomMeshes are not supported by this gizmo
  104295. * @param mesh The mesh to replace the default mesh of the gizmo
  104296. */
  104297. PositionGizmo.prototype.setCustomMesh = function (mesh) {
  104298. 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)");
  104299. };
  104300. return PositionGizmo;
  104301. }(BABYLON.Gizmo));
  104302. BABYLON.PositionGizmo = PositionGizmo;
  104303. })(BABYLON || (BABYLON = {}));
  104304. //# sourceMappingURL=babylon.positionGizmo.js.map
  104305. var BABYLON;
  104306. (function (BABYLON) {
  104307. /**
  104308. * Gizmo that enables rotating a mesh along 3 axis
  104309. */
  104310. var RotationGizmo = /** @class */ (function (_super) {
  104311. __extends(RotationGizmo, _super);
  104312. /**
  104313. * Creates a RotationGizmo
  104314. * @param gizmoLayer The utility layer the gizmo will be added to
  104315. * @param tessellation Amount of tessellation to be used when creating rotation circles
  104316. */
  104317. function RotationGizmo(gizmoLayer, tessellation) {
  104318. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  104319. if (tessellation === void 0) { tessellation = 32; }
  104320. var _this = _super.call(this, gizmoLayer) || this;
  104321. /** Fires an event when any of it's sub gizmos are dragged */
  104322. _this.onDragStartObservable = new BABYLON.Observable();
  104323. /** Fires an event when any of it's sub gizmos are released from dragging */
  104324. _this.onDragEndObservable = new BABYLON.Observable();
  104325. _this.xGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer, tessellation);
  104326. _this.yGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer, tessellation);
  104327. _this.zGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer, tessellation);
  104328. // Relay drag events
  104329. [_this.xGizmo, _this.yGizmo, _this.zGizmo].forEach(function (gizmo) {
  104330. gizmo.dragBehavior.onDragStartObservable.add(function () {
  104331. _this.onDragStartObservable.notifyObservers({});
  104332. });
  104333. gizmo.dragBehavior.onDragEndObservable.add(function () {
  104334. _this.onDragEndObservable.notifyObservers({});
  104335. });
  104336. });
  104337. _this.attachedMesh = null;
  104338. return _this;
  104339. }
  104340. Object.defineProperty(RotationGizmo.prototype, "attachedMesh", {
  104341. set: function (mesh) {
  104342. if (this.xGizmo) {
  104343. this.xGizmo.attachedMesh = mesh;
  104344. this.yGizmo.attachedMesh = mesh;
  104345. this.zGizmo.attachedMesh = mesh;
  104346. }
  104347. },
  104348. enumerable: true,
  104349. configurable: true
  104350. });
  104351. Object.defineProperty(RotationGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  104352. get: function () {
  104353. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  104354. },
  104355. set: function (value) {
  104356. if (this.xGizmo) {
  104357. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  104358. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  104359. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  104360. }
  104361. },
  104362. enumerable: true,
  104363. configurable: true
  104364. });
  104365. Object.defineProperty(RotationGizmo.prototype, "snapDistance", {
  104366. get: function () {
  104367. return this.xGizmo.snapDistance;
  104368. },
  104369. /**
  104370. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  104371. */
  104372. set: function (value) {
  104373. if (this.xGizmo) {
  104374. this.xGizmo.snapDistance = value;
  104375. this.yGizmo.snapDistance = value;
  104376. this.zGizmo.snapDistance = value;
  104377. }
  104378. },
  104379. enumerable: true,
  104380. configurable: true
  104381. });
  104382. Object.defineProperty(RotationGizmo.prototype, "scaleRatio", {
  104383. get: function () {
  104384. return this.xGizmo.scaleRatio;
  104385. },
  104386. /**
  104387. * Ratio for the scale of the gizmo (Default: 1)
  104388. */
  104389. set: function (value) {
  104390. if (this.xGizmo) {
  104391. this.xGizmo.scaleRatio = value;
  104392. this.yGizmo.scaleRatio = value;
  104393. this.zGizmo.scaleRatio = value;
  104394. }
  104395. },
  104396. enumerable: true,
  104397. configurable: true
  104398. });
  104399. /**
  104400. * Disposes of the gizmo
  104401. */
  104402. RotationGizmo.prototype.dispose = function () {
  104403. this.xGizmo.dispose();
  104404. this.yGizmo.dispose();
  104405. this.zGizmo.dispose();
  104406. this.onDragStartObservable.clear();
  104407. this.onDragEndObservable.clear();
  104408. };
  104409. /**
  104410. * CustomMeshes are not supported by this gizmo
  104411. * @param mesh The mesh to replace the default mesh of the gizmo
  104412. */
  104413. RotationGizmo.prototype.setCustomMesh = function (mesh) {
  104414. 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)");
  104415. };
  104416. return RotationGizmo;
  104417. }(BABYLON.Gizmo));
  104418. BABYLON.RotationGizmo = RotationGizmo;
  104419. })(BABYLON || (BABYLON = {}));
  104420. //# sourceMappingURL=babylon.rotationGizmo.js.map
  104421. var BABYLON;
  104422. (function (BABYLON) {
  104423. /**
  104424. * Gizmo that enables scaling a mesh along 3 axis
  104425. */
  104426. var ScaleGizmo = /** @class */ (function (_super) {
  104427. __extends(ScaleGizmo, _super);
  104428. /**
  104429. * Creates a ScaleGizmo
  104430. * @param gizmoLayer The utility layer the gizmo will be added to
  104431. */
  104432. function ScaleGizmo(gizmoLayer) {
  104433. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  104434. var _this = _super.call(this, gizmoLayer) || this;
  104435. /** Fires an event when any of it's sub gizmos are dragged */
  104436. _this.onDragStartObservable = new BABYLON.Observable();
  104437. /** Fires an event when any of it's sub gizmos are released from dragging */
  104438. _this.onDragEndObservable = new BABYLON.Observable();
  104439. _this.xGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  104440. _this.yGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  104441. _this.zGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  104442. // Create uniform scale gizmo
  104443. _this.uniformScaleGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Yellow().scale(0.5), gizmoLayer);
  104444. _this.uniformScaleGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  104445. _this.uniformScaleGizmo.uniformScaling = true;
  104446. var uniformScalingMesh = BABYLON.Mesh.CreatePolyhedron("", { type: 1 }, _this.uniformScaleGizmo.gizmoLayer.utilityLayerScene);
  104447. uniformScalingMesh.scaling.scaleInPlace(0.02);
  104448. uniformScalingMesh.visibility = 0;
  104449. var octahedron = BABYLON.Mesh.CreatePolyhedron("", { type: 1 }, _this.uniformScaleGizmo.gizmoLayer.utilityLayerScene);
  104450. octahedron.scaling.scaleInPlace(0.007);
  104451. uniformScalingMesh.addChild(octahedron);
  104452. _this.uniformScaleGizmo.setCustomMesh(uniformScalingMesh, true);
  104453. // Relay drag events
  104454. [_this.xGizmo, _this.yGizmo, _this.zGizmo, _this.uniformScaleGizmo].forEach(function (gizmo) {
  104455. gizmo.dragBehavior.onDragStartObservable.add(function () {
  104456. _this.onDragStartObservable.notifyObservers({});
  104457. });
  104458. gizmo.dragBehavior.onDragEndObservable.add(function () {
  104459. _this.onDragEndObservable.notifyObservers({});
  104460. });
  104461. });
  104462. _this.attachedMesh = null;
  104463. return _this;
  104464. }
  104465. Object.defineProperty(ScaleGizmo.prototype, "attachedMesh", {
  104466. set: function (mesh) {
  104467. if (this.xGizmo) {
  104468. this.xGizmo.attachedMesh = mesh;
  104469. this.yGizmo.attachedMesh = mesh;
  104470. this.zGizmo.attachedMesh = mesh;
  104471. this.uniformScaleGizmo.attachedMesh = mesh;
  104472. }
  104473. },
  104474. enumerable: true,
  104475. configurable: true
  104476. });
  104477. Object.defineProperty(ScaleGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  104478. get: function () {
  104479. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  104480. },
  104481. set: function (value) {
  104482. if (!value) {
  104483. BABYLON.Tools.Warn("Setting updateGizmoRotationToMatchAttachedMesh = false on scaling gizmo is not supported.");
  104484. }
  104485. if (this.xGizmo) {
  104486. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  104487. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  104488. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  104489. }
  104490. },
  104491. enumerable: true,
  104492. configurable: true
  104493. });
  104494. Object.defineProperty(ScaleGizmo.prototype, "snapDistance", {
  104495. get: function () {
  104496. return this.xGizmo.snapDistance;
  104497. },
  104498. /**
  104499. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  104500. */
  104501. set: function (value) {
  104502. if (this.xGizmo) {
  104503. this.xGizmo.snapDistance = value;
  104504. this.yGizmo.snapDistance = value;
  104505. this.zGizmo.snapDistance = value;
  104506. this.uniformScaleGizmo.snapDistance = value;
  104507. }
  104508. },
  104509. enumerable: true,
  104510. configurable: true
  104511. });
  104512. Object.defineProperty(ScaleGizmo.prototype, "scaleRatio", {
  104513. get: function () {
  104514. return this.xGizmo.scaleRatio;
  104515. },
  104516. /**
  104517. * Ratio for the scale of the gizmo (Default: 1)
  104518. */
  104519. set: function (value) {
  104520. if (this.xGizmo) {
  104521. this.xGizmo.scaleRatio = value;
  104522. this.yGizmo.scaleRatio = value;
  104523. this.zGizmo.scaleRatio = value;
  104524. this.uniformScaleGizmo.scaleRatio = value;
  104525. }
  104526. },
  104527. enumerable: true,
  104528. configurable: true
  104529. });
  104530. /**
  104531. * Disposes of the gizmo
  104532. */
  104533. ScaleGizmo.prototype.dispose = function () {
  104534. this.xGizmo.dispose();
  104535. this.yGizmo.dispose();
  104536. this.zGizmo.dispose();
  104537. this.uniformScaleGizmo.dispose();
  104538. this.onDragStartObservable.clear();
  104539. this.onDragEndObservable.clear();
  104540. };
  104541. return ScaleGizmo;
  104542. }(BABYLON.Gizmo));
  104543. BABYLON.ScaleGizmo = ScaleGizmo;
  104544. })(BABYLON || (BABYLON = {}));
  104545. //# sourceMappingURL=babylon.scaleGizmo.js.map
  104546. var BABYLON;
  104547. (function (BABYLON) {
  104548. /**
  104549. * Bounding box gizmo
  104550. */
  104551. var BoundingBoxGizmo = /** @class */ (function (_super) {
  104552. __extends(BoundingBoxGizmo, _super);
  104553. /**
  104554. * Creates an BoundingBoxGizmo
  104555. * @param gizmoLayer The utility layer the gizmo will be added to
  104556. * @param color The color of the gizmo
  104557. */
  104558. function BoundingBoxGizmo(color, gizmoLayer) {
  104559. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  104560. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultKeepDepthUtilityLayer; }
  104561. var _this = _super.call(this, gizmoLayer) || this;
  104562. _this._boundingDimensions = new BABYLON.Vector3(1, 1, 1);
  104563. _this._renderObserver = null;
  104564. _this._pointerObserver = null;
  104565. _this._scaleDragSpeed = 0.2;
  104566. _this._tmpQuaternion = new BABYLON.Quaternion();
  104567. _this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  104568. _this._tmpRotationMatrix = new BABYLON.Matrix();
  104569. /**
  104570. * 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)
  104571. */
  104572. _this.ignoreChildren = false;
  104573. /**
  104574. * 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)
  104575. */
  104576. _this.includeChildPredicate = null;
  104577. /**
  104578. * The size of the rotation spheres attached to the bounding box (Default: 0.1)
  104579. */
  104580. _this.rotationSphereSize = 0.1;
  104581. /**
  104582. * The size of the scale boxes attached to the bounding box (Default: 0.1)
  104583. */
  104584. _this.scaleBoxSize = 0.1;
  104585. /**
  104586. * 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)
  104587. */
  104588. _this.fixedDragMeshScreenSize = false;
  104589. /**
  104590. * The distance away from the object which the draggable meshes should appear world sized when fixedDragMeshScreenSize is set to true (default: 10)
  104591. */
  104592. _this.fixedDragMeshScreenSizeDistanceFactor = 10;
  104593. /**
  104594. * Fired when a rotation sphere or scale box is dragged
  104595. */
  104596. _this.onDragStartObservable = new BABYLON.Observable();
  104597. /**
  104598. * Fired when a scale box is dragged
  104599. */
  104600. _this.onScaleBoxDragObservable = new BABYLON.Observable();
  104601. /**
  104602. * Fired when a scale box drag is ended
  104603. */
  104604. _this.onScaleBoxDragEndObservable = new BABYLON.Observable();
  104605. /**
  104606. * Fired when a rotation sphere is dragged
  104607. */
  104608. _this.onRotationSphereDragObservable = new BABYLON.Observable();
  104609. /**
  104610. * Fired when a rotation sphere drag is ended
  104611. */
  104612. _this.onRotationSphereDragEndObservable = new BABYLON.Observable();
  104613. /**
  104614. * 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)
  104615. */
  104616. _this.scalePivot = null;
  104617. _this._existingMeshScale = new BABYLON.Vector3();
  104618. // Dragging
  104619. _this._dragMesh = null;
  104620. _this.pointerDragBehavior = new BABYLON.PointerDragBehavior();
  104621. // Do not update the gizmo's scale so it has a fixed size to the object its attached to
  104622. _this._updateScale = false;
  104623. _this._anchorMesh = new BABYLON.AbstractMesh("anchor", gizmoLayer.utilityLayerScene);
  104624. // Create Materials
  104625. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  104626. coloredMaterial.disableLighting = true;
  104627. coloredMaterial.emissiveColor = color;
  104628. var hoverColoredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  104629. hoverColoredMaterial.disableLighting = true;
  104630. hoverColoredMaterial.emissiveColor = color.clone().add(new BABYLON.Color3(0.3, 0.3, 0.3));
  104631. // Build bounding box out of lines
  104632. _this._lineBoundingBox = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  104633. _this._lineBoundingBox.rotationQuaternion = new BABYLON.Quaternion();
  104634. var lines = [];
  104635. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0)] }, gizmoLayer.utilityLayerScene));
  104636. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  104637. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  104638. 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));
  104639. 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));
  104640. 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));
  104641. 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));
  104642. 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));
  104643. 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));
  104644. 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));
  104645. 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));
  104646. 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));
  104647. lines.forEach(function (l) {
  104648. l.color = color;
  104649. l.position.addInPlace(new BABYLON.Vector3(-_this._boundingDimensions.x / 2, -_this._boundingDimensions.y / 2, -_this._boundingDimensions.z / 2));
  104650. l.isPickable = false;
  104651. _this._lineBoundingBox.addChild(l);
  104652. });
  104653. _this._rootMesh.addChild(_this._lineBoundingBox);
  104654. // Create rotation spheres
  104655. _this._rotateSpheresParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  104656. _this._rotateSpheresParent.rotationQuaternion = new BABYLON.Quaternion();
  104657. var _loop_1 = function (i_1) {
  104658. var sphere = BABYLON.MeshBuilder.CreateSphere("", { diameter: 1 }, gizmoLayer.utilityLayerScene);
  104659. sphere.rotationQuaternion = new BABYLON.Quaternion();
  104660. sphere.material = coloredMaterial;
  104661. // Drag behavior
  104662. _dragBehavior = new BABYLON.PointerDragBehavior({});
  104663. _dragBehavior.moveAttached = false;
  104664. _dragBehavior.updateDragPlane = false;
  104665. sphere.addBehavior(_dragBehavior);
  104666. var startingTurnDirection = new BABYLON.Vector3(1, 0, 0);
  104667. var totalTurnAmountOfDrag = 0;
  104668. _dragBehavior.onDragStartObservable.add(function (event) {
  104669. startingTurnDirection.copyFrom(sphere.forward);
  104670. totalTurnAmountOfDrag = 0;
  104671. });
  104672. _dragBehavior.onDragObservable.add(function (event) {
  104673. _this.onRotationSphereDragObservable.notifyObservers({});
  104674. if (_this.attachedMesh) {
  104675. BoundingBoxGizmo._RemoveAndStorePivotPoint(_this.attachedMesh);
  104676. var worldDragDirection = startingTurnDirection;
  104677. // Project the world right on to the drag plane
  104678. var toSub = event.dragPlaneNormal.scale(BABYLON.Vector3.Dot(event.dragPlaneNormal, worldDragDirection));
  104679. var dragAxis = worldDragDirection.subtract(toSub).normalizeToNew();
  104680. // project drag delta on to the resulting drag axis and rotate based on that
  104681. var projectDist = BABYLON.Vector3.Dot(dragAxis, event.delta) < 0 ? Math.abs(event.delta.length()) : -Math.abs(event.delta.length());
  104682. // Make rotation relative to size of mesh.
  104683. projectDist = (projectDist / _this._boundingDimensions.length()) * _this._anchorMesh.scaling.length();
  104684. // Rotate based on axis
  104685. if (!_this.attachedMesh.rotationQuaternion) {
  104686. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  104687. }
  104688. if (!_this._anchorMesh.rotationQuaternion) {
  104689. _this._anchorMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._anchorMesh.rotation.y, _this._anchorMesh.rotation.x, _this._anchorMesh.rotation.z);
  104690. }
  104691. // Do not allow the object to turn more than a full circle
  104692. totalTurnAmountOfDrag += projectDist;
  104693. if (Math.abs(totalTurnAmountOfDrag) <= 2 * Math.PI) {
  104694. if (i_1 >= 8) {
  104695. BABYLON.Quaternion.RotationYawPitchRollToRef(0, 0, projectDist, _this._tmpQuaternion);
  104696. }
  104697. else if (i_1 >= 4) {
  104698. BABYLON.Quaternion.RotationYawPitchRollToRef(projectDist, 0, 0, _this._tmpQuaternion);
  104699. }
  104700. else {
  104701. BABYLON.Quaternion.RotationYawPitchRollToRef(0, projectDist, 0, _this._tmpQuaternion);
  104702. }
  104703. // Rotate around center of bounding box
  104704. _this._anchorMesh.addChild(_this.attachedMesh);
  104705. _this._anchorMesh.rotationQuaternion.multiplyToRef(_this._tmpQuaternion, _this._anchorMesh.rotationQuaternion);
  104706. _this._anchorMesh.removeChild(_this.attachedMesh);
  104707. }
  104708. _this.updateBoundingBox();
  104709. BoundingBoxGizmo._RestorePivotPoint(_this.attachedMesh);
  104710. }
  104711. _this._updateDummy();
  104712. });
  104713. // Selection/deselection
  104714. _dragBehavior.onDragStartObservable.add(function () {
  104715. _this.onDragStartObservable.notifyObservers({});
  104716. _this._selectNode(sphere);
  104717. });
  104718. _dragBehavior.onDragEndObservable.add(function () {
  104719. _this.onRotationSphereDragEndObservable.notifyObservers({});
  104720. _this._selectNode(null);
  104721. _this._updateDummy();
  104722. });
  104723. this_1._rotateSpheresParent.addChild(sphere);
  104724. };
  104725. var this_1 = this, _dragBehavior;
  104726. for (var i_1 = 0; i_1 < 12; i_1++) {
  104727. _loop_1(i_1);
  104728. }
  104729. _this._rootMesh.addChild(_this._rotateSpheresParent);
  104730. // Create scale cubes
  104731. _this._scaleBoxesParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  104732. _this._scaleBoxesParent.rotationQuaternion = new BABYLON.Quaternion();
  104733. for (var i = 0; i < 2; i++) {
  104734. for (var j = 0; j < 2; j++) {
  104735. var _loop_2 = function () {
  104736. var box = BABYLON.MeshBuilder.CreateBox("", { size: 1 }, gizmoLayer.utilityLayerScene);
  104737. box.material = coloredMaterial;
  104738. // Dragging logic
  104739. var dragAxis = new BABYLON.Vector3(i == 0 ? -1 : 1, j == 0 ? -1 : 1, k == 0 ? -1 : 1);
  104740. _dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  104741. _dragBehavior.moveAttached = false;
  104742. box.addBehavior(_dragBehavior);
  104743. _dragBehavior.onDragObservable.add(function (event) {
  104744. _this.onScaleBoxDragObservable.notifyObservers({});
  104745. if (_this.attachedMesh) {
  104746. BoundingBoxGizmo._RemoveAndStorePivotPoint(_this.attachedMesh);
  104747. var relativeDragDistance = (event.dragDistance / _this._boundingDimensions.length()) * _this._anchorMesh.scaling.length();
  104748. var deltaScale = new BABYLON.Vector3(relativeDragDistance, relativeDragDistance, relativeDragDistance);
  104749. deltaScale.scaleInPlace(_this._scaleDragSpeed);
  104750. _this.updateBoundingBox();
  104751. if (_this.scalePivot) {
  104752. _this.attachedMesh.getWorldMatrix().getRotationMatrixToRef(_this._tmpRotationMatrix);
  104753. // Move anchor to desired pivot point (Bottom left corner + dimension/2)
  104754. _this._boundingDimensions.scaleToRef(0.5, _this._tmpVector);
  104755. BABYLON.Vector3.TransformCoordinatesToRef(_this._tmpVector, _this._tmpRotationMatrix, _this._tmpVector);
  104756. _this._anchorMesh.position.subtractInPlace(_this._tmpVector);
  104757. _this._boundingDimensions.multiplyToRef(_this.scalePivot, _this._tmpVector);
  104758. BABYLON.Vector3.TransformCoordinatesToRef(_this._tmpVector, _this._tmpRotationMatrix, _this._tmpVector);
  104759. _this._anchorMesh.position.addInPlace(_this._tmpVector);
  104760. }
  104761. else {
  104762. // Scale from the position of the opposite corner
  104763. box.absolutePosition.subtractToRef(_this._anchorMesh.position, _this._tmpVector);
  104764. _this._anchorMesh.position.subtractInPlace(_this._tmpVector);
  104765. }
  104766. _this._anchorMesh.addChild(_this.attachedMesh);
  104767. _this._anchorMesh.scaling.addInPlace(deltaScale);
  104768. if (_this._anchorMesh.scaling.x < 0 || _this._anchorMesh.scaling.y < 0 || _this._anchorMesh.scaling.z < 0) {
  104769. _this._anchorMesh.scaling.subtractInPlace(deltaScale);
  104770. }
  104771. _this._anchorMesh.removeChild(_this.attachedMesh);
  104772. BoundingBoxGizmo._RestorePivotPoint(_this.attachedMesh);
  104773. }
  104774. _this._updateDummy();
  104775. });
  104776. // Selection/deselection
  104777. _dragBehavior.onDragStartObservable.add(function () {
  104778. _this.onDragStartObservable.notifyObservers({});
  104779. _this._selectNode(box);
  104780. });
  104781. _dragBehavior.onDragEndObservable.add(function () {
  104782. _this.onScaleBoxDragEndObservable.notifyObservers({});
  104783. _this._selectNode(null);
  104784. _this._updateDummy();
  104785. });
  104786. this_2._scaleBoxesParent.addChild(box);
  104787. };
  104788. var this_2 = this, _dragBehavior;
  104789. for (var k = 0; k < 2; k++) {
  104790. _loop_2();
  104791. }
  104792. }
  104793. }
  104794. _this._rootMesh.addChild(_this._scaleBoxesParent);
  104795. // Hover color change
  104796. var pointerIds = new Array();
  104797. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  104798. if (!pointerIds[pointerInfo.event.pointerId]) {
  104799. _this._rotateSpheresParent.getChildMeshes().concat(_this._scaleBoxesParent.getChildMeshes()).forEach(function (mesh) {
  104800. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh == mesh) {
  104801. pointerIds[pointerInfo.event.pointerId] = mesh;
  104802. mesh.material = hoverColoredMaterial;
  104803. }
  104804. });
  104805. }
  104806. else {
  104807. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh != pointerIds[pointerInfo.event.pointerId]) {
  104808. pointerIds[pointerInfo.event.pointerId].material = coloredMaterial;
  104809. delete pointerIds[pointerInfo.event.pointerId];
  104810. }
  104811. }
  104812. });
  104813. // Update bounding box positions
  104814. _this._renderObserver = _this.gizmoLayer.originalScene.onBeforeRenderObservable.add(function () {
  104815. // Only update the bouding box if scaling has changed
  104816. if (_this.attachedMesh && !_this._existingMeshScale.equals(_this.attachedMesh.scaling)) {
  104817. _this.updateBoundingBox();
  104818. }
  104819. else if (_this.fixedDragMeshScreenSize) {
  104820. _this._updateRotationSpheres();
  104821. _this._updateScaleBoxes();
  104822. }
  104823. // If dragg mesh is enabled and dragging, update the attached mesh pose to match the drag mesh
  104824. if (_this._dragMesh && _this.attachedMesh && _this.pointerDragBehavior.dragging) {
  104825. _this._lineBoundingBox.position.rotateByQuaternionToRef(_this._rootMesh.rotationQuaternion, _this._tmpVector);
  104826. _this.attachedMesh.setAbsolutePosition(_this._dragMesh.position.add(_this._tmpVector.scale(-1)));
  104827. }
  104828. });
  104829. _this.updateBoundingBox();
  104830. return _this;
  104831. }
  104832. /** @hidden */
  104833. BoundingBoxGizmo._RemoveAndStorePivotPoint = function (mesh) {
  104834. if (mesh && BoundingBoxGizmo._PivotCached === 0) {
  104835. // Save old pivot and set pivot to 0,0,0
  104836. mesh.getPivotPointToRef(BoundingBoxGizmo._OldPivotPoint);
  104837. if (!BoundingBoxGizmo._OldPivotPoint.equalsToFloats(0, 0, 0)) {
  104838. mesh.setPivotMatrix(BABYLON.Matrix.IdentityReadOnly);
  104839. BoundingBoxGizmo._OldPivotPoint.subtractToRef(mesh.getPivotPoint(), BoundingBoxGizmo._PivotTranslation);
  104840. BoundingBoxGizmo._PivotTmpVector.copyFromFloats(1, 1, 1);
  104841. BoundingBoxGizmo._PivotTmpVector.subtractInPlace(mesh.scaling);
  104842. BoundingBoxGizmo._PivotTmpVector.multiplyInPlace(BoundingBoxGizmo._PivotTranslation);
  104843. mesh.position.addInPlace(BoundingBoxGizmo._PivotTmpVector);
  104844. }
  104845. }
  104846. BoundingBoxGizmo._PivotCached++;
  104847. };
  104848. /** @hidden */
  104849. BoundingBoxGizmo._RestorePivotPoint = function (mesh) {
  104850. if (mesh && !BoundingBoxGizmo._OldPivotPoint.equalsToFloats(0, 0, 0) && BoundingBoxGizmo._PivotCached === 1) {
  104851. mesh.setPivotPoint(BoundingBoxGizmo._OldPivotPoint);
  104852. BoundingBoxGizmo._PivotTmpVector.copyFromFloats(1, 1, 1);
  104853. BoundingBoxGizmo._PivotTmpVector.subtractInPlace(mesh.scaling);
  104854. BoundingBoxGizmo._PivotTmpVector.multiplyInPlace(BoundingBoxGizmo._PivotTranslation);
  104855. mesh.position.subtractInPlace(BoundingBoxGizmo._PivotTmpVector);
  104856. }
  104857. this._PivotCached--;
  104858. };
  104859. BoundingBoxGizmo.prototype._attachedMeshChanged = function (value) {
  104860. var _this = this;
  104861. if (value) {
  104862. // Reset anchor mesh to match attached mesh's scale
  104863. // This is needed to avoid invalid box/sphere position on first drag
  104864. BoundingBoxGizmo._RemoveAndStorePivotPoint(value);
  104865. this._anchorMesh.addChild(value);
  104866. this._anchorMesh.removeChild(value);
  104867. BoundingBoxGizmo._RestorePivotPoint(value);
  104868. this.updateBoundingBox();
  104869. this.gizmoLayer.utilityLayerScene.onAfterRenderObservable.addOnce(function () {
  104870. _this._updateDummy();
  104871. });
  104872. }
  104873. };
  104874. BoundingBoxGizmo.prototype._selectNode = function (selectedMesh) {
  104875. this._rotateSpheresParent.getChildMeshes()
  104876. .concat(this._scaleBoxesParent.getChildMeshes()).forEach(function (m, i) {
  104877. m.isVisible = (!selectedMesh || m == selectedMesh);
  104878. });
  104879. };
  104880. /**
  104881. * Updates the bounding box information for the Gizmo
  104882. */
  104883. BoundingBoxGizmo.prototype.updateBoundingBox = function () {
  104884. if (this.attachedMesh) {
  104885. BoundingBoxGizmo._RemoveAndStorePivotPoint(this.attachedMesh);
  104886. this._update();
  104887. // Rotate based on axis
  104888. if (!this.attachedMesh.rotationQuaternion) {
  104889. this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.attachedMesh.rotation.y, this.attachedMesh.rotation.x, this.attachedMesh.rotation.z);
  104890. }
  104891. if (!this._anchorMesh.rotationQuaternion) {
  104892. this._anchorMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this._anchorMesh.rotation.y, this._anchorMesh.rotation.x, this._anchorMesh.rotation.z);
  104893. }
  104894. this._anchorMesh.rotationQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  104895. // Store original position and reset mesh to origin before computing the bounding box
  104896. this._tmpQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  104897. this._tmpVector.copyFrom(this.attachedMesh.position);
  104898. this.attachedMesh.rotationQuaternion.set(0, 0, 0, 1);
  104899. this.attachedMesh.position.set(0, 0, 0);
  104900. // Update bounding dimensions/positions
  104901. var boundingMinMax = this.attachedMesh.getHierarchyBoundingVectors(!this.ignoreChildren, this.includeChildPredicate);
  104902. boundingMinMax.max.subtractToRef(boundingMinMax.min, this._boundingDimensions);
  104903. // Update gizmo to match bounding box scaling and rotation
  104904. this._lineBoundingBox.scaling.copyFrom(this._boundingDimensions);
  104905. 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);
  104906. this._rotateSpheresParent.position.copyFrom(this._lineBoundingBox.position);
  104907. this._scaleBoxesParent.position.copyFrom(this._lineBoundingBox.position);
  104908. this._lineBoundingBox.computeWorldMatrix();
  104909. this._anchorMesh.position.copyFrom(this._lineBoundingBox.absolutePosition);
  104910. // restore position/rotation values
  104911. this.attachedMesh.rotationQuaternion.copyFrom(this._tmpQuaternion);
  104912. this.attachedMesh.position.copyFrom(this._tmpVector);
  104913. }
  104914. this._updateRotationSpheres();
  104915. this._updateScaleBoxes();
  104916. if (this.attachedMesh) {
  104917. this._existingMeshScale.copyFrom(this.attachedMesh.scaling);
  104918. BoundingBoxGizmo._RestorePivotPoint(this.attachedMesh);
  104919. }
  104920. };
  104921. BoundingBoxGizmo.prototype._updateRotationSpheres = function () {
  104922. var rotateSpheres = this._rotateSpheresParent.getChildMeshes();
  104923. for (var i = 0; i < 3; i++) {
  104924. for (var j = 0; j < 2; j++) {
  104925. for (var k = 0; k < 2; k++) {
  104926. var index = ((i * 4) + (j * 2)) + k;
  104927. if (i == 0) {
  104928. rotateSpheres[index].position.set(this._boundingDimensions.x / 2, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  104929. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  104930. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(rotateSpheres[index].position.normalizeToNew(), BABYLON.Vector3.Right()).normalizeToNew().add(rotateSpheres[index].position));
  104931. }
  104932. if (i == 1) {
  104933. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y / 2, this._boundingDimensions.z * k);
  104934. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  104935. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(rotateSpheres[index].position.normalizeToNew(), BABYLON.Vector3.Up()).normalizeToNew().add(rotateSpheres[index].position));
  104936. }
  104937. if (i == 2) {
  104938. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y * k, this._boundingDimensions.z / 2);
  104939. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  104940. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(rotateSpheres[index].position.normalizeToNew(), BABYLON.Vector3.Forward()).normalizeToNew().add(rotateSpheres[index].position));
  104941. }
  104942. if (this.fixedDragMeshScreenSize && this.gizmoLayer.utilityLayerScene.activeCamera) {
  104943. rotateSpheres[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  104944. var distanceFromCamera = this.rotationSphereSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  104945. rotateSpheres[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  104946. }
  104947. else {
  104948. rotateSpheres[index].scaling.set(this.rotationSphereSize, this.rotationSphereSize, this.rotationSphereSize);
  104949. }
  104950. }
  104951. }
  104952. }
  104953. };
  104954. BoundingBoxGizmo.prototype._updateScaleBoxes = function () {
  104955. var scaleBoxes = this._scaleBoxesParent.getChildMeshes();
  104956. for (var i = 0; i < 2; i++) {
  104957. for (var j = 0; j < 2; j++) {
  104958. for (var k = 0; k < 2; k++) {
  104959. var index = ((i * 4) + (j * 2)) + k;
  104960. if (scaleBoxes[index]) {
  104961. scaleBoxes[index].position.set(this._boundingDimensions.x * i, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  104962. scaleBoxes[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  104963. if (this.fixedDragMeshScreenSize && this.gizmoLayer.utilityLayerScene.activeCamera) {
  104964. scaleBoxes[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  104965. var distanceFromCamera = this.scaleBoxSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  104966. scaleBoxes[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  104967. }
  104968. else {
  104969. scaleBoxes[index].scaling.set(this.scaleBoxSize, this.scaleBoxSize, this.scaleBoxSize);
  104970. }
  104971. }
  104972. }
  104973. }
  104974. }
  104975. };
  104976. /**
  104977. * Enables rotation on the specified axis and disables rotation on the others
  104978. * @param axis The list of axis that should be enabled (eg. "xy" or "xyz")
  104979. */
  104980. BoundingBoxGizmo.prototype.setEnabledRotationAxis = function (axis) {
  104981. this._rotateSpheresParent.getChildMeshes().forEach(function (m, i) {
  104982. if (i < 4) {
  104983. m.setEnabled(axis.indexOf("x") != -1);
  104984. }
  104985. else if (i < 8) {
  104986. m.setEnabled(axis.indexOf("y") != -1);
  104987. }
  104988. else {
  104989. m.setEnabled(axis.indexOf("z") != -1);
  104990. }
  104991. });
  104992. };
  104993. BoundingBoxGizmo.prototype._updateDummy = function () {
  104994. if (this._dragMesh) {
  104995. this._dragMesh.position.copyFrom(this._lineBoundingBox.getAbsolutePosition());
  104996. this._dragMesh.scaling.copyFrom(this._lineBoundingBox.scaling);
  104997. this._dragMesh.rotationQuaternion.copyFrom(this._rootMesh.rotationQuaternion);
  104998. }
  104999. };
  105000. /**
  105001. * Enables a pointer drag behavior on the bounding box of the gizmo
  105002. */
  105003. BoundingBoxGizmo.prototype.enableDragBehavior = function () {
  105004. this._dragMesh = BABYLON.Mesh.CreateBox("dummy", 1, this.gizmoLayer.utilityLayerScene);
  105005. this._dragMesh.visibility = 0;
  105006. this._dragMesh.rotationQuaternion = new BABYLON.Quaternion();
  105007. this.pointerDragBehavior.useObjectOrienationForDragging = false;
  105008. this._dragMesh.addBehavior(this.pointerDragBehavior);
  105009. };
  105010. /**
  105011. * Disposes of the gizmo
  105012. */
  105013. BoundingBoxGizmo.prototype.dispose = function () {
  105014. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  105015. this.gizmoLayer.originalScene.onBeforeRenderObservable.remove(this._renderObserver);
  105016. this._lineBoundingBox.dispose();
  105017. this._rotateSpheresParent.dispose();
  105018. this._scaleBoxesParent.dispose();
  105019. if (this._dragMesh) {
  105020. this._dragMesh.dispose();
  105021. }
  105022. _super.prototype.dispose.call(this);
  105023. };
  105024. /**
  105025. * 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)
  105026. * @param mesh the mesh to wrap in the bounding box mesh and make not pickable
  105027. * @returns the bounding box mesh with the passed in mesh as a child
  105028. */
  105029. BoundingBoxGizmo.MakeNotPickableAndWrapInBoundingBox = function (mesh) {
  105030. var makeNotPickable = function (root) {
  105031. root.isPickable = false;
  105032. root.getChildMeshes().forEach(function (c) {
  105033. makeNotPickable(c);
  105034. });
  105035. };
  105036. makeNotPickable(mesh);
  105037. // Reset position to get boudning box from origin with no rotation
  105038. if (!mesh.rotationQuaternion) {
  105039. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  105040. }
  105041. var oldPos = mesh.position.clone();
  105042. var oldRot = mesh.rotationQuaternion.clone();
  105043. mesh.rotationQuaternion.set(0, 0, 0, 1);
  105044. mesh.position.set(0, 0, 0);
  105045. // Update bounding dimensions/positions
  105046. var box = BABYLON.MeshBuilder.CreateBox("box", { size: 1 }, mesh.getScene());
  105047. var boundingMinMax = mesh.getHierarchyBoundingVectors();
  105048. boundingMinMax.max.subtractToRef(boundingMinMax.min, box.scaling);
  105049. // Adjust scale to avoid undefined behavior when adding child
  105050. if (box.scaling.y === 0) {
  105051. box.scaling.y = BABYLON.Epsilon;
  105052. }
  105053. if (box.scaling.x === 0) {
  105054. box.scaling.x = BABYLON.Epsilon;
  105055. }
  105056. if (box.scaling.z === 0) {
  105057. box.scaling.z = BABYLON.Epsilon;
  105058. }
  105059. box.position.set((boundingMinMax.max.x + boundingMinMax.min.x) / 2, (boundingMinMax.max.y + boundingMinMax.min.y) / 2, (boundingMinMax.max.z + boundingMinMax.min.z) / 2);
  105060. // Restore original positions
  105061. mesh.addChild(box);
  105062. mesh.rotationQuaternion.copyFrom(oldRot);
  105063. mesh.position.copyFrom(oldPos);
  105064. // Reverse parenting
  105065. mesh.removeChild(box);
  105066. box.addChild(mesh);
  105067. box.visibility = 0;
  105068. return box;
  105069. };
  105070. /**
  105071. * CustomMeshes are not supported by this gizmo
  105072. * @param mesh The mesh to replace the default mesh of the gizmo
  105073. */
  105074. BoundingBoxGizmo.prototype.setCustomMesh = function (mesh) {
  105075. BABYLON.Tools.Error("Custom meshes are not supported on this gizmo");
  105076. };
  105077. // Stores the state of the pivot cache (_oldPivotPoint, _pivotTranslation)
  105078. // store/remove pivot point should only be applied during their outermost calls
  105079. BoundingBoxGizmo._PivotCached = 0;
  105080. BoundingBoxGizmo._OldPivotPoint = new BABYLON.Vector3();
  105081. BoundingBoxGizmo._PivotTranslation = new BABYLON.Vector3();
  105082. BoundingBoxGizmo._PivotTmpVector = new BABYLON.Vector3();
  105083. return BoundingBoxGizmo;
  105084. }(BABYLON.Gizmo));
  105085. BABYLON.BoundingBoxGizmo = BoundingBoxGizmo;
  105086. })(BABYLON || (BABYLON = {}));
  105087. //# sourceMappingURL=babylon.boundingBoxGizmo.js.map
  105088. var BABYLON;
  105089. (function (BABYLON) {
  105090. /**
  105091. * Helps setup gizmo's in the scene to rotate/scale/position meshes
  105092. */
  105093. var GizmoManager = /** @class */ (function () {
  105094. /**
  105095. * Instatiates a gizmo manager
  105096. * @param scene the scene to overlay the gizmos on top of
  105097. */
  105098. function GizmoManager(scene) {
  105099. var _this = this;
  105100. this.scene = scene;
  105101. /** When true, the gizmo will be detached from the current object when a pointer down occurs with an empty picked mesh */
  105102. this.clearGizmoOnEmptyPointerEvent = false;
  105103. /** Fires an event when the manager is attached to a mesh */
  105104. this.onAttachedToMeshObservable = new BABYLON.Observable();
  105105. this._gizmosEnabled = { positionGizmo: false, rotationGizmo: false, scaleGizmo: false, boundingBoxGizmo: false };
  105106. this._pointerObserver = null;
  105107. this._attachedMesh = null;
  105108. this._boundingBoxColor = BABYLON.Color3.FromHexString("#0984e3");
  105109. /**
  105110. * When bounding box gizmo is enabled, this can be used to track drag/end events
  105111. */
  105112. this.boundingBoxDragBehavior = new BABYLON.SixDofDragBehavior();
  105113. /**
  105114. * Array of meshes which will have the gizmo attached when a pointer selected them. If null, all meshes are attachable. (Default: null)
  105115. */
  105116. this.attachableMeshes = null;
  105117. /**
  105118. * If pointer events should perform attaching/detaching a gizmo, if false this can be done manually via attachToMesh. (Default: true)
  105119. */
  105120. this.usePointerToAttachGizmos = true;
  105121. this._defaultKeepDepthUtilityLayer = new BABYLON.UtilityLayerRenderer(scene);
  105122. this._defaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil = false;
  105123. this._defaultUtilityLayer = new BABYLON.UtilityLayerRenderer(scene);
  105124. this.gizmos = { positionGizmo: null, rotationGizmo: null, scaleGizmo: null, boundingBoxGizmo: null };
  105125. // Instatiate/dispose gizmos based on pointer actions
  105126. this._pointerObserver = scene.onPointerObservable.add(function (pointerInfo, state) {
  105127. if (!_this.usePointerToAttachGizmos) {
  105128. return;
  105129. }
  105130. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  105131. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh) {
  105132. var node = pointerInfo.pickInfo.pickedMesh;
  105133. if (_this.attachableMeshes == null) {
  105134. // Attach to the most parent node
  105135. while (node && node.parent != null) {
  105136. node = node.parent;
  105137. }
  105138. }
  105139. else {
  105140. // Attach to the parent node that is an attachableMesh
  105141. var found = false;
  105142. _this.attachableMeshes.forEach(function (mesh) {
  105143. if (node && (node == mesh || node.isDescendantOf(mesh))) {
  105144. node = mesh;
  105145. found = true;
  105146. }
  105147. });
  105148. if (!found) {
  105149. node = null;
  105150. }
  105151. }
  105152. if (node instanceof BABYLON.AbstractMesh) {
  105153. if (_this._attachedMesh != node) {
  105154. _this.attachToMesh(node);
  105155. }
  105156. }
  105157. else {
  105158. if (_this.clearGizmoOnEmptyPointerEvent) {
  105159. _this.attachToMesh(null);
  105160. }
  105161. }
  105162. }
  105163. else {
  105164. if (_this.clearGizmoOnEmptyPointerEvent) {
  105165. _this.attachToMesh(null);
  105166. }
  105167. }
  105168. }
  105169. });
  105170. }
  105171. /**
  105172. * Attaches a set of gizmos to the specified mesh
  105173. * @param mesh The mesh the gizmo's should be attached to
  105174. */
  105175. GizmoManager.prototype.attachToMesh = function (mesh) {
  105176. if (this._attachedMesh) {
  105177. this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior);
  105178. }
  105179. this._attachedMesh = mesh;
  105180. for (var key in this.gizmos) {
  105181. var gizmo = (this.gizmos[key]);
  105182. if (gizmo && this._gizmosEnabled[key]) {
  105183. gizmo.attachedMesh = mesh;
  105184. }
  105185. }
  105186. if (this.boundingBoxGizmoEnabled && this._attachedMesh) {
  105187. this._attachedMesh.addBehavior(this.boundingBoxDragBehavior);
  105188. }
  105189. this.onAttachedToMeshObservable.notifyObservers(mesh);
  105190. };
  105191. Object.defineProperty(GizmoManager.prototype, "positionGizmoEnabled", {
  105192. get: function () {
  105193. return this._gizmosEnabled.positionGizmo;
  105194. },
  105195. /**
  105196. * If the position gizmo is enabled
  105197. */
  105198. set: function (value) {
  105199. if (value) {
  105200. if (!this.gizmos.positionGizmo) {
  105201. this.gizmos.positionGizmo = new BABYLON.PositionGizmo(this._defaultUtilityLayer);
  105202. }
  105203. this.gizmos.positionGizmo.attachedMesh = this._attachedMesh;
  105204. }
  105205. else if (this.gizmos.positionGizmo) {
  105206. this.gizmos.positionGizmo.attachedMesh = null;
  105207. }
  105208. this._gizmosEnabled.positionGizmo = value;
  105209. },
  105210. enumerable: true,
  105211. configurable: true
  105212. });
  105213. Object.defineProperty(GizmoManager.prototype, "rotationGizmoEnabled", {
  105214. get: function () {
  105215. return this._gizmosEnabled.rotationGizmo;
  105216. },
  105217. /**
  105218. * If the rotation gizmo is enabled
  105219. */
  105220. set: function (value) {
  105221. if (value) {
  105222. if (!this.gizmos.rotationGizmo) {
  105223. this.gizmos.rotationGizmo = new BABYLON.RotationGizmo(this._defaultUtilityLayer);
  105224. }
  105225. this.gizmos.rotationGizmo.attachedMesh = this._attachedMesh;
  105226. }
  105227. else if (this.gizmos.rotationGizmo) {
  105228. this.gizmos.rotationGizmo.attachedMesh = null;
  105229. }
  105230. this._gizmosEnabled.rotationGizmo = value;
  105231. },
  105232. enumerable: true,
  105233. configurable: true
  105234. });
  105235. Object.defineProperty(GizmoManager.prototype, "scaleGizmoEnabled", {
  105236. get: function () {
  105237. return this._gizmosEnabled.scaleGizmo;
  105238. },
  105239. /**
  105240. * If the scale gizmo is enabled
  105241. */
  105242. set: function (value) {
  105243. if (value) {
  105244. this.gizmos.scaleGizmo = this.gizmos.scaleGizmo || new BABYLON.ScaleGizmo(this._defaultUtilityLayer);
  105245. this.gizmos.scaleGizmo.attachedMesh = this._attachedMesh;
  105246. }
  105247. else if (this.gizmos.scaleGizmo) {
  105248. this.gizmos.scaleGizmo.attachedMesh = null;
  105249. }
  105250. this._gizmosEnabled.scaleGizmo = value;
  105251. },
  105252. enumerable: true,
  105253. configurable: true
  105254. });
  105255. Object.defineProperty(GizmoManager.prototype, "boundingBoxGizmoEnabled", {
  105256. get: function () {
  105257. return this._gizmosEnabled.boundingBoxGizmo;
  105258. },
  105259. /**
  105260. * If the boundingBox gizmo is enabled
  105261. */
  105262. set: function (value) {
  105263. if (value) {
  105264. this.gizmos.boundingBoxGizmo = this.gizmos.boundingBoxGizmo || new BABYLON.BoundingBoxGizmo(this._boundingBoxColor, this._defaultKeepDepthUtilityLayer);
  105265. this.gizmos.boundingBoxGizmo.attachedMesh = this._attachedMesh;
  105266. if (this._attachedMesh) {
  105267. this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior);
  105268. this._attachedMesh.addBehavior(this.boundingBoxDragBehavior);
  105269. }
  105270. }
  105271. else if (this.gizmos.boundingBoxGizmo) {
  105272. this.gizmos.boundingBoxGizmo.attachedMesh = null;
  105273. }
  105274. this._gizmosEnabled.boundingBoxGizmo = value;
  105275. },
  105276. enumerable: true,
  105277. configurable: true
  105278. });
  105279. /**
  105280. * Disposes of the gizmo manager
  105281. */
  105282. GizmoManager.prototype.dispose = function () {
  105283. this.scene.onPointerObservable.remove(this._pointerObserver);
  105284. for (var key in this.gizmos) {
  105285. var gizmo = (this.gizmos[key]);
  105286. if (gizmo) {
  105287. gizmo.dispose();
  105288. }
  105289. }
  105290. this._defaultKeepDepthUtilityLayer.dispose();
  105291. this._defaultUtilityLayer.dispose();
  105292. this.boundingBoxDragBehavior.detach();
  105293. this.onAttachedToMeshObservable.clear();
  105294. };
  105295. return GizmoManager;
  105296. }());
  105297. BABYLON.GizmoManager = GizmoManager;
  105298. })(BABYLON || (BABYLON = {}));
  105299. //# sourceMappingURL=babylon.gizmoManager.js.map
  105300. var BABYLON;
  105301. (function (BABYLON) {
  105302. /**
  105303. * Defines a target to use with MorphTargetManager
  105304. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  105305. */
  105306. var MorphTarget = /** @class */ (function () {
  105307. /**
  105308. * Creates a new MorphTarget
  105309. * @param name defines the name of the target
  105310. * @param influence defines the influence to use
  105311. */
  105312. function MorphTarget(
  105313. /** defines the name of the target */
  105314. name, influence, scene) {
  105315. if (influence === void 0) { influence = 0; }
  105316. if (scene === void 0) { scene = null; }
  105317. this.name = name;
  105318. /**
  105319. * Gets or sets the list of animations
  105320. */
  105321. this.animations = new Array();
  105322. this._positions = null;
  105323. this._normals = null;
  105324. this._tangents = null;
  105325. /**
  105326. * Observable raised when the influence changes
  105327. */
  105328. this.onInfluenceChanged = new BABYLON.Observable();
  105329. /** @hidden */
  105330. this._onDataLayoutChanged = new BABYLON.Observable();
  105331. this._animationPropertiesOverride = null;
  105332. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  105333. this.influence = influence;
  105334. }
  105335. Object.defineProperty(MorphTarget.prototype, "influence", {
  105336. /**
  105337. * Gets or sets the influence of this target (ie. its weight in the overall morphing)
  105338. */
  105339. get: function () {
  105340. return this._influence;
  105341. },
  105342. set: function (influence) {
  105343. if (this._influence === influence) {
  105344. return;
  105345. }
  105346. var previous = this._influence;
  105347. this._influence = influence;
  105348. if (this.onInfluenceChanged.hasObservers) {
  105349. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  105350. }
  105351. },
  105352. enumerable: true,
  105353. configurable: true
  105354. });
  105355. Object.defineProperty(MorphTarget.prototype, "animationPropertiesOverride", {
  105356. /**
  105357. * Gets or sets the animation properties override
  105358. */
  105359. get: function () {
  105360. if (!this._animationPropertiesOverride && this._scene) {
  105361. return this._scene.animationPropertiesOverride;
  105362. }
  105363. return this._animationPropertiesOverride;
  105364. },
  105365. set: function (value) {
  105366. this._animationPropertiesOverride = value;
  105367. },
  105368. enumerable: true,
  105369. configurable: true
  105370. });
  105371. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  105372. /**
  105373. * Gets a boolean defining if the target contains position data
  105374. */
  105375. get: function () {
  105376. return !!this._positions;
  105377. },
  105378. enumerable: true,
  105379. configurable: true
  105380. });
  105381. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  105382. /**
  105383. * Gets a boolean defining if the target contains normal data
  105384. */
  105385. get: function () {
  105386. return !!this._normals;
  105387. },
  105388. enumerable: true,
  105389. configurable: true
  105390. });
  105391. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  105392. /**
  105393. * Gets a boolean defining if the target contains tangent data
  105394. */
  105395. get: function () {
  105396. return !!this._tangents;
  105397. },
  105398. enumerable: true,
  105399. configurable: true
  105400. });
  105401. /**
  105402. * Affects position data to this target
  105403. * @param data defines the position data to use
  105404. */
  105405. MorphTarget.prototype.setPositions = function (data) {
  105406. var hadPositions = this.hasPositions;
  105407. this._positions = data;
  105408. if (hadPositions !== this.hasPositions) {
  105409. this._onDataLayoutChanged.notifyObservers(undefined);
  105410. }
  105411. };
  105412. /**
  105413. * Gets the position data stored in this target
  105414. * @returns a FloatArray containing the position data (or null if not present)
  105415. */
  105416. MorphTarget.prototype.getPositions = function () {
  105417. return this._positions;
  105418. };
  105419. /**
  105420. * Affects normal data to this target
  105421. * @param data defines the normal data to use
  105422. */
  105423. MorphTarget.prototype.setNormals = function (data) {
  105424. var hadNormals = this.hasNormals;
  105425. this._normals = data;
  105426. if (hadNormals !== this.hasNormals) {
  105427. this._onDataLayoutChanged.notifyObservers(undefined);
  105428. }
  105429. };
  105430. /**
  105431. * Gets the normal data stored in this target
  105432. * @returns a FloatArray containing the normal data (or null if not present)
  105433. */
  105434. MorphTarget.prototype.getNormals = function () {
  105435. return this._normals;
  105436. };
  105437. /**
  105438. * Affects tangent data to this target
  105439. * @param data defines the tangent data to use
  105440. */
  105441. MorphTarget.prototype.setTangents = function (data) {
  105442. var hadTangents = this.hasTangents;
  105443. this._tangents = data;
  105444. if (hadTangents !== this.hasTangents) {
  105445. this._onDataLayoutChanged.notifyObservers(undefined);
  105446. }
  105447. };
  105448. /**
  105449. * Gets the tangent data stored in this target
  105450. * @returns a FloatArray containing the tangent data (or null if not present)
  105451. */
  105452. MorphTarget.prototype.getTangents = function () {
  105453. return this._tangents;
  105454. };
  105455. /**
  105456. * Serializes the current target into a Serialization object
  105457. * @returns the serialized object
  105458. */
  105459. MorphTarget.prototype.serialize = function () {
  105460. var serializationObject = {};
  105461. serializationObject.name = this.name;
  105462. serializationObject.influence = this.influence;
  105463. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  105464. if (this.id != null) {
  105465. serializationObject.id = this.id;
  105466. }
  105467. if (this.hasNormals) {
  105468. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  105469. }
  105470. if (this.hasTangents) {
  105471. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  105472. }
  105473. // Animations
  105474. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  105475. return serializationObject;
  105476. };
  105477. /**
  105478. * Returns the string "MorphTarget"
  105479. * @returns "MorphTarget"
  105480. */
  105481. MorphTarget.prototype.getClassName = function () {
  105482. return "MorphTarget";
  105483. };
  105484. // Statics
  105485. /**
  105486. * Creates a new target from serialized data
  105487. * @param serializationObject defines the serialized data to use
  105488. * @returns a new MorphTarget
  105489. */
  105490. MorphTarget.Parse = function (serializationObject) {
  105491. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  105492. result.setPositions(serializationObject.positions);
  105493. if (serializationObject.id != null) {
  105494. result.id = serializationObject.id;
  105495. }
  105496. if (serializationObject.normals) {
  105497. result.setNormals(serializationObject.normals);
  105498. }
  105499. if (serializationObject.tangents) {
  105500. result.setTangents(serializationObject.tangents);
  105501. }
  105502. // Animations
  105503. if (serializationObject.animations) {
  105504. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  105505. var parsedAnimation = serializationObject.animations[animationIndex];
  105506. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  105507. }
  105508. }
  105509. return result;
  105510. };
  105511. /**
  105512. * Creates a MorphTarget from mesh data
  105513. * @param mesh defines the source mesh
  105514. * @param name defines the name to use for the new target
  105515. * @param influence defines the influence to attach to the target
  105516. * @returns a new MorphTarget
  105517. */
  105518. MorphTarget.FromMesh = function (mesh, name, influence) {
  105519. if (!name) {
  105520. name = mesh.name;
  105521. }
  105522. var result = new MorphTarget(name, influence, mesh.getScene());
  105523. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  105524. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  105525. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  105526. }
  105527. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  105528. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  105529. }
  105530. return result;
  105531. };
  105532. __decorate([
  105533. BABYLON.serialize()
  105534. ], MorphTarget.prototype, "id", void 0);
  105535. return MorphTarget;
  105536. }());
  105537. BABYLON.MorphTarget = MorphTarget;
  105538. })(BABYLON || (BABYLON = {}));
  105539. //# sourceMappingURL=babylon.morphTarget.js.map
  105540. var BABYLON;
  105541. (function (BABYLON) {
  105542. /**
  105543. * This class is used to deform meshes using morphing between different targets
  105544. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  105545. */
  105546. var MorphTargetManager = /** @class */ (function () {
  105547. /**
  105548. * Creates a new MorphTargetManager
  105549. * @param scene defines the current scene
  105550. */
  105551. function MorphTargetManager(scene) {
  105552. if (scene === void 0) { scene = null; }
  105553. this._targets = new Array();
  105554. this._targetInfluenceChangedObservers = new Array();
  105555. this._targetDataLayoutChangedObservers = new Array();
  105556. this._activeTargets = new BABYLON.SmartArray(16);
  105557. this._supportsNormals = false;
  105558. this._supportsTangents = false;
  105559. this._vertexCount = 0;
  105560. this._uniqueId = 0;
  105561. this._tempInfluences = new Array();
  105562. if (!scene) {
  105563. scene = BABYLON.Engine.LastCreatedScene;
  105564. }
  105565. this._scene = scene;
  105566. if (this._scene) {
  105567. this._scene.morphTargetManagers.push(this);
  105568. this._uniqueId = this._scene.getUniqueId();
  105569. }
  105570. }
  105571. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  105572. /**
  105573. * Gets the unique ID of this manager
  105574. */
  105575. get: function () {
  105576. return this._uniqueId;
  105577. },
  105578. enumerable: true,
  105579. configurable: true
  105580. });
  105581. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  105582. /**
  105583. * Gets the number of vertices handled by this manager
  105584. */
  105585. get: function () {
  105586. return this._vertexCount;
  105587. },
  105588. enumerable: true,
  105589. configurable: true
  105590. });
  105591. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  105592. /**
  105593. * Gets a boolean indicating if this manager supports morphing of normals
  105594. */
  105595. get: function () {
  105596. return this._supportsNormals;
  105597. },
  105598. enumerable: true,
  105599. configurable: true
  105600. });
  105601. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  105602. /**
  105603. * Gets a boolean indicating if this manager supports morphing of tangents
  105604. */
  105605. get: function () {
  105606. return this._supportsTangents;
  105607. },
  105608. enumerable: true,
  105609. configurable: true
  105610. });
  105611. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  105612. /**
  105613. * Gets the number of targets stored in this manager
  105614. */
  105615. get: function () {
  105616. return this._targets.length;
  105617. },
  105618. enumerable: true,
  105619. configurable: true
  105620. });
  105621. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  105622. /**
  105623. * Gets the number of influencers (ie. the number of targets with influences > 0)
  105624. */
  105625. get: function () {
  105626. return this._activeTargets.length;
  105627. },
  105628. enumerable: true,
  105629. configurable: true
  105630. });
  105631. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  105632. /**
  105633. * Gets the list of influences (one per target)
  105634. */
  105635. get: function () {
  105636. return this._influences;
  105637. },
  105638. enumerable: true,
  105639. configurable: true
  105640. });
  105641. /**
  105642. * Gets the active target at specified index. An active target is a target with an influence > 0
  105643. * @param index defines the index to check
  105644. * @returns the requested target
  105645. */
  105646. MorphTargetManager.prototype.getActiveTarget = function (index) {
  105647. return this._activeTargets.data[index];
  105648. };
  105649. /**
  105650. * Gets the target at specified index
  105651. * @param index defines the index to check
  105652. * @returns the requested target
  105653. */
  105654. MorphTargetManager.prototype.getTarget = function (index) {
  105655. return this._targets[index];
  105656. };
  105657. /**
  105658. * Add a new target to this manager
  105659. * @param target defines the target to add
  105660. */
  105661. MorphTargetManager.prototype.addTarget = function (target) {
  105662. var _this = this;
  105663. this._targets.push(target);
  105664. this._targetInfluenceChangedObservers.push(target.onInfluenceChanged.add(function (needUpdate) {
  105665. _this._syncActiveTargets(needUpdate);
  105666. }));
  105667. this._targetDataLayoutChangedObservers.push(target._onDataLayoutChanged.add(function () {
  105668. _this._syncActiveTargets(true);
  105669. }));
  105670. this._syncActiveTargets(true);
  105671. };
  105672. /**
  105673. * Removes a target from the manager
  105674. * @param target defines the target to remove
  105675. */
  105676. MorphTargetManager.prototype.removeTarget = function (target) {
  105677. var index = this._targets.indexOf(target);
  105678. if (index >= 0) {
  105679. this._targets.splice(index, 1);
  105680. target.onInfluenceChanged.remove(this._targetInfluenceChangedObservers.splice(index, 1)[0]);
  105681. target._onDataLayoutChanged.remove(this._targetDataLayoutChangedObservers.splice(index, 1)[0]);
  105682. this._syncActiveTargets(true);
  105683. }
  105684. };
  105685. /**
  105686. * Serializes the current manager into a Serialization object
  105687. * @returns the serialized object
  105688. */
  105689. MorphTargetManager.prototype.serialize = function () {
  105690. var serializationObject = {};
  105691. serializationObject.id = this.uniqueId;
  105692. serializationObject.targets = [];
  105693. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  105694. var target = _a[_i];
  105695. serializationObject.targets.push(target.serialize());
  105696. }
  105697. return serializationObject;
  105698. };
  105699. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  105700. var influenceCount = 0;
  105701. this._activeTargets.reset();
  105702. this._supportsNormals = true;
  105703. this._supportsTangents = true;
  105704. this._vertexCount = 0;
  105705. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  105706. var target = _a[_i];
  105707. if (target.influence === 0) {
  105708. continue;
  105709. }
  105710. this._activeTargets.push(target);
  105711. this._tempInfluences[influenceCount++] = target.influence;
  105712. this._supportsNormals = this._supportsNormals && target.hasNormals;
  105713. this._supportsTangents = this._supportsTangents && target.hasTangents;
  105714. var positions = target.getPositions();
  105715. if (positions) {
  105716. var vertexCount = positions.length / 3;
  105717. if (this._vertexCount === 0) {
  105718. this._vertexCount = vertexCount;
  105719. }
  105720. else if (this._vertexCount !== vertexCount) {
  105721. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  105722. return;
  105723. }
  105724. }
  105725. }
  105726. if (!this._influences || this._influences.length !== influenceCount) {
  105727. this._influences = new Float32Array(influenceCount);
  105728. }
  105729. for (var index = 0; index < influenceCount; index++) {
  105730. this._influences[index] = this._tempInfluences[index];
  105731. }
  105732. if (needUpdate) {
  105733. this.synchronize();
  105734. }
  105735. };
  105736. /**
  105737. * Syncrhonize the targets with all the meshes using this morph target manager
  105738. */
  105739. MorphTargetManager.prototype.synchronize = function () {
  105740. if (!this._scene) {
  105741. return;
  105742. }
  105743. // Flag meshes as dirty to resync with the active targets
  105744. for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {
  105745. var mesh = _a[_i];
  105746. if (mesh.morphTargetManager === this) {
  105747. mesh._syncGeometryWithMorphTargetManager();
  105748. }
  105749. }
  105750. };
  105751. // Statics
  105752. /**
  105753. * Creates a new MorphTargetManager from serialized data
  105754. * @param serializationObject defines the serialized data
  105755. * @param scene defines the hosting scene
  105756. * @returns the new MorphTargetManager
  105757. */
  105758. MorphTargetManager.Parse = function (serializationObject, scene) {
  105759. var result = new MorphTargetManager(scene);
  105760. result._uniqueId = serializationObject.id;
  105761. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  105762. var targetData = _a[_i];
  105763. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  105764. }
  105765. return result;
  105766. };
  105767. return MorphTargetManager;
  105768. }());
  105769. BABYLON.MorphTargetManager = MorphTargetManager;
  105770. })(BABYLON || (BABYLON = {}));
  105771. //# sourceMappingURL=babylon.morphTargetManager.js.map
  105772. var BABYLON;
  105773. (function (BABYLON) {
  105774. /**
  105775. * Octrees are a really powerful data structure that can quickly select entities based on space coordinates.
  105776. * @see https://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  105777. */
  105778. var Octree = /** @class */ (function () {
  105779. /**
  105780. * Creates a octree
  105781. * @see https://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  105782. * @param creationFunc function to be used to instatiate the octree
  105783. * @param maxBlockCapacity defines the maximum number of meshes you want on your octree's leaves (default: 64)
  105784. * @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.)
  105785. */
  105786. function Octree(creationFunc, maxBlockCapacity,
  105787. /** 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.) */
  105788. maxDepth) {
  105789. if (maxDepth === void 0) { maxDepth = 2; }
  105790. this.maxDepth = maxDepth;
  105791. /**
  105792. * Content stored in the octree
  105793. */
  105794. this.dynamicContent = new Array();
  105795. this._maxBlockCapacity = maxBlockCapacity || 64;
  105796. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  105797. this._creationFunc = creationFunc;
  105798. }
  105799. // Methods
  105800. /**
  105801. * Updates the octree by adding blocks for the passed in meshes within the min and max world parameters
  105802. * @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);
  105803. * @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);
  105804. * @param entries meshes to be added to the octree blocks
  105805. */
  105806. Octree.prototype.update = function (worldMin, worldMax, entries) {
  105807. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  105808. };
  105809. /**
  105810. * Adds a mesh to the octree
  105811. * @param entry Mesh to add to the octree
  105812. */
  105813. Octree.prototype.addMesh = function (entry) {
  105814. for (var index = 0; index < this.blocks.length; index++) {
  105815. var block = this.blocks[index];
  105816. block.addEntry(entry);
  105817. }
  105818. };
  105819. /**
  105820. * Remove an element from the octree
  105821. * @param entry defines the element to remove
  105822. */
  105823. Octree.prototype.removeMesh = function (entry) {
  105824. for (var index = 0; index < this.blocks.length; index++) {
  105825. var block = this.blocks[index];
  105826. block.removeEntry(entry);
  105827. }
  105828. };
  105829. /**
  105830. * Selects an array of meshes within the frustum
  105831. * @param frustumPlanes The frustum planes to use which will select all meshes within it
  105832. * @param allowDuplicate If duplicate objects are allowed in the resulting object array
  105833. * @returns array of meshes within the frustum
  105834. */
  105835. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  105836. this._selectionContent.reset();
  105837. for (var index = 0; index < this.blocks.length; index++) {
  105838. var block = this.blocks[index];
  105839. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  105840. }
  105841. if (allowDuplicate) {
  105842. this._selectionContent.concat(this.dynamicContent);
  105843. }
  105844. else {
  105845. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  105846. }
  105847. return this._selectionContent;
  105848. };
  105849. /**
  105850. * Test if the octree intersect with the given bounding sphere and if yes, then add its content to the selection array
  105851. * @param sphereCenter defines the bounding sphere center
  105852. * @param sphereRadius defines the bounding sphere radius
  105853. * @param allowDuplicate defines if the selection array can contains duplicated entries
  105854. * @returns an array of objects that intersect the sphere
  105855. */
  105856. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  105857. this._selectionContent.reset();
  105858. for (var index = 0; index < this.blocks.length; index++) {
  105859. var block = this.blocks[index];
  105860. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  105861. }
  105862. if (allowDuplicate) {
  105863. this._selectionContent.concat(this.dynamicContent);
  105864. }
  105865. else {
  105866. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  105867. }
  105868. return this._selectionContent;
  105869. };
  105870. /**
  105871. * Test if the octree intersect with the given ray and if yes, then add its content to resulting array
  105872. * @param ray defines the ray to test with
  105873. * @returns array of intersected objects
  105874. */
  105875. Octree.prototype.intersectsRay = function (ray) {
  105876. this._selectionContent.reset();
  105877. for (var index = 0; index < this.blocks.length; index++) {
  105878. var block = this.blocks[index];
  105879. block.intersectsRay(ray, this._selectionContent);
  105880. }
  105881. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  105882. return this._selectionContent;
  105883. };
  105884. /**
  105885. * @hidden
  105886. */
  105887. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  105888. target.blocks = new Array();
  105889. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  105890. // Segmenting space
  105891. for (var x = 0; x < 2; x++) {
  105892. for (var y = 0; y < 2; y++) {
  105893. for (var z = 0; z < 2; z++) {
  105894. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  105895. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  105896. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  105897. block.addEntries(entries);
  105898. target.blocks.push(block);
  105899. }
  105900. }
  105901. }
  105902. };
  105903. /**
  105904. * Adds a mesh into the octree block if it intersects the block
  105905. */
  105906. Octree.CreationFuncForMeshes = function (entry, block) {
  105907. var boundingInfo = entry.getBoundingInfo();
  105908. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  105909. block.entries.push(entry);
  105910. }
  105911. };
  105912. /**
  105913. * Adds a submesh into the octree block if it intersects the block
  105914. */
  105915. Octree.CreationFuncForSubMeshes = function (entry, block) {
  105916. var boundingInfo = entry.getBoundingInfo();
  105917. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  105918. block.entries.push(entry);
  105919. }
  105920. };
  105921. return Octree;
  105922. }());
  105923. BABYLON.Octree = Octree;
  105924. })(BABYLON || (BABYLON = {}));
  105925. //# sourceMappingURL=babylon.octree.js.map
  105926. var BABYLON;
  105927. (function (BABYLON) {
  105928. /**
  105929. * Class used to store a cell in an octree
  105930. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  105931. */
  105932. var OctreeBlock = /** @class */ (function () {
  105933. /**
  105934. * Creates a new block
  105935. * @param minPoint defines the minimum vector (in world space) of the block's bounding box
  105936. * @param maxPoint defines the maximum vector (in world space) of the block's bounding box
  105937. * @param capacity defines the maximum capacity of this block (if capacity is reached the block will be split into sub blocks)
  105938. * @param depth defines the current depth of this block in the octree
  105939. * @param maxDepth defines the maximal depth allowed (beyond this value, the capacity is ignored)
  105940. * @param creationFunc defines a callback to call when an element is added to the block
  105941. */
  105942. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  105943. /**
  105944. * Gets the content of the current block
  105945. */
  105946. this.entries = new Array();
  105947. this._boundingVectors = new Array();
  105948. this._capacity = capacity;
  105949. this._depth = depth;
  105950. this._maxDepth = maxDepth;
  105951. this._creationFunc = creationFunc;
  105952. this._minPoint = minPoint;
  105953. this._maxPoint = maxPoint;
  105954. this._boundingVectors.push(minPoint.clone());
  105955. this._boundingVectors.push(maxPoint.clone());
  105956. this._boundingVectors.push(minPoint.clone());
  105957. this._boundingVectors[2].x = maxPoint.x;
  105958. this._boundingVectors.push(minPoint.clone());
  105959. this._boundingVectors[3].y = maxPoint.y;
  105960. this._boundingVectors.push(minPoint.clone());
  105961. this._boundingVectors[4].z = maxPoint.z;
  105962. this._boundingVectors.push(maxPoint.clone());
  105963. this._boundingVectors[5].z = minPoint.z;
  105964. this._boundingVectors.push(maxPoint.clone());
  105965. this._boundingVectors[6].x = minPoint.x;
  105966. this._boundingVectors.push(maxPoint.clone());
  105967. this._boundingVectors[7].y = minPoint.y;
  105968. }
  105969. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  105970. // Property
  105971. /**
  105972. * Gets the maximum capacity of this block (if capacity is reached the block will be split into sub blocks)
  105973. */
  105974. get: function () {
  105975. return this._capacity;
  105976. },
  105977. enumerable: true,
  105978. configurable: true
  105979. });
  105980. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  105981. /**
  105982. * Gets the minimum vector (in world space) of the block's bounding box
  105983. */
  105984. get: function () {
  105985. return this._minPoint;
  105986. },
  105987. enumerable: true,
  105988. configurable: true
  105989. });
  105990. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  105991. /**
  105992. * Gets the maximum vector (in world space) of the block's bounding box
  105993. */
  105994. get: function () {
  105995. return this._maxPoint;
  105996. },
  105997. enumerable: true,
  105998. configurable: true
  105999. });
  106000. // Methods
  106001. /**
  106002. * Add a new element to this block
  106003. * @param entry defines the element to add
  106004. */
  106005. OctreeBlock.prototype.addEntry = function (entry) {
  106006. if (this.blocks) {
  106007. for (var index = 0; index < this.blocks.length; index++) {
  106008. var block = this.blocks[index];
  106009. block.addEntry(entry);
  106010. }
  106011. return;
  106012. }
  106013. this._creationFunc(entry, this);
  106014. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  106015. this.createInnerBlocks();
  106016. }
  106017. };
  106018. /**
  106019. * Remove an element from this block
  106020. * @param entry defines the element to remove
  106021. */
  106022. OctreeBlock.prototype.removeEntry = function (entry) {
  106023. if (this.blocks) {
  106024. for (var index = 0; index < this.blocks.length; index++) {
  106025. var block = this.blocks[index];
  106026. block.removeEntry(entry);
  106027. }
  106028. return;
  106029. }
  106030. var entryIndex = this.entries.indexOf(entry);
  106031. if (entryIndex > -1) {
  106032. this.entries.splice(entryIndex, 1);
  106033. }
  106034. };
  106035. /**
  106036. * Add an array of elements to this block
  106037. * @param entries defines the array of elements to add
  106038. */
  106039. OctreeBlock.prototype.addEntries = function (entries) {
  106040. for (var index = 0; index < entries.length; index++) {
  106041. var mesh = entries[index];
  106042. this.addEntry(mesh);
  106043. }
  106044. };
  106045. /**
  106046. * Test if the current block intersects the furstum planes and if yes, then add its content to the selection array
  106047. * @param frustumPlanes defines the frustum planes to test
  106048. * @param selection defines the array to store current content if selection is positive
  106049. * @param allowDuplicate defines if the selection array can contains duplicated entries
  106050. */
  106051. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  106052. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  106053. if (this.blocks) {
  106054. for (var index = 0; index < this.blocks.length; index++) {
  106055. var block = this.blocks[index];
  106056. block.select(frustumPlanes, selection, allowDuplicate);
  106057. }
  106058. return;
  106059. }
  106060. if (allowDuplicate) {
  106061. selection.concat(this.entries);
  106062. }
  106063. else {
  106064. selection.concatWithNoDuplicate(this.entries);
  106065. }
  106066. }
  106067. };
  106068. /**
  106069. * Test if the current block intersect with the given bounding sphere and if yes, then add its content to the selection array
  106070. * @param sphereCenter defines the bounding sphere center
  106071. * @param sphereRadius defines the bounding sphere radius
  106072. * @param selection defines the array to store current content if selection is positive
  106073. * @param allowDuplicate defines if the selection array can contains duplicated entries
  106074. */
  106075. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  106076. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  106077. if (this.blocks) {
  106078. for (var index = 0; index < this.blocks.length; index++) {
  106079. var block = this.blocks[index];
  106080. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  106081. }
  106082. return;
  106083. }
  106084. if (allowDuplicate) {
  106085. selection.concat(this.entries);
  106086. }
  106087. else {
  106088. selection.concatWithNoDuplicate(this.entries);
  106089. }
  106090. }
  106091. };
  106092. /**
  106093. * Test if the current block intersect with the given ray and if yes, then add its content to the selection array
  106094. * @param ray defines the ray to test with
  106095. * @param selection defines the array to store current content if selection is positive
  106096. */
  106097. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  106098. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  106099. if (this.blocks) {
  106100. for (var index = 0; index < this.blocks.length; index++) {
  106101. var block = this.blocks[index];
  106102. block.intersectsRay(ray, selection);
  106103. }
  106104. return;
  106105. }
  106106. selection.concatWithNoDuplicate(this.entries);
  106107. }
  106108. };
  106109. /**
  106110. * Subdivide the content into child blocks (this block will then be empty)
  106111. */
  106112. OctreeBlock.prototype.createInnerBlocks = function () {
  106113. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  106114. };
  106115. return OctreeBlock;
  106116. }());
  106117. BABYLON.OctreeBlock = OctreeBlock;
  106118. })(BABYLON || (BABYLON = {}));
  106119. //# sourceMappingURL=babylon.octreeBlock.js.map
  106120. var BABYLON;
  106121. (function (BABYLON) {
  106122. BABYLON.Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  106123. if (maxCapacity === void 0) { maxCapacity = 64; }
  106124. if (maxDepth === void 0) { maxDepth = 2; }
  106125. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_OCTREE);
  106126. if (!component) {
  106127. component = new OctreeSceneComponent(this);
  106128. this._addComponent(component);
  106129. }
  106130. if (!this._selectionOctree) {
  106131. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  106132. }
  106133. var worldExtends = this.getWorldExtends();
  106134. // Update octree
  106135. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  106136. return this._selectionOctree;
  106137. };
  106138. Object.defineProperty(BABYLON.Scene.prototype, "selectionOctree", {
  106139. get: function () {
  106140. return this._selectionOctree;
  106141. },
  106142. enumerable: true,
  106143. configurable: true
  106144. });
  106145. /**
  106146. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  106147. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  106148. * @param maxCapacity defines the maximum size of each block (64 by default)
  106149. * @param maxDepth defines the maximum depth to use (no more than 2 levels by default)
  106150. * @returns the new octree
  106151. * @see https://www.babylonjs-playground.com/#NA4OQ#12
  106152. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  106153. */
  106154. BABYLON.AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  106155. if (maxCapacity === void 0) { maxCapacity = 64; }
  106156. if (maxDepth === void 0) { maxDepth = 2; }
  106157. var scene = this.getScene();
  106158. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_OCTREE);
  106159. if (!component) {
  106160. component = new OctreeSceneComponent(scene);
  106161. scene._addComponent(component);
  106162. }
  106163. if (!this._submeshesOctree) {
  106164. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  106165. }
  106166. this.computeWorldMatrix(true);
  106167. var boundingInfo = this.getBoundingInfo();
  106168. // Update octree
  106169. var bbox = boundingInfo.boundingBox;
  106170. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  106171. return this._submeshesOctree;
  106172. };
  106173. /**
  106174. * Defines the octree scene component responsible to manage any octrees
  106175. * in a given scene.
  106176. */
  106177. var OctreeSceneComponent = /** @class */ (function () {
  106178. /**
  106179. * Creates a new instance of the component for the given scene
  106180. * @param scene Defines the scene to register the component in
  106181. */
  106182. function OctreeSceneComponent(scene) {
  106183. /**
  106184. * The component name helpfull to identify the component in the list of scene components.
  106185. */
  106186. this.name = BABYLON.SceneComponentConstants.NAME_OCTREE;
  106187. /**
  106188. * Indicates if the meshes have been checked to make sure they are isEnabled()
  106189. */
  106190. this.checksIsEnabled = true;
  106191. this._tempRay = new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(1, 1, 1));
  106192. this.scene = scene;
  106193. this.scene.getActiveMeshCandidates = this.getActiveMeshCandidates.bind(this);
  106194. this.scene.getActiveSubMeshCandidates = this.getActiveSubMeshCandidates.bind(this);
  106195. this.scene.getCollidingSubMeshCandidates = this.getCollidingSubMeshCandidates.bind(this);
  106196. this.scene.getIntersectingSubMeshCandidates = this.getIntersectingSubMeshCandidates.bind(this);
  106197. }
  106198. /**
  106199. * Registers the component in a given scene
  106200. */
  106201. OctreeSceneComponent.prototype.register = function () {
  106202. var _this = this;
  106203. this.scene.onMeshRemovedObservable.add(function (mesh) {
  106204. var sceneOctree = _this.scene.selectionOctree;
  106205. if (sceneOctree !== undefined && sceneOctree !== null) {
  106206. var index = sceneOctree.dynamicContent.indexOf(mesh);
  106207. if (index !== -1) {
  106208. sceneOctree.dynamicContent.splice(index, 1);
  106209. }
  106210. }
  106211. });
  106212. this.scene.onMeshImportedObservable.add(function (mesh) {
  106213. var sceneOctree = _this.scene.selectionOctree;
  106214. if (sceneOctree !== undefined && sceneOctree !== null) {
  106215. sceneOctree.addMesh(mesh);
  106216. }
  106217. });
  106218. };
  106219. /**
  106220. * Return the list of active meshes
  106221. * @returns the list of active meshes
  106222. */
  106223. OctreeSceneComponent.prototype.getActiveMeshCandidates = function () {
  106224. if (this.scene._selectionOctree) {
  106225. var selection = this.scene._selectionOctree.select(this.scene.frustumPlanes);
  106226. return selection;
  106227. }
  106228. return this.scene._getDefaultMeshCandidates();
  106229. };
  106230. /**
  106231. * Return the list of active sub meshes
  106232. * @param mesh The mesh to get the candidates sub meshes from
  106233. * @returns the list of active sub meshes
  106234. */
  106235. OctreeSceneComponent.prototype.getActiveSubMeshCandidates = function (mesh) {
  106236. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  106237. var intersections = mesh._submeshesOctree.select(this.scene.frustumPlanes);
  106238. return intersections;
  106239. }
  106240. return this.scene._getDefaultSubMeshCandidates(mesh);
  106241. };
  106242. /**
  106243. * Return the list of sub meshes intersecting with a given local ray
  106244. * @param mesh defines the mesh to find the submesh for
  106245. * @param localRay defines the ray in local space
  106246. * @returns the list of intersecting sub meshes
  106247. */
  106248. OctreeSceneComponent.prototype.getIntersectingSubMeshCandidates = function (mesh, localRay) {
  106249. if (mesh._submeshesOctree && mesh.useOctreeForPicking) {
  106250. BABYLON.Ray.TransformToRef(localRay, mesh.getWorldMatrix(), this._tempRay);
  106251. var intersections = mesh._submeshesOctree.intersectsRay(this._tempRay);
  106252. return intersections;
  106253. }
  106254. return this.scene._getDefaultSubMeshCandidates(mesh);
  106255. };
  106256. /**
  106257. * Return the list of sub meshes colliding with a collider
  106258. * @param mesh defines the mesh to find the submesh for
  106259. * @param collider defines the collider to evaluate the collision against
  106260. * @returns the list of colliding sub meshes
  106261. */
  106262. OctreeSceneComponent.prototype.getCollidingSubMeshCandidates = function (mesh, collider) {
  106263. if (mesh._submeshesOctree && mesh.useOctreeForCollisions) {
  106264. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  106265. var intersections = mesh._submeshesOctree.intersects(collider._basePointWorld, radius);
  106266. return intersections;
  106267. }
  106268. return this.scene._getDefaultSubMeshCandidates(mesh);
  106269. };
  106270. /**
  106271. * Rebuilds the elements related to this component in case of
  106272. * context lost for instance.
  106273. */
  106274. OctreeSceneComponent.prototype.rebuild = function () {
  106275. // Nothing to do here.
  106276. };
  106277. /**
  106278. * Disposes the component and the associated ressources.
  106279. */
  106280. OctreeSceneComponent.prototype.dispose = function () {
  106281. // Nothing to do here.
  106282. };
  106283. return OctreeSceneComponent;
  106284. }());
  106285. BABYLON.OctreeSceneComponent = OctreeSceneComponent;
  106286. })(BABYLON || (BABYLON = {}));
  106287. //# sourceMappingURL=babylon.octreeSceneComponent.js.map
  106288. var BABYLON;
  106289. (function (BABYLON) {
  106290. /**
  106291. * Postprocess used to generate anaglyphic rendering
  106292. */
  106293. var AnaglyphPostProcess = /** @class */ (function (_super) {
  106294. __extends(AnaglyphPostProcess, _super);
  106295. /**
  106296. * Creates a new AnaglyphPostProcess
  106297. * @param name defines postprocess name
  106298. * @param options defines creation options or target ratio scale
  106299. * @param rigCameras defines cameras using this postprocess
  106300. * @param samplingMode defines required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  106301. * @param engine defines hosting engine
  106302. * @param reusable defines if the postprocess will be reused multiple times per frame
  106303. */
  106304. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  106305. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  106306. _this._passedProcess = rigCameras[0]._rigPostProcess;
  106307. _this.onApplyObservable.add(function (effect) {
  106308. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  106309. });
  106310. return _this;
  106311. }
  106312. return AnaglyphPostProcess;
  106313. }(BABYLON.PostProcess));
  106314. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  106315. })(BABYLON || (BABYLON = {}));
  106316. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  106317. var BABYLON;
  106318. (function (BABYLON) {
  106319. BABYLON.Node.AddNodeConstructor("AnaglyphArcRotateCamera", function (name, scene, options) {
  106320. return function () { return new AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  106321. });
  106322. /**
  106323. * Camera used to simulate anaglyphic rendering (based on ArcRotateCamera)
  106324. * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras
  106325. */
  106326. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  106327. __extends(AnaglyphArcRotateCamera, _super);
  106328. /**
  106329. * Creates a new AnaglyphArcRotateCamera
  106330. * @param name defines camera name
  106331. * @param alpha defines alpha angle (in radians)
  106332. * @param beta defines beta angle (in radians)
  106333. * @param radius defines radius
  106334. * @param target defines camera target
  106335. * @param interaxialDistance defines distance between each color axis
  106336. * @param scene defines the hosting scene
  106337. */
  106338. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  106339. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  106340. _this.interaxialDistance = interaxialDistance;
  106341. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  106342. return _this;
  106343. }
  106344. /**
  106345. * Gets camera class name
  106346. * @returns AnaglyphArcRotateCamera
  106347. */
  106348. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  106349. return "AnaglyphArcRotateCamera";
  106350. };
  106351. return AnaglyphArcRotateCamera;
  106352. }(BABYLON.ArcRotateCamera));
  106353. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  106354. })(BABYLON || (BABYLON = {}));
  106355. //# sourceMappingURL=babylon.anaglyphArcRotateCamera.js.map
  106356. var BABYLON;
  106357. (function (BABYLON) {
  106358. BABYLON.Node.AddNodeConstructor("AnaglyphFreeCamera", function (name, scene, options) {
  106359. return function () { return new AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  106360. });
  106361. /**
  106362. * Camera used to simulate anaglyphic rendering (based on FreeCamera)
  106363. * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras
  106364. */
  106365. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  106366. __extends(AnaglyphFreeCamera, _super);
  106367. /**
  106368. * Creates a new AnaglyphFreeCamera
  106369. * @param name defines camera name
  106370. * @param position defines initial position
  106371. * @param interaxialDistance defines distance between each color axis
  106372. * @param scene defines the hosting scene
  106373. */
  106374. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  106375. var _this = _super.call(this, name, position, scene) || this;
  106376. _this.interaxialDistance = interaxialDistance;
  106377. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  106378. return _this;
  106379. }
  106380. /**
  106381. * Gets camera class name
  106382. * @returns AnaglyphFreeCamera
  106383. */
  106384. AnaglyphFreeCamera.prototype.getClassName = function () {
  106385. return "AnaglyphFreeCamera";
  106386. };
  106387. return AnaglyphFreeCamera;
  106388. }(BABYLON.FreeCamera));
  106389. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  106390. })(BABYLON || (BABYLON = {}));
  106391. //# sourceMappingURL=babylon.anaglyphFreeCamera.js.map
  106392. var BABYLON;
  106393. (function (BABYLON) {
  106394. BABYLON.Node.AddNodeConstructor("AnaglyphGamepadCamera", function (name, scene, options) {
  106395. return function () { return new AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  106396. });
  106397. /**
  106398. * Camera used to simulate anaglyphic rendering (based on GamepadCamera)
  106399. * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras
  106400. */
  106401. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  106402. __extends(AnaglyphGamepadCamera, _super);
  106403. /**
  106404. * Creates a new AnaglyphGamepadCamera
  106405. * @param name defines camera name
  106406. * @param position defines initial position
  106407. * @param interaxialDistance defines distance between each color axis
  106408. * @param scene defines the hosting scene
  106409. */
  106410. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  106411. var _this = _super.call(this, name, position, scene) || this;
  106412. _this.interaxialDistance = interaxialDistance;
  106413. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  106414. return _this;
  106415. }
  106416. /**
  106417. * Gets camera class name
  106418. * @returns AnaglyphGamepadCamera
  106419. */
  106420. AnaglyphGamepadCamera.prototype.getClassName = function () {
  106421. return "AnaglyphGamepadCamera";
  106422. };
  106423. return AnaglyphGamepadCamera;
  106424. }(BABYLON.GamepadCamera));
  106425. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  106426. })(BABYLON || (BABYLON = {}));
  106427. //# sourceMappingURL=babylon.anaglyphGamepadCamera.js.map
  106428. var BABYLON;
  106429. (function (BABYLON) {
  106430. BABYLON.Node.AddNodeConstructor("AnaglyphUniversalCamera", function (name, scene, options) {
  106431. return function () { return new AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  106432. });
  106433. /**
  106434. * Camera used to simulate anaglyphic rendering (based on UniversalCamera)
  106435. * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras
  106436. */
  106437. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  106438. __extends(AnaglyphUniversalCamera, _super);
  106439. /**
  106440. * Creates a new AnaglyphUniversalCamera
  106441. * @param name defines camera name
  106442. * @param position defines initial position
  106443. * @param interaxialDistance defines distance between each color axis
  106444. * @param scene defines the hosting scene
  106445. */
  106446. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  106447. var _this = _super.call(this, name, position, scene) || this;
  106448. _this.interaxialDistance = interaxialDistance;
  106449. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  106450. return _this;
  106451. }
  106452. /**
  106453. * Gets camera class name
  106454. * @returns AnaglyphUniversalCamera
  106455. */
  106456. AnaglyphUniversalCamera.prototype.getClassName = function () {
  106457. return "AnaglyphUniversalCamera";
  106458. };
  106459. return AnaglyphUniversalCamera;
  106460. }(BABYLON.UniversalCamera));
  106461. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  106462. })(BABYLON || (BABYLON = {}));
  106463. //# sourceMappingURL=babylon.anaglyphUniversalCamera.js.map
  106464. var BABYLON;
  106465. (function (BABYLON) {
  106466. /**
  106467. * StereoscopicInterlacePostProcess used to render stereo views from a rigged camera
  106468. */
  106469. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  106470. __extends(StereoscopicInterlacePostProcess, _super);
  106471. /**
  106472. * Initializes a StereoscopicInterlacePostProcess
  106473. * @param name The name of the effect.
  106474. * @param rigCameras The rig cameras to be appled to the post process
  106475. * @param isStereoscopicHoriz If the rendered results are horizontal or verticle
  106476. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  106477. * @param engine The engine which the post process will be applied. (default: current engine)
  106478. * @param reusable If the post process can be reused on the same frame. (default: false)
  106479. */
  106480. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  106481. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  106482. _this._passedProcess = rigCameras[0]._rigPostProcess;
  106483. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  106484. _this.onSizeChangedObservable.add(function () {
  106485. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  106486. });
  106487. _this.onApplyObservable.add(function (effect) {
  106488. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  106489. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  106490. });
  106491. return _this;
  106492. }
  106493. return StereoscopicInterlacePostProcess;
  106494. }(BABYLON.PostProcess));
  106495. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  106496. })(BABYLON || (BABYLON = {}));
  106497. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  106498. var BABYLON;
  106499. (function (BABYLON) {
  106500. BABYLON.Node.AddNodeConstructor("StereoscopicArcRotateCamera", function (name, scene, options) {
  106501. return function () { return new StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  106502. });
  106503. /**
  106504. * Camera used to simulate stereoscopic rendering (based on ArcRotateCamera)
  106505. * @see http://doc.babylonjs.com/features/cameras
  106506. */
  106507. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  106508. __extends(StereoscopicArcRotateCamera, _super);
  106509. /**
  106510. * Creates a new StereoscopicArcRotateCamera
  106511. * @param name defines camera name
  106512. * @param alpha defines alpha angle (in radians)
  106513. * @param beta defines beta angle (in radians)
  106514. * @param radius defines radius
  106515. * @param target defines camera target
  106516. * @param interaxialDistance defines distance between each color axis
  106517. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  106518. * @param scene defines the hosting scene
  106519. */
  106520. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  106521. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  106522. _this.interaxialDistance = interaxialDistance;
  106523. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  106524. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  106525. return _this;
  106526. }
  106527. /**
  106528. * Gets camera class name
  106529. * @returns StereoscopicArcRotateCamera
  106530. */
  106531. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  106532. return "StereoscopicArcRotateCamera";
  106533. };
  106534. return StereoscopicArcRotateCamera;
  106535. }(BABYLON.ArcRotateCamera));
  106536. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  106537. })(BABYLON || (BABYLON = {}));
  106538. //# sourceMappingURL=babylon.stereoscopicArcRotateCamera.js.map
  106539. var BABYLON;
  106540. (function (BABYLON) {
  106541. BABYLON.Node.AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) {
  106542. return function () { return new StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  106543. });
  106544. /**
  106545. * Camera used to simulate stereoscopic rendering (based on FreeCamera)
  106546. * @see http://doc.babylonjs.com/features/cameras
  106547. */
  106548. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  106549. __extends(StereoscopicFreeCamera, _super);
  106550. /**
  106551. * Creates a new StereoscopicFreeCamera
  106552. * @param name defines camera name
  106553. * @param position defines initial position
  106554. * @param interaxialDistance defines distance between each color axis
  106555. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  106556. * @param scene defines the hosting scene
  106557. */
  106558. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  106559. var _this = _super.call(this, name, position, scene) || this;
  106560. _this.interaxialDistance = interaxialDistance;
  106561. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  106562. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  106563. return _this;
  106564. }
  106565. /**
  106566. * Gets camera class name
  106567. * @returns StereoscopicFreeCamera
  106568. */
  106569. StereoscopicFreeCamera.prototype.getClassName = function () {
  106570. return "StereoscopicFreeCamera";
  106571. };
  106572. return StereoscopicFreeCamera;
  106573. }(BABYLON.FreeCamera));
  106574. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  106575. })(BABYLON || (BABYLON = {}));
  106576. //# sourceMappingURL=babylon.stereoscopicFreeCamera.js.map
  106577. var BABYLON;
  106578. (function (BABYLON) {
  106579. BABYLON.Node.AddNodeConstructor("StereoscopicGamepadCamera", function (name, scene, options) {
  106580. return function () { return new StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  106581. });
  106582. /**
  106583. * Camera used to simulate stereoscopic rendering (based on GamepadCamera)
  106584. * @see http://doc.babylonjs.com/features/cameras
  106585. */
  106586. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  106587. __extends(StereoscopicGamepadCamera, _super);
  106588. /**
  106589. * Creates a new StereoscopicGamepadCamera
  106590. * @param name defines camera name
  106591. * @param position defines initial position
  106592. * @param interaxialDistance defines distance between each color axis
  106593. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  106594. * @param scene defines the hosting scene
  106595. */
  106596. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  106597. var _this = _super.call(this, name, position, scene) || this;
  106598. _this.interaxialDistance = interaxialDistance;
  106599. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  106600. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  106601. return _this;
  106602. }
  106603. /**
  106604. * Gets camera class name
  106605. * @returns StereoscopicGamepadCamera
  106606. */
  106607. StereoscopicGamepadCamera.prototype.getClassName = function () {
  106608. return "StereoscopicGamepadCamera";
  106609. };
  106610. return StereoscopicGamepadCamera;
  106611. }(BABYLON.GamepadCamera));
  106612. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  106613. })(BABYLON || (BABYLON = {}));
  106614. //# sourceMappingURL=babylon.stereoscopicGamepadCamera.js.map
  106615. var BABYLON;
  106616. (function (BABYLON) {
  106617. BABYLON.Node.AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) {
  106618. return function () { return new StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  106619. });
  106620. /**
  106621. * Camera used to simulate stereoscopic rendering (based on UniversalCamera)
  106622. * @see http://doc.babylonjs.com/features/cameras
  106623. */
  106624. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  106625. __extends(StereoscopicUniversalCamera, _super);
  106626. /**
  106627. * Creates a new StereoscopicUniversalCamera
  106628. * @param name defines camera name
  106629. * @param position defines initial position
  106630. * @param interaxialDistance defines distance between each color axis
  106631. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  106632. * @param scene defines the hosting scene
  106633. */
  106634. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  106635. var _this = _super.call(this, name, position, scene) || this;
  106636. _this.interaxialDistance = interaxialDistance;
  106637. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  106638. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  106639. return _this;
  106640. }
  106641. /**
  106642. * Gets camera class name
  106643. * @returns StereoscopicUniversalCamera
  106644. */
  106645. StereoscopicUniversalCamera.prototype.getClassName = function () {
  106646. return "StereoscopicUniversalCamera";
  106647. };
  106648. return StereoscopicUniversalCamera;
  106649. }(BABYLON.UniversalCamera));
  106650. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  106651. })(BABYLON || (BABYLON = {}));
  106652. //# sourceMappingURL=babylon.stereoscopicUniversalCamera.js.map
  106653. var BABYLON;
  106654. (function (BABYLON) {
  106655. /**
  106656. * VRDistortionCorrectionPostProcess used for mobile VR
  106657. */
  106658. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  106659. __extends(VRDistortionCorrectionPostProcess, _super);
  106660. /**
  106661. * Initializes the VRDistortionCorrectionPostProcess
  106662. * @param name The name of the effect.
  106663. * @param camera The camera to apply the render pass to.
  106664. * @param isRightEye If this is for the right eye distortion
  106665. * @param vrMetrics All the required metrics for the VR camera
  106666. */
  106667. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  106668. var _this = _super.call(this, name, "vrDistortionCorrection", [
  106669. 'LensCenter',
  106670. 'Scale',
  106671. 'ScaleIn',
  106672. 'HmdWarpParam'
  106673. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  106674. _this._isRightEye = isRightEye;
  106675. _this._distortionFactors = vrMetrics.distortionK;
  106676. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  106677. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  106678. _this.adaptScaleToCurrentViewport = true;
  106679. _this.onSizeChangedObservable.add(function () {
  106680. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  106681. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  106682. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  106683. });
  106684. _this.onApplyObservable.add(function (effect) {
  106685. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  106686. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  106687. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  106688. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  106689. });
  106690. return _this;
  106691. }
  106692. return VRDistortionCorrectionPostProcess;
  106693. }(BABYLON.PostProcess));
  106694. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  106695. })(BABYLON || (BABYLON = {}));
  106696. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  106697. var BABYLON;
  106698. (function (BABYLON) {
  106699. /**
  106700. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  106701. * Screen rotation is taken into account.
  106702. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  106703. */
  106704. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  106705. /**
  106706. * Instantiates a new input
  106707. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  106708. */
  106709. function FreeCameraDeviceOrientationInput() {
  106710. var _this = this;
  106711. this._screenOrientationAngle = 0;
  106712. this._screenQuaternion = new BABYLON.Quaternion();
  106713. this._alpha = 0;
  106714. this._beta = 0;
  106715. this._gamma = 0;
  106716. this._orientationChanged = function () {
  106717. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && (window.screen.orientation)['angle'] ? (window.screen.orientation).angle : 0));
  106718. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  106719. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  106720. };
  106721. this._deviceOrientation = function (evt) {
  106722. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  106723. _this._beta = evt.beta !== null ? evt.beta : 0;
  106724. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  106725. };
  106726. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  106727. this._orientationChanged();
  106728. }
  106729. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  106730. /**
  106731. * Define the camera controlled by the input.
  106732. */
  106733. get: function () {
  106734. return this._camera;
  106735. },
  106736. set: function (camera) {
  106737. this._camera = camera;
  106738. if (this._camera != null && !this._camera.rotationQuaternion) {
  106739. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  106740. }
  106741. },
  106742. enumerable: true,
  106743. configurable: true
  106744. });
  106745. /**
  106746. * Attach the input controls to a specific dom element to get the input from.
  106747. * @param element Defines the element the controls should be listened from
  106748. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  106749. */
  106750. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  106751. window.addEventListener("orientationchange", this._orientationChanged);
  106752. window.addEventListener("deviceorientation", this._deviceOrientation);
  106753. //In certain cases, the attach control is called AFTER orientation was changed,
  106754. //So this is needed.
  106755. this._orientationChanged();
  106756. };
  106757. /**
  106758. * Detach the current controls from the specified dom element.
  106759. * @param element Defines the element to stop listening the inputs from
  106760. */
  106761. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  106762. window.removeEventListener("orientationchange", this._orientationChanged);
  106763. window.removeEventListener("deviceorientation", this._deviceOrientation);
  106764. };
  106765. /**
  106766. * Update the current camera state depending on the inputs that have been used this frame.
  106767. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  106768. */
  106769. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  106770. //if no device orientation provided, don't update the rotation.
  106771. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  106772. if (!this._alpha) {
  106773. return;
  106774. }
  106775. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  106776. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  106777. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  106778. //Mirror on XY Plane
  106779. this._camera.rotationQuaternion.z *= -1;
  106780. this._camera.rotationQuaternion.w *= -1;
  106781. };
  106782. /**
  106783. * Gets the class name of the current intput.
  106784. * @returns the class name
  106785. */
  106786. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  106787. return "FreeCameraDeviceOrientationInput";
  106788. };
  106789. /**
  106790. * Get the friendly name associated with the input class.
  106791. * @returns the input friendly name
  106792. */
  106793. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  106794. return "deviceOrientation";
  106795. };
  106796. return FreeCameraDeviceOrientationInput;
  106797. }());
  106798. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  106799. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  106800. })(BABYLON || (BABYLON = {}));
  106801. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  106802. var BABYLON;
  106803. (function (BABYLON) {
  106804. /**
  106805. * Manage the device orientation inputs (gyroscope) to control an arc rotate camera.
  106806. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  106807. */
  106808. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  106809. /**
  106810. * Instantiate a new ArcRotateCameraVRDeviceOrientationInput.
  106811. */
  106812. function ArcRotateCameraVRDeviceOrientationInput() {
  106813. /**
  106814. * Defines a correction factor applied on the alpha value retrieved from the orientation events.
  106815. */
  106816. this.alphaCorrection = 1;
  106817. /**
  106818. * Defines a correction factor applied on the gamma value retrieved from the orientation events.
  106819. */
  106820. this.gammaCorrection = 1;
  106821. this._alpha = 0;
  106822. this._gamma = 0;
  106823. this._dirty = false;
  106824. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  106825. }
  106826. /**
  106827. * Attach the input controls to a specific dom element to get the input from.
  106828. * @param element Defines the element the controls should be listened from
  106829. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  106830. */
  106831. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  106832. this.camera.attachControl(element, noPreventDefault);
  106833. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  106834. };
  106835. /** @hidden */
  106836. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  106837. if (evt.alpha !== null) {
  106838. this._alpha = (+evt.alpha | 0) * this.alphaCorrection;
  106839. }
  106840. if (evt.gamma !== null) {
  106841. this._gamma = (+evt.gamma | 0) * this.gammaCorrection;
  106842. }
  106843. this._dirty = true;
  106844. };
  106845. /**
  106846. * Update the current camera state depending on the inputs that have been used this frame.
  106847. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  106848. */
  106849. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  106850. if (this._dirty) {
  106851. this._dirty = false;
  106852. if (this._gamma < 0) {
  106853. this._gamma = 180 + this._gamma;
  106854. }
  106855. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  106856. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  106857. }
  106858. };
  106859. /**
  106860. * Detach the current controls from the specified dom element.
  106861. * @param element Defines the element to stop listening the inputs from
  106862. */
  106863. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  106864. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  106865. };
  106866. /**
  106867. * Gets the class name of the current intput.
  106868. * @returns the class name
  106869. */
  106870. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  106871. return "ArcRotateCameraVRDeviceOrientationInput";
  106872. };
  106873. /**
  106874. * Get the friendly name associated with the input class.
  106875. * @returns the input friendly name
  106876. */
  106877. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  106878. return "VRDeviceOrientation";
  106879. };
  106880. return ArcRotateCameraVRDeviceOrientationInput;
  106881. }());
  106882. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  106883. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  106884. })(BABYLON || (BABYLON = {}));
  106885. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  106886. var BABYLON;
  106887. (function (BABYLON) {
  106888. /**
  106889. * This represents all the required metrics to create a VR camera.
  106890. * @see http://doc.babylonjs.com/babylon101/cameras#device-orientation-camera
  106891. */
  106892. var VRCameraMetrics = /** @class */ (function () {
  106893. function VRCameraMetrics() {
  106894. /**
  106895. * Define if the current vr camera should compensate the distortion of the lense or not.
  106896. */
  106897. this.compensateDistortion = true;
  106898. }
  106899. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  106900. /**
  106901. * Gets the rendering aspect ratio based on the provided resolutions.
  106902. */
  106903. get: function () {
  106904. return this.hResolution / (2 * this.vResolution);
  106905. },
  106906. enumerable: true,
  106907. configurable: true
  106908. });
  106909. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  106910. /**
  106911. * Gets the aspect ratio based on the FOV, scale factors, and real screen sizes.
  106912. */
  106913. get: function () {
  106914. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  106915. },
  106916. enumerable: true,
  106917. configurable: true
  106918. });
  106919. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  106920. /**
  106921. * @hidden
  106922. */
  106923. get: function () {
  106924. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  106925. var h = (4 * meters) / this.hScreenSize;
  106926. return BABYLON.Matrix.Translation(h, 0, 0);
  106927. },
  106928. enumerable: true,
  106929. configurable: true
  106930. });
  106931. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  106932. /**
  106933. * @hidden
  106934. */
  106935. get: function () {
  106936. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  106937. var h = (4 * meters) / this.hScreenSize;
  106938. return BABYLON.Matrix.Translation(-h, 0, 0);
  106939. },
  106940. enumerable: true,
  106941. configurable: true
  106942. });
  106943. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  106944. /**
  106945. * @hidden
  106946. */
  106947. get: function () {
  106948. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  106949. },
  106950. enumerable: true,
  106951. configurable: true
  106952. });
  106953. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  106954. /**
  106955. * @hidden
  106956. */
  106957. get: function () {
  106958. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  106959. },
  106960. enumerable: true,
  106961. configurable: true
  106962. });
  106963. /**
  106964. * Get the default VRMetrics based on the most generic setup.
  106965. * @returns the default vr metrics
  106966. */
  106967. VRCameraMetrics.GetDefault = function () {
  106968. var result = new VRCameraMetrics();
  106969. result.hResolution = 1280;
  106970. result.vResolution = 800;
  106971. result.hScreenSize = 0.149759993;
  106972. result.vScreenSize = 0.0935999975;
  106973. result.vScreenCenter = 0.0467999987;
  106974. result.eyeToScreenDistance = 0.0410000011;
  106975. result.lensSeparationDistance = 0.0635000020;
  106976. result.interpupillaryDistance = 0.0640000030;
  106977. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  106978. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  106979. result.postProcessScaleFactor = 1.714605507808412;
  106980. result.lensCenterOffset = 0.151976421;
  106981. return result;
  106982. };
  106983. return VRCameraMetrics;
  106984. }());
  106985. BABYLON.VRCameraMetrics = VRCameraMetrics;
  106986. })(BABYLON || (BABYLON = {}));
  106987. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  106988. var BABYLON;
  106989. (function (BABYLON) {
  106990. BABYLON.Node.AddNodeConstructor("WebVRFreeCamera", function (name, scene) {
  106991. return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  106992. });
  106993. BABYLON.Node.AddNodeConstructor("WebVRGamepadCamera", function (name, scene) {
  106994. return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  106995. });
  106996. /**
  106997. * This represents a WebVR camera.
  106998. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  106999. * @example http://doc.babylonjs.com/how_to/webvr_camera
  107000. */
  107001. var WebVRFreeCamera = /** @class */ (function (_super) {
  107002. __extends(WebVRFreeCamera, _super);
  107003. /**
  107004. * Instantiates a WebVRFreeCamera.
  107005. * @param name The name of the WebVRFreeCamera
  107006. * @param position The starting anchor position for the camera
  107007. * @param scene The scene the camera belongs to
  107008. * @param webVROptions a set of customizable options for the webVRCamera
  107009. */
  107010. function WebVRFreeCamera(name, position, scene, webVROptions) {
  107011. if (webVROptions === void 0) { webVROptions = {}; }
  107012. var _this = _super.call(this, name, position, scene) || this;
  107013. _this.webVROptions = webVROptions;
  107014. /**
  107015. * @hidden
  107016. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  107017. */
  107018. _this._vrDevice = null;
  107019. /**
  107020. * The rawPose of the vrDevice.
  107021. */
  107022. _this.rawPose = null;
  107023. _this._specsVersion = "1.1";
  107024. _this._attached = false;
  107025. _this._descendants = [];
  107026. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  107027. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  107028. /** @hidden */
  107029. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  107030. _this._standingMatrix = null;
  107031. /**
  107032. * Represents device position in babylon space.
  107033. */
  107034. _this.devicePosition = BABYLON.Vector3.Zero();
  107035. /**
  107036. * Represents device rotation in babylon space.
  107037. */
  107038. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  107039. /**
  107040. * The scale of the device to be used when translating from device space to babylon space.
  107041. */
  107042. _this.deviceScaleFactor = 1;
  107043. _this._deviceToWorld = BABYLON.Matrix.Identity();
  107044. _this._worldToDevice = BABYLON.Matrix.Identity();
  107045. /**
  107046. * References to the webVR controllers for the vrDevice.
  107047. */
  107048. _this.controllers = [];
  107049. /**
  107050. * Emits an event when a controller is attached.
  107051. */
  107052. _this.onControllersAttachedObservable = new BABYLON.Observable();
  107053. /**
  107054. * Emits an event when a controller's mesh has been loaded;
  107055. */
  107056. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  107057. /**
  107058. * Emits an event when the HMD's pose has been updated.
  107059. */
  107060. _this.onPoseUpdatedFromDeviceObservable = new BABYLON.Observable();
  107061. _this._poseSet = false;
  107062. /**
  107063. * If the rig cameras be used as parent instead of this camera.
  107064. */
  107065. _this.rigParenting = true;
  107066. _this._defaultHeight = undefined;
  107067. _this._htmlElementAttached = null;
  107068. _this._detachIfAttached = function () {
  107069. var vrDisplay = _this.getEngine().getVRDevice();
  107070. if (vrDisplay && !vrDisplay.isPresenting && _this._htmlElementAttached) {
  107071. _this.detachControl(_this._htmlElementAttached);
  107072. }
  107073. };
  107074. _this._workingVector = BABYLON.Vector3.Zero();
  107075. _this._oneVector = BABYLON.Vector3.One();
  107076. _this._workingMatrix = BABYLON.Matrix.Identity();
  107077. _this._tmpMatrix = new BABYLON.Matrix();
  107078. _this._cache.position = BABYLON.Vector3.Zero();
  107079. if (webVROptions.defaultHeight) {
  107080. _this._defaultHeight = webVROptions.defaultHeight;
  107081. _this.position.y = _this._defaultHeight;
  107082. }
  107083. _this.minZ = 0.1;
  107084. //legacy support - the compensation boolean was removed.
  107085. if (arguments.length === 5) {
  107086. _this.webVROptions = arguments[4];
  107087. }
  107088. // default webVR options
  107089. if (_this.webVROptions.trackPosition == undefined) {
  107090. _this.webVROptions.trackPosition = true;
  107091. }
  107092. if (_this.webVROptions.controllerMeshes == undefined) {
  107093. _this.webVROptions.controllerMeshes = true;
  107094. }
  107095. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  107096. _this.webVROptions.defaultLightingOnControllers = true;
  107097. }
  107098. _this.rotationQuaternion = new BABYLON.Quaternion();
  107099. if (_this.webVROptions && _this.webVROptions.positionScale) {
  107100. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  107101. }
  107102. //enable VR
  107103. var engine = _this.getEngine();
  107104. _this._onVREnabled = function (success) { if (success) {
  107105. _this.initControllers();
  107106. } };
  107107. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  107108. engine.initWebVR().add(function (event) {
  107109. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  107110. return;
  107111. }
  107112. _this._vrDevice = event.vrDisplay;
  107113. //reset the rig parameters.
  107114. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  107115. if (_this._attached) {
  107116. _this.getEngine().enableVR();
  107117. }
  107118. });
  107119. if (typeof (VRFrameData) !== "undefined") {
  107120. _this._frameData = new VRFrameData();
  107121. }
  107122. /**
  107123. * The idea behind the following lines:
  107124. * objects that have the camera as parent should actually have the rig cameras as a parent.
  107125. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  107126. * the second will not show it correctly.
  107127. *
  107128. * To solve this - each object that has the camera as parent will be added to a protected array.
  107129. * When the rig camera renders, it will take this array and set all of those to be its children.
  107130. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  107131. * Amazing!
  107132. */
  107133. scene.onBeforeCameraRenderObservable.add(function (camera) {
  107134. if (camera.parent === _this && _this.rigParenting) {
  107135. _this._descendants = _this.getDescendants(true, function (n) {
  107136. // don't take the cameras or the controllers!
  107137. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  107138. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  107139. return !isController && !isRigCamera;
  107140. });
  107141. _this._descendants.forEach(function (node) {
  107142. node.parent = camera;
  107143. });
  107144. }
  107145. });
  107146. scene.onAfterCameraRenderObservable.add(function (camera) {
  107147. if (camera.parent === _this && _this.rigParenting) {
  107148. _this._descendants.forEach(function (node) {
  107149. node.parent = _this;
  107150. });
  107151. }
  107152. });
  107153. return _this;
  107154. }
  107155. /**
  107156. * Gets the device distance from the ground in meters.
  107157. * @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.
  107158. */
  107159. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  107160. if (this._standingMatrix) {
  107161. // Add standing matrix offset to get real offset from ground in room
  107162. this._standingMatrix.getTranslationToRef(this._workingVector);
  107163. return this._deviceRoomPosition.y + this._workingVector.y;
  107164. }
  107165. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  107166. return this._defaultHeight || 0;
  107167. };
  107168. /**
  107169. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  107170. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  107171. */
  107172. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  107173. var _this = this;
  107174. if (callback === void 0) { callback = function (bool) { }; }
  107175. // Use standing matrix if available
  107176. this.getEngine().initWebVRAsync().then(function (result) {
  107177. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform || !_this.webVROptions.trackPosition) {
  107178. callback(false);
  107179. }
  107180. else {
  107181. _this._standingMatrix = new BABYLON.Matrix();
  107182. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  107183. if (!_this.getScene().useRightHandedSystem) {
  107184. if (_this._standingMatrix) {
  107185. _this._standingMatrix.toggleModelMatrixHandInPlace();
  107186. }
  107187. }
  107188. callback(true);
  107189. }
  107190. });
  107191. };
  107192. /**
  107193. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  107194. * @returns A promise with a boolean set to if the standing matrix is supported.
  107195. */
  107196. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  107197. var _this = this;
  107198. return new Promise(function (res, rej) {
  107199. _this.useStandingMatrix(function (supported) {
  107200. res(supported);
  107201. });
  107202. });
  107203. };
  107204. /**
  107205. * Disposes the camera
  107206. */
  107207. WebVRFreeCamera.prototype.dispose = function () {
  107208. this._detachIfAttached();
  107209. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  107210. if (this._updateCacheWhenTrackingDisabledObserver) {
  107211. this._scene.onBeforeRenderObservable.remove(this._updateCacheWhenTrackingDisabledObserver);
  107212. }
  107213. _super.prototype.dispose.call(this);
  107214. };
  107215. /**
  107216. * Gets a vrController by name.
  107217. * @param name The name of the controller to retreive
  107218. * @returns the controller matching the name specified or null if not found
  107219. */
  107220. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  107221. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  107222. var gp = _a[_i];
  107223. if (gp.hand === name) {
  107224. return gp;
  107225. }
  107226. }
  107227. return null;
  107228. };
  107229. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  107230. /**
  107231. * The controller corrisponding to the users left hand.
  107232. */
  107233. get: function () {
  107234. if (!this._leftController) {
  107235. this._leftController = this.getControllerByName("left");
  107236. }
  107237. return this._leftController;
  107238. },
  107239. enumerable: true,
  107240. configurable: true
  107241. });
  107242. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  107243. /**
  107244. * The controller corrisponding to the users right hand.
  107245. */
  107246. get: function () {
  107247. if (!this._rightController) {
  107248. this._rightController = this.getControllerByName("right");
  107249. }
  107250. return this._rightController;
  107251. },
  107252. enumerable: true,
  107253. configurable: true
  107254. });
  107255. /**
  107256. * Casts a ray forward from the vrCamera's gaze.
  107257. * @param length Length of the ray (default: 100)
  107258. * @returns the ray corrisponding to the gaze
  107259. */
  107260. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  107261. if (length === void 0) { length = 100; }
  107262. if (this.leftCamera) {
  107263. // Use left eye to avoid computation to compute center on every call
  107264. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  107265. }
  107266. else {
  107267. return _super.prototype.getForwardRay.call(this, length);
  107268. }
  107269. };
  107270. /**
  107271. * @hidden
  107272. * Updates the camera based on device's frame data
  107273. */
  107274. WebVRFreeCamera.prototype._checkInputs = function () {
  107275. if (this._vrDevice && this._vrDevice.isPresenting) {
  107276. this._vrDevice.getFrameData(this._frameData);
  107277. this.updateFromDevice(this._frameData.pose);
  107278. }
  107279. _super.prototype._checkInputs.call(this);
  107280. };
  107281. /**
  107282. * Updates the poseControlled values based on the input device pose.
  107283. * @param poseData Pose coming from the device
  107284. */
  107285. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  107286. if (poseData && poseData.orientation) {
  107287. this.rawPose = poseData;
  107288. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  107289. if (this.getScene().useRightHandedSystem) {
  107290. this._deviceRoomRotationQuaternion.z *= -1;
  107291. this._deviceRoomRotationQuaternion.w *= -1;
  107292. }
  107293. if (this.webVROptions.trackPosition && this.rawPose.position) {
  107294. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  107295. if (this.getScene().useRightHandedSystem) {
  107296. this._deviceRoomPosition.z *= -1;
  107297. }
  107298. }
  107299. this._poseSet = true;
  107300. }
  107301. };
  107302. /**
  107303. * WebVR's attach control will start broadcasting frames to the device.
  107304. * Note that in certain browsers (chrome for example) this function must be called
  107305. * within a user-interaction callback. Example:
  107306. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  107307. *
  107308. * @param element html element to attach the vrDevice to
  107309. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  107310. */
  107311. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  107312. _super.prototype.attachControl.call(this, element, noPreventDefault);
  107313. this._attached = true;
  107314. this._htmlElementAttached = element;
  107315. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  107316. if (this._vrDevice) {
  107317. this.getEngine().enableVR();
  107318. }
  107319. window.addEventListener('vrdisplaypresentchange', this._detachIfAttached);
  107320. };
  107321. /**
  107322. * Detaches the camera from the html element and disables VR
  107323. *
  107324. * @param element html element to detach from
  107325. */
  107326. WebVRFreeCamera.prototype.detachControl = function (element) {
  107327. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  107328. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  107329. _super.prototype.detachControl.call(this, element);
  107330. this._attached = false;
  107331. this.getEngine().disableVR();
  107332. window.removeEventListener('vrdisplaypresentchange', this._detachIfAttached);
  107333. };
  107334. /**
  107335. * @returns the name of this class
  107336. */
  107337. WebVRFreeCamera.prototype.getClassName = function () {
  107338. return "WebVRFreeCamera";
  107339. };
  107340. /**
  107341. * Calls resetPose on the vrDisplay
  107342. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  107343. */
  107344. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  107345. //uses the vrDisplay's "resetPose()".
  107346. //pitch and roll won't be affected.
  107347. this._vrDevice.resetPose();
  107348. };
  107349. /**
  107350. * @hidden
  107351. * Updates the rig cameras (left and right eye)
  107352. */
  107353. WebVRFreeCamera.prototype._updateRigCameras = function () {
  107354. var camLeft = this._rigCameras[0];
  107355. var camRight = this._rigCameras[1];
  107356. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  107357. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  107358. camLeft.position.copyFrom(this._deviceRoomPosition);
  107359. camRight.position.copyFrom(this._deviceRoomPosition);
  107360. };
  107361. // Remove translation from 6dof headset if trackposition is set to false
  107362. WebVRFreeCamera.prototype._correctPositionIfNotTrackPosition = function (matrix, isViewMatrix) {
  107363. if (isViewMatrix === void 0) { isViewMatrix = false; }
  107364. if (this.rawPose && this.rawPose.position && !this.webVROptions.trackPosition) {
  107365. BABYLON.Matrix.TranslationToRef(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2], this._tmpMatrix);
  107366. if (!isViewMatrix) {
  107367. this._tmpMatrix.invert();
  107368. }
  107369. this._tmpMatrix.multiplyToRef(matrix, matrix);
  107370. }
  107371. };
  107372. /**
  107373. * @hidden
  107374. * Updates the cached values of the camera
  107375. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  107376. */
  107377. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  107378. var _this = this;
  107379. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  107380. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  107381. if (!this.updateCacheCalled) {
  107382. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  107383. this.updateCacheCalled = true;
  107384. this.update();
  107385. }
  107386. // Set working vector to the device position in room space rotated by the new rotation
  107387. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  107388. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  107389. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  107390. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  107391. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  107392. // Add translation from anchor position
  107393. this._deviceToWorld.getTranslationToRef(this._workingVector);
  107394. this._workingVector.addInPlace(this.position);
  107395. this._workingVector.subtractInPlace(this._cache.position);
  107396. this._deviceToWorld.setTranslation(this._workingVector);
  107397. // Set an inverted matrix to be used when updating the camera
  107398. this._deviceToWorld.invertToRef(this._worldToDevice);
  107399. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  107400. this.controllers.forEach(function (controller) {
  107401. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  107402. _this._correctPositionIfNotTrackPosition(controller._deviceToWorld);
  107403. controller.update();
  107404. });
  107405. }
  107406. if (!ignoreParentClass) {
  107407. _super.prototype._updateCache.call(this);
  107408. }
  107409. this.updateCacheCalled = false;
  107410. };
  107411. /**
  107412. * @hidden
  107413. * Get current device position in babylon world
  107414. */
  107415. WebVRFreeCamera.prototype._computeDevicePosition = function () {
  107416. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  107417. };
  107418. /**
  107419. * Updates the current device position and rotation in the babylon world
  107420. */
  107421. WebVRFreeCamera.prototype.update = function () {
  107422. this._computeDevicePosition();
  107423. // Get current device rotation in babylon world
  107424. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  107425. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  107426. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  107427. if (this._poseSet) {
  107428. this.onPoseUpdatedFromDeviceObservable.notifyObservers(null);
  107429. }
  107430. _super.prototype.update.call(this);
  107431. };
  107432. /**
  107433. * @hidden
  107434. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  107435. * @returns an identity matrix
  107436. */
  107437. WebVRFreeCamera.prototype._getViewMatrix = function () {
  107438. return BABYLON.Matrix.Identity();
  107439. };
  107440. /**
  107441. * This function is called by the two RIG cameras.
  107442. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  107443. */
  107444. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  107445. // Update the parent camera prior to using a child camera to avoid desynchronization
  107446. var parentCamera = this._cameraRigParams["parentCamera"];
  107447. parentCamera._updateCache();
  107448. //WebVR 1.1
  107449. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  107450. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  107451. if (!this.getScene().useRightHandedSystem) {
  107452. this._webvrViewMatrix.toggleModelMatrixHandInPlace();
  107453. }
  107454. // update the camera rotation matrix
  107455. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  107456. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  107457. // Computing target and final matrix
  107458. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  107459. // should the view matrix be updated with scale and position offset?
  107460. if (parentCamera.deviceScaleFactor !== 1) {
  107461. this._webvrViewMatrix.invert();
  107462. // scale the position, if set
  107463. if (parentCamera.deviceScaleFactor) {
  107464. this._webvrViewMatrix.multiplyAtIndex(12, parentCamera.deviceScaleFactor);
  107465. this._webvrViewMatrix.multiplyAtIndex(13, parentCamera.deviceScaleFactor);
  107466. this._webvrViewMatrix.multiplyAtIndex(14, parentCamera.deviceScaleFactor);
  107467. }
  107468. this._webvrViewMatrix.invert();
  107469. }
  107470. // Remove translation from 6dof headset if trackposition is set to false
  107471. parentCamera._correctPositionIfNotTrackPosition(this._webvrViewMatrix, true);
  107472. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  107473. // Compute global position
  107474. this._workingMatrix = this._workingMatrix || BABYLON.Matrix.Identity();
  107475. this._webvrViewMatrix.invertToRef(this._workingMatrix);
  107476. this._workingMatrix.multiplyToRef(parentCamera.getWorldMatrix(), this._workingMatrix);
  107477. this._workingMatrix.getTranslationToRef(this._globalPosition);
  107478. this._markSyncedWithParent();
  107479. return this._webvrViewMatrix;
  107480. };
  107481. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  107482. var parentCamera = this.parent;
  107483. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  107484. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  107485. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  107486. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  107487. //babylon compatible matrix
  107488. if (!this.getScene().useRightHandedSystem) {
  107489. this._projectionMatrix.toggleProjectionMatrixHandInPlace();
  107490. }
  107491. return this._projectionMatrix;
  107492. };
  107493. /**
  107494. * Initializes the controllers and their meshes
  107495. */
  107496. WebVRFreeCamera.prototype.initControllers = function () {
  107497. var _this = this;
  107498. this.controllers = [];
  107499. var manager = this.getScene().gamepadManager;
  107500. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  107501. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  107502. var webVrController = gamepad;
  107503. if (webVrController.defaultModel) {
  107504. webVrController.defaultModel.setEnabled(false);
  107505. }
  107506. if (webVrController.hand === "right") {
  107507. _this._rightController = null;
  107508. }
  107509. if (webVrController.hand === "left") {
  107510. _this._leftController = null;
  107511. }
  107512. var controllerIndex = _this.controllers.indexOf(webVrController);
  107513. if (controllerIndex !== -1) {
  107514. _this.controllers.splice(controllerIndex, 1);
  107515. }
  107516. }
  107517. });
  107518. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  107519. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  107520. var webVrController_1 = gamepad;
  107521. if (!_this.webVROptions.trackPosition) {
  107522. webVrController_1._disableTrackPosition(new BABYLON.Vector3(webVrController_1.hand == "left" ? -0.15 : 0.15, -0.5, 0.25));
  107523. // Cache must be updated before rendering controllers to avoid them being one frame behind
  107524. if (!_this._updateCacheWhenTrackingDisabledObserver) {
  107525. _this._updateCacheWhenTrackingDisabledObserver = _this._scene.onBeforeRenderObservable.add(function () {
  107526. _this._updateCache();
  107527. });
  107528. }
  107529. }
  107530. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  107531. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  107532. _this._correctPositionIfNotTrackPosition(webVrController_1._deviceToWorld);
  107533. if (_this.webVROptions.controllerMeshes) {
  107534. if (webVrController_1.defaultModel) {
  107535. webVrController_1.defaultModel.setEnabled(true);
  107536. }
  107537. else {
  107538. // Load the meshes
  107539. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  107540. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  107541. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  107542. if (_this.webVROptions.defaultLightingOnControllers) {
  107543. if (!_this._lightOnControllers) {
  107544. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  107545. }
  107546. var activateLightOnSubMeshes_1 = function (mesh, light) {
  107547. var children = mesh.getChildren();
  107548. if (children && children.length !== 0) {
  107549. children.forEach(function (mesh) {
  107550. light.includedOnlyMeshes.push(mesh);
  107551. activateLightOnSubMeshes_1(mesh, light);
  107552. });
  107553. }
  107554. };
  107555. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  107556. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  107557. }
  107558. });
  107559. }
  107560. }
  107561. webVrController_1.attachToPoseControlledCamera(_this);
  107562. // since this is async - sanity check. Is the controller already stored?
  107563. if (_this.controllers.indexOf(webVrController_1) === -1) {
  107564. //add to the controllers array
  107565. _this.controllers.push(webVrController_1);
  107566. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  107567. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  107568. // So we're overriding setting left & right manually to be sure
  107569. var firstViveWandDetected = false;
  107570. for (var i = 0; i < _this.controllers.length; i++) {
  107571. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  107572. if (!firstViveWandDetected) {
  107573. firstViveWandDetected = true;
  107574. _this.controllers[i].hand = "left";
  107575. }
  107576. else {
  107577. _this.controllers[i].hand = "right";
  107578. }
  107579. }
  107580. }
  107581. //did we find enough controllers? Great! let the developer know.
  107582. if (_this.controllers.length >= 2) {
  107583. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  107584. }
  107585. }
  107586. }
  107587. });
  107588. };
  107589. return WebVRFreeCamera;
  107590. }(BABYLON.FreeCamera));
  107591. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  107592. })(BABYLON || (BABYLON = {}));
  107593. //# sourceMappingURL=babylon.webVRCamera.js.map
  107594. var BABYLON;
  107595. (function (BABYLON) {
  107596. BABYLON.Node.AddNodeConstructor("DeviceOrientationCamera", function (name, scene) {
  107597. return function () { return new DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  107598. });
  107599. // We're mainly based on the logic defined into the FreeCamera code
  107600. /**
  107601. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  107602. * being tilted forward or back and left or right.
  107603. */
  107604. var DeviceOrientationCamera = /** @class */ (function (_super) {
  107605. __extends(DeviceOrientationCamera, _super);
  107606. /**
  107607. * Creates a new device orientation camera
  107608. * @param name The name of the camera
  107609. * @param position The start position camera
  107610. * @param scene The scene the camera belongs to
  107611. */
  107612. function DeviceOrientationCamera(name, position, scene) {
  107613. var _this = _super.call(this, name, position, scene) || this;
  107614. _this._quaternionCache = new BABYLON.Quaternion();
  107615. _this.inputs.addDeviceOrientation();
  107616. return _this;
  107617. }
  107618. /**
  107619. * Gets the current instance class name ("DeviceOrientationCamera").
  107620. * This helps avoiding instanceof at run time.
  107621. * @returns the class name
  107622. */
  107623. DeviceOrientationCamera.prototype.getClassName = function () {
  107624. return "DeviceOrientationCamera";
  107625. };
  107626. /**
  107627. * @hidden
  107628. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  107629. */
  107630. DeviceOrientationCamera.prototype._checkInputs = function () {
  107631. _super.prototype._checkInputs.call(this);
  107632. this._quaternionCache.copyFrom(this.rotationQuaternion);
  107633. if (this._initialQuaternion) {
  107634. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  107635. }
  107636. };
  107637. /**
  107638. * Reset the camera to its default orientation on the specified axis only.
  107639. * @param axis The axis to reset
  107640. */
  107641. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  107642. var _this = this;
  107643. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  107644. //can only work if this camera has a rotation quaternion already.
  107645. if (!this.rotationQuaternion) {
  107646. return;
  107647. }
  107648. if (!this._initialQuaternion) {
  107649. this._initialQuaternion = new BABYLON.Quaternion();
  107650. }
  107651. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  107652. ['x', 'y', 'z'].forEach(function (axisName) {
  107653. if (!axis[axisName]) {
  107654. _this._initialQuaternion[axisName] = 0;
  107655. }
  107656. else {
  107657. _this._initialQuaternion[axisName] *= -1;
  107658. }
  107659. });
  107660. this._initialQuaternion.normalize();
  107661. //force rotation update
  107662. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  107663. };
  107664. return DeviceOrientationCamera;
  107665. }(BABYLON.FreeCamera));
  107666. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  107667. })(BABYLON || (BABYLON = {}));
  107668. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  107669. var BABYLON;
  107670. (function (BABYLON) {
  107671. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) {
  107672. return function () { return new VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  107673. });
  107674. /**
  107675. * Camera used to simulate VR rendering (based on FreeCamera)
  107676. * @see http://doc.babylonjs.com/babylon101/cameras#vr-device-orientation-cameras
  107677. */
  107678. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  107679. __extends(VRDeviceOrientationFreeCamera, _super);
  107680. /**
  107681. * Creates a new VRDeviceOrientationFreeCamera
  107682. * @param name defines camera name
  107683. * @param position defines the start position of the camera
  107684. * @param scene defines the scene the camera belongs to
  107685. * @param compensateDistortion defines if the camera needs to compensate the lens distorsion
  107686. * @param vrCameraMetrics defines the vr metrics associated to the camera
  107687. */
  107688. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  107689. if (compensateDistortion === void 0) { compensateDistortion = true; }
  107690. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  107691. var _this = _super.call(this, name, position, scene) || this;
  107692. vrCameraMetrics.compensateDistortion = compensateDistortion;
  107693. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  107694. return _this;
  107695. }
  107696. /**
  107697. * Gets camera class name
  107698. * @returns VRDeviceOrientationFreeCamera
  107699. */
  107700. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  107701. return "VRDeviceOrientationFreeCamera";
  107702. };
  107703. return VRDeviceOrientationFreeCamera;
  107704. }(BABYLON.DeviceOrientationCamera));
  107705. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  107706. })(BABYLON || (BABYLON = {}));
  107707. //# sourceMappingURL=babylon.vrDeviceOrientationFreeCamera.js.map
  107708. var BABYLON;
  107709. (function (BABYLON) {
  107710. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) {
  107711. return function () { return new VRDeviceOrientationArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  107712. });
  107713. /**
  107714. * Camera used to simulate VR rendering (based on ArcRotateCamera)
  107715. * @see http://doc.babylonjs.com/babylon101/cameras#vr-device-orientation-cameras
  107716. */
  107717. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  107718. __extends(VRDeviceOrientationArcRotateCamera, _super);
  107719. /**
  107720. * Creates a new VRDeviceOrientationArcRotateCamera
  107721. * @param name defines camera name
  107722. * @param alpha defines the camera rotation along the logitudinal axis
  107723. * @param beta defines the camera rotation along the latitudinal axis
  107724. * @param radius defines the camera distance from its target
  107725. * @param target defines the camera target
  107726. * @param scene defines the scene the camera belongs to
  107727. * @param compensateDistortion defines if the camera needs to compensate the lens distorsion
  107728. * @param vrCameraMetrics defines the vr metrics associated to the camera
  107729. */
  107730. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  107731. if (compensateDistortion === void 0) { compensateDistortion = true; }
  107732. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  107733. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  107734. vrCameraMetrics.compensateDistortion = compensateDistortion;
  107735. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  107736. _this.inputs.addVRDeviceOrientation();
  107737. return _this;
  107738. }
  107739. /**
  107740. * Gets camera class name
  107741. * @returns VRDeviceOrientationArcRotateCamera
  107742. */
  107743. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  107744. return "VRDeviceOrientationArcRotateCamera";
  107745. };
  107746. return VRDeviceOrientationArcRotateCamera;
  107747. }(BABYLON.ArcRotateCamera));
  107748. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  107749. })(BABYLON || (BABYLON = {}));
  107750. //# sourceMappingURL=babylon.vrDeviceOrientationArcRotateCamera.js.map
  107751. var BABYLON;
  107752. (function (BABYLON) {
  107753. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationGamepadCamera", function (name, scene) {
  107754. return function () { return new VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  107755. });
  107756. /**
  107757. * Camera used to simulate VR rendering (based on VRDeviceOrientationFreeCamera)
  107758. * @see http://doc.babylonjs.com/babylon101/cameras#vr-device-orientation-cameras
  107759. */
  107760. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  107761. __extends(VRDeviceOrientationGamepadCamera, _super);
  107762. /**
  107763. * Creates a new VRDeviceOrientationGamepadCamera
  107764. * @param name defines camera name
  107765. * @param position defines the start position of the camera
  107766. * @param scene defines the scene the camera belongs to
  107767. * @param compensateDistortion defines if the camera needs to compensate the lens distorsion
  107768. * @param vrCameraMetrics defines the vr metrics associated to the camera
  107769. */
  107770. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  107771. if (compensateDistortion === void 0) { compensateDistortion = true; }
  107772. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  107773. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  107774. _this.inputs.addGamepad();
  107775. return _this;
  107776. }
  107777. /**
  107778. * Gets camera class name
  107779. * @returns VRDeviceOrientationGamepadCamera
  107780. */
  107781. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  107782. return "VRDeviceOrientationGamepadCamera";
  107783. };
  107784. return VRDeviceOrientationGamepadCamera;
  107785. }(BABYLON.VRDeviceOrientationFreeCamera));
  107786. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  107787. })(BABYLON || (BABYLON = {}));
  107788. //# sourceMappingURL=babylon.vrDeviceOrientationGamepadCamera.js.map
  107789. var BABYLON;
  107790. (function (BABYLON) {
  107791. var VRExperienceHelperGazer = /** @class */ (function () {
  107792. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  107793. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  107794. this.scene = scene;
  107795. /** @hidden */
  107796. this._pointerDownOnMeshAsked = false;
  107797. /** @hidden */
  107798. this._isActionableMesh = false;
  107799. /** @hidden */
  107800. this._teleportationRequestInitiated = false;
  107801. /** @hidden */
  107802. this._teleportationBackRequestInitiated = false;
  107803. /** @hidden */
  107804. this._rotationRightAsked = false;
  107805. /** @hidden */
  107806. this._rotationLeftAsked = false;
  107807. /** @hidden */
  107808. this._dpadPressed = true;
  107809. /** @hidden */
  107810. this._activePointer = false;
  107811. this._id = VRExperienceHelperGazer._idCounter++;
  107812. // Gaze tracker
  107813. if (!gazeTrackerToClone) {
  107814. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  107815. this._gazeTracker.bakeCurrentTransformIntoVertices();
  107816. this._gazeTracker.isPickable = false;
  107817. this._gazeTracker.isVisible = false;
  107818. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  107819. targetMat.specularColor = BABYLON.Color3.Black();
  107820. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  107821. targetMat.backFaceCulling = false;
  107822. this._gazeTracker.material = targetMat;
  107823. }
  107824. else {
  107825. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  107826. }
  107827. }
  107828. /** @hidden */
  107829. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  107830. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  107831. };
  107832. /** @hidden */
  107833. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  107834. this._pointerDownOnMeshAsked = true;
  107835. if (this._currentHit) {
  107836. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  107837. }
  107838. };
  107839. /** @hidden */
  107840. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  107841. if (this._currentHit) {
  107842. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  107843. }
  107844. this._pointerDownOnMeshAsked = false;
  107845. };
  107846. /** @hidden */
  107847. VRExperienceHelperGazer.prototype._activatePointer = function () {
  107848. this._activePointer = true;
  107849. };
  107850. /** @hidden */
  107851. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  107852. this._activePointer = false;
  107853. };
  107854. /** @hidden */
  107855. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  107856. if (distance === void 0) { distance = 100; }
  107857. };
  107858. VRExperienceHelperGazer.prototype.dispose = function () {
  107859. this._interactionsEnabled = false;
  107860. this._teleportationEnabled = false;
  107861. if (this._gazeTracker) {
  107862. this._gazeTracker.dispose();
  107863. }
  107864. };
  107865. VRExperienceHelperGazer._idCounter = 0;
  107866. return VRExperienceHelperGazer;
  107867. }());
  107868. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  107869. __extends(VRExperienceHelperControllerGazer, _super);
  107870. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  107871. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  107872. _this.webVRController = webVRController;
  107873. // Laser pointer
  107874. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  107875. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  107876. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  107877. laserPointerMaterial.alpha = 0.6;
  107878. _this._laserPointer.material = laserPointerMaterial;
  107879. _this._laserPointer.rotation.x = Math.PI / 2;
  107880. _this._laserPointer.position.z = -0.5;
  107881. _this._laserPointer.isVisible = false;
  107882. _this._laserPointer.isPickable = false;
  107883. if (!webVRController.mesh) {
  107884. // Create an empty mesh that is used prior to loading the high quality model
  107885. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  107886. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  107887. preloadPointerPose.rotation.x = -0.7;
  107888. preloadMesh.addChild(preloadPointerPose);
  107889. webVRController.attachToMesh(preloadMesh);
  107890. }
  107891. _this._setLaserPointerParent(webVRController.mesh);
  107892. _this._meshAttachedObserver = webVRController._meshAttachedObservable.add(function (mesh) {
  107893. _this._setLaserPointerParent(mesh);
  107894. });
  107895. return _this;
  107896. }
  107897. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  107898. return this.webVRController.getForwardRay(length);
  107899. };
  107900. /** @hidden */
  107901. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  107902. _super.prototype._activatePointer.call(this);
  107903. this._laserPointer.isVisible = true;
  107904. };
  107905. /** @hidden */
  107906. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  107907. _super.prototype._deactivatePointer.call(this);
  107908. this._laserPointer.isVisible = false;
  107909. };
  107910. /** @hidden */
  107911. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  107912. this._laserPointer.material.emissiveColor = color;
  107913. };
  107914. /** @hidden */
  107915. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  107916. var makeNotPick = function (root) {
  107917. root.isPickable = false;
  107918. root.getChildMeshes().forEach(function (c) {
  107919. makeNotPick(c);
  107920. });
  107921. };
  107922. makeNotPick(mesh);
  107923. var meshChildren = mesh.getChildren(undefined, false);
  107924. var laserParent = mesh;
  107925. this.webVRController._pointingPoseNode = null;
  107926. for (var i = 0; i < meshChildren.length; i++) {
  107927. if (meshChildren[i].name && meshChildren[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  107928. laserParent = meshChildren[i];
  107929. this.webVRController._pointingPoseNode = laserParent;
  107930. break;
  107931. }
  107932. }
  107933. this._laserPointer.parent = laserParent;
  107934. };
  107935. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  107936. if (distance === void 0) { distance = 100; }
  107937. this._laserPointer.scaling.y = distance;
  107938. this._laserPointer.position.z = -distance / 2;
  107939. };
  107940. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  107941. _super.prototype.dispose.call(this);
  107942. this._laserPointer.dispose();
  107943. if (this._meshAttachedObserver) {
  107944. this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver);
  107945. }
  107946. };
  107947. return VRExperienceHelperControllerGazer;
  107948. }(VRExperienceHelperGazer));
  107949. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  107950. __extends(VRExperienceHelperCameraGazer, _super);
  107951. function VRExperienceHelperCameraGazer(getCamera, scene) {
  107952. var _this = _super.call(this, scene) || this;
  107953. _this.getCamera = getCamera;
  107954. return _this;
  107955. }
  107956. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  107957. var camera = this.getCamera();
  107958. if (camera) {
  107959. return camera.getForwardRay(length);
  107960. }
  107961. else {
  107962. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  107963. }
  107964. };
  107965. return VRExperienceHelperCameraGazer;
  107966. }(VRExperienceHelperGazer));
  107967. /**
  107968. * Helps to quickly add VR support to an existing scene.
  107969. * See http://doc.babylonjs.com/how_to/webvr_helper
  107970. */
  107971. var VRExperienceHelper = /** @class */ (function () {
  107972. /**
  107973. * Instantiates a VRExperienceHelper.
  107974. * Helps to quickly add VR support to an existing scene.
  107975. * @param scene The scene the VRExperienceHelper belongs to.
  107976. * @param webVROptions Options to modify the vr experience helper's behavior.
  107977. */
  107978. function VRExperienceHelper(scene,
  107979. /** Options to modify the vr experience helper's behavior. */
  107980. webVROptions) {
  107981. if (webVROptions === void 0) { webVROptions = {}; }
  107982. var _this = this;
  107983. this.webVROptions = webVROptions;
  107984. // Can the system support WebVR, even if a headset isn't plugged in?
  107985. this._webVRsupported = false;
  107986. // If WebVR is supported, is a headset plugged in and are we ready to present?
  107987. this._webVRready = false;
  107988. // Are we waiting for the requestPresent callback to complete?
  107989. this._webVRrequesting = false;
  107990. // Are we presenting to the headset right now? (this is the vrDevice state)
  107991. this._webVRpresenting = false;
  107992. // Are we presenting in the fullscreen fallback?
  107993. this._fullscreenVRpresenting = false;
  107994. /**
  107995. * Observable raised when entering VR.
  107996. */
  107997. this.onEnteringVRObservable = new BABYLON.Observable();
  107998. /**
  107999. * Observable raised when exiting VR.
  108000. */
  108001. this.onExitingVRObservable = new BABYLON.Observable();
  108002. /**
  108003. * Observable raised when controller mesh is loaded.
  108004. */
  108005. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  108006. this._useCustomVRButton = false;
  108007. this._teleportationRequested = false;
  108008. this._teleportActive = false;
  108009. this._floorMeshesCollection = [];
  108010. this._rotationAllowed = true;
  108011. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  108012. this._isDefaultTeleportationTarget = true;
  108013. this._teleportationFillColor = "#444444";
  108014. this._teleportationBorderColor = "#FFFFFF";
  108015. this._rotationAngle = 0;
  108016. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  108017. this._padSensibilityUp = 0.65;
  108018. this._padSensibilityDown = 0.35;
  108019. this._leftController = null;
  108020. this._rightController = null;
  108021. /**
  108022. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  108023. */
  108024. this.onNewMeshSelected = new BABYLON.Observable();
  108025. /**
  108026. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  108027. */
  108028. this.onNewMeshPicked = new BABYLON.Observable();
  108029. /**
  108030. * Observable raised before camera teleportation
  108031. */
  108032. this.onBeforeCameraTeleport = new BABYLON.Observable();
  108033. /**
  108034. * Observable raised after camera teleportation
  108035. */
  108036. this.onAfterCameraTeleport = new BABYLON.Observable();
  108037. /**
  108038. * Observable raised when current selected mesh gets unselected
  108039. */
  108040. this.onSelectedMeshUnselected = new BABYLON.Observable();
  108041. /**
  108042. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  108043. */
  108044. this.teleportationEnabled = true;
  108045. this._teleportationInitialized = false;
  108046. this._interactionsEnabled = false;
  108047. this._interactionsRequested = false;
  108048. this._displayGaze = true;
  108049. this._displayLaserPointer = true;
  108050. /**
  108051. * If the gaze trackers scale should be updated to be constant size when pointing at near/far meshes
  108052. */
  108053. this.updateGazeTrackerScale = true;
  108054. /**
  108055. * If the gaze trackers color should be updated when selecting meshes
  108056. */
  108057. this.updateGazeTrackerColor = true;
  108058. this._onResize = function () {
  108059. _this.moveButtonToBottomRight();
  108060. if (_this._fullscreenVRpresenting && _this._webVRready) {
  108061. _this.exitVR();
  108062. }
  108063. };
  108064. this._onFullscreenChange = function () {
  108065. if (document.fullscreen !== undefined) {
  108066. _this._fullscreenVRpresenting = document.fullscreen;
  108067. }
  108068. else if (document.mozFullScreen !== undefined) {
  108069. _this._fullscreenVRpresenting = document.mozFullScreen;
  108070. }
  108071. else if (document.webkitIsFullScreen !== undefined) {
  108072. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  108073. }
  108074. else if (document.msIsFullScreen !== undefined) {
  108075. _this._fullscreenVRpresenting = document.msIsFullScreen;
  108076. }
  108077. else if (document.msFullscreenElement !== undefined) {
  108078. _this._fullscreenVRpresenting = document.msFullscreenElement;
  108079. }
  108080. if (!_this._fullscreenVRpresenting && _this._canvas) {
  108081. _this.exitVR();
  108082. if (!_this._useCustomVRButton) {
  108083. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  108084. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  108085. }
  108086. }
  108087. };
  108088. this._cachedAngularSensibility = { angularSensibilityX: null, angularSensibilityY: null, angularSensibility: null };
  108089. this.beforeRender = function () {
  108090. if (_this._leftController && _this._leftController._activePointer) {
  108091. _this._castRayAndSelectObject(_this._leftController);
  108092. }
  108093. if (_this._rightController && _this._rightController._activePointer) {
  108094. _this._castRayAndSelectObject(_this._rightController);
  108095. }
  108096. if (_this._noControllerIsActive) {
  108097. _this._castRayAndSelectObject(_this._cameraGazer);
  108098. }
  108099. else {
  108100. _this._cameraGazer._gazeTracker.isVisible = false;
  108101. }
  108102. };
  108103. this._onNewGamepadConnected = function (gamepad) {
  108104. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  108105. if (gamepad.leftStick) {
  108106. gamepad.onleftstickchanged(function (stickValues) {
  108107. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  108108. // Listening to classic/xbox gamepad only if no VR controller is active
  108109. if ((!_this._leftController && !_this._rightController) ||
  108110. ((_this._leftController && !_this._leftController._activePointer) &&
  108111. (_this._rightController && !_this._rightController._activePointer))) {
  108112. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  108113. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  108114. }
  108115. }
  108116. });
  108117. }
  108118. if (gamepad.rightStick) {
  108119. gamepad.onrightstickchanged(function (stickValues) {
  108120. if (_this._teleportationInitialized) {
  108121. _this._checkRotate(stickValues, _this._cameraGazer);
  108122. }
  108123. });
  108124. }
  108125. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  108126. gamepad.onbuttondown(function (buttonPressed) {
  108127. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  108128. _this._cameraGazer._selectionPointerDown();
  108129. }
  108130. });
  108131. gamepad.onbuttonup(function (buttonPressed) {
  108132. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  108133. _this._cameraGazer._selectionPointerUp();
  108134. }
  108135. });
  108136. }
  108137. }
  108138. else {
  108139. var webVRController = gamepad;
  108140. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  108141. if (webVRController.hand === "right" || (_this._leftController && _this._leftController.webVRController != webVRController)) {
  108142. _this._rightController = controller;
  108143. }
  108144. else {
  108145. _this._leftController = controller;
  108146. }
  108147. _this._tryEnableInteractionOnController(controller);
  108148. }
  108149. };
  108150. // 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
  108151. this._tryEnableInteractionOnController = function (controller) {
  108152. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  108153. _this._enableInteractionOnController(controller);
  108154. }
  108155. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  108156. _this._enableTeleportationOnController(controller);
  108157. }
  108158. };
  108159. this._onNewGamepadDisconnected = function (gamepad) {
  108160. if (gamepad instanceof BABYLON.WebVRController) {
  108161. if (gamepad.hand === "left" && _this._leftController != null) {
  108162. _this._leftController.dispose();
  108163. _this._leftController = null;
  108164. }
  108165. if (gamepad.hand === "right" && _this._rightController != null) {
  108166. _this._rightController.dispose();
  108167. _this._rightController = null;
  108168. }
  108169. }
  108170. };
  108171. this._workingVector = BABYLON.Vector3.Zero();
  108172. this._workingQuaternion = BABYLON.Quaternion.Identity();
  108173. this._workingMatrix = BABYLON.Matrix.Identity();
  108174. this._scene = scene;
  108175. this._canvas = scene.getEngine().getRenderingCanvas();
  108176. // Parse options
  108177. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  108178. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  108179. }
  108180. if (webVROptions.createDeviceOrientationCamera === undefined) {
  108181. webVROptions.createDeviceOrientationCamera = true;
  108182. }
  108183. if (webVROptions.laserToggle === undefined) {
  108184. webVROptions.laserToggle = true;
  108185. }
  108186. if (webVROptions.defaultHeight === undefined) {
  108187. webVROptions.defaultHeight = 1.7;
  108188. }
  108189. if (webVROptions.useCustomVRButton) {
  108190. this._useCustomVRButton = true;
  108191. if (webVROptions.customVRButton) {
  108192. this._btnVR = webVROptions.customVRButton;
  108193. }
  108194. }
  108195. if (webVROptions.rayLength) {
  108196. this._rayLength = webVROptions.rayLength;
  108197. }
  108198. this._defaultHeight = webVROptions.defaultHeight;
  108199. if (webVROptions.positionScale) {
  108200. this._rayLength *= webVROptions.positionScale;
  108201. this._defaultHeight *= webVROptions.positionScale;
  108202. }
  108203. this._hasEnteredVR = false;
  108204. // Set position
  108205. if (this._scene.activeCamera) {
  108206. this._position = this._scene.activeCamera.position.clone();
  108207. }
  108208. else {
  108209. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  108210. }
  108211. // Set non-vr camera
  108212. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  108213. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  108214. // Copy data from existing camera
  108215. if (this._scene.activeCamera) {
  108216. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  108217. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  108218. // Set rotation from previous camera
  108219. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  108220. var targetCamera = this._scene.activeCamera;
  108221. if (targetCamera.rotationQuaternion) {
  108222. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  108223. }
  108224. else {
  108225. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  108226. }
  108227. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  108228. }
  108229. }
  108230. this._scene.activeCamera = this._deviceOrientationCamera;
  108231. if (this._canvas) {
  108232. this._scene.activeCamera.attachControl(this._canvas);
  108233. }
  108234. }
  108235. else {
  108236. this._existingCamera = this._scene.activeCamera;
  108237. }
  108238. // Create VR cameras
  108239. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  108240. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  108241. this._vrDeviceOrientationCamera.angularSensibility = Number.MAX_VALUE;
  108242. }
  108243. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  108244. this._webVRCamera.useStandingMatrix();
  108245. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  108246. // Create default button
  108247. if (!this._useCustomVRButton) {
  108248. this._btnVR = document.createElement("BUTTON");
  108249. this._btnVR.className = "babylonVRicon";
  108250. this._btnVR.id = "babylonVRiconbtn";
  108251. this._btnVR.title = "Click to switch to VR";
  108252. 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) }";
  108253. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  108254. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  108255. // css += ".babylonVRicon.vrdisplaysupported { }";
  108256. // css += ".babylonVRicon.vrdisplayready { }";
  108257. // css += ".babylonVRicon.vrdisplayrequesting { }";
  108258. var style = document.createElement('style');
  108259. style.appendChild(document.createTextNode(css));
  108260. document.getElementsByTagName('head')[0].appendChild(style);
  108261. this.moveButtonToBottomRight();
  108262. }
  108263. // VR button click event
  108264. if (this._btnVR) {
  108265. this._btnVR.addEventListener("click", function () {
  108266. if (!_this.isInVRMode) {
  108267. _this.enterVR();
  108268. }
  108269. else {
  108270. _this.exitVR();
  108271. }
  108272. });
  108273. }
  108274. // Window events
  108275. window.addEventListener("resize", this._onResize);
  108276. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  108277. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  108278. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  108279. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  108280. document.onmsfullscreenchange = this._onFullscreenChange;
  108281. // Display vr button when headset is connected
  108282. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  108283. this.displayVRButton();
  108284. }
  108285. else {
  108286. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  108287. if (e.vrDisplay) {
  108288. _this.displayVRButton();
  108289. }
  108290. });
  108291. }
  108292. // Exiting VR mode using 'ESC' key on desktop
  108293. this._onKeyDown = function (event) {
  108294. if (event.keyCode === 27 && _this.isInVRMode) {
  108295. _this.exitVR();
  108296. }
  108297. };
  108298. document.addEventListener("keydown", this._onKeyDown);
  108299. // Exiting VR mode double tapping the touch screen
  108300. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  108301. if (_this.isInVRMode) {
  108302. _this.exitVR();
  108303. if (_this._fullscreenVRpresenting) {
  108304. _this._scene.getEngine().switchFullscreen(true);
  108305. }
  108306. }
  108307. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  108308. // Listen for WebVR display changes
  108309. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  108310. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  108311. this._onVRRequestPresentStart = function () {
  108312. _this._webVRrequesting = true;
  108313. _this.updateButtonVisibility();
  108314. };
  108315. this._onVRRequestPresentComplete = function (success) {
  108316. _this._webVRrequesting = false;
  108317. _this.updateButtonVisibility();
  108318. };
  108319. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  108320. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  108321. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  108322. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  108323. scene.onDisposeObservable.add(function () {
  108324. _this.dispose();
  108325. });
  108326. // Gamepad connection events
  108327. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  108328. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  108329. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  108330. this.updateButtonVisibility();
  108331. //create easing functions
  108332. this._circleEase = new BABYLON.CircleEase();
  108333. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  108334. if (this.webVROptions.floorMeshes) {
  108335. this.enableTeleportation({ floorMeshes: this.webVROptions.floorMeshes });
  108336. }
  108337. }
  108338. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  108339. /** Return this.onEnteringVRObservable
  108340. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  108341. */
  108342. get: function () {
  108343. return this.onEnteringVRObservable;
  108344. },
  108345. enumerable: true,
  108346. configurable: true
  108347. });
  108348. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  108349. /** Return this.onExitingVRObservable
  108350. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  108351. */
  108352. get: function () {
  108353. return this.onExitingVRObservable;
  108354. },
  108355. enumerable: true,
  108356. configurable: true
  108357. });
  108358. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  108359. /** Return this.onControllerMeshLoadedObservable
  108360. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  108361. */
  108362. get: function () {
  108363. return this.onControllerMeshLoadedObservable;
  108364. },
  108365. enumerable: true,
  108366. configurable: true
  108367. });
  108368. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  108369. /**
  108370. * The mesh used to display where the user is going to teleport.
  108371. */
  108372. get: function () {
  108373. return this._teleportationTarget;
  108374. },
  108375. /**
  108376. * Sets the mesh to be used to display where the user is going to teleport.
  108377. */
  108378. set: function (value) {
  108379. if (value) {
  108380. value.name = "teleportationTarget";
  108381. this._isDefaultTeleportationTarget = false;
  108382. this._teleportationTarget = value;
  108383. }
  108384. },
  108385. enumerable: true,
  108386. configurable: true
  108387. });
  108388. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  108389. /**
  108390. * 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
  108391. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  108392. * See http://doc.babylonjs.com/resources/baking_transformations
  108393. */
  108394. get: function () {
  108395. return this._cameraGazer._gazeTracker;
  108396. },
  108397. set: function (value) {
  108398. if (value) {
  108399. // Dispose of existing meshes
  108400. if (this._cameraGazer._gazeTracker) {
  108401. this._cameraGazer._gazeTracker.dispose();
  108402. }
  108403. if (this._leftController && this._leftController._gazeTracker) {
  108404. this._leftController._gazeTracker.dispose();
  108405. }
  108406. if (this._rightController && this._rightController._gazeTracker) {
  108407. this._rightController._gazeTracker.dispose();
  108408. }
  108409. // Set and create gaze trackers on head and controllers
  108410. this._cameraGazer._gazeTracker = value;
  108411. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  108412. this._cameraGazer._gazeTracker.isPickable = false;
  108413. this._cameraGazer._gazeTracker.isVisible = false;
  108414. this._cameraGazer._gazeTracker.name = "gazeTracker";
  108415. if (this._leftController) {
  108416. this._leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  108417. }
  108418. if (this._rightController) {
  108419. this._rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  108420. }
  108421. }
  108422. },
  108423. enumerable: true,
  108424. configurable: true
  108425. });
  108426. Object.defineProperty(VRExperienceHelper.prototype, "leftControllerGazeTrackerMesh", {
  108427. /**
  108428. * The gaze tracking mesh corresponding to the left controller
  108429. */
  108430. get: function () {
  108431. if (this._leftController) {
  108432. return this._leftController._gazeTracker;
  108433. }
  108434. return null;
  108435. },
  108436. enumerable: true,
  108437. configurable: true
  108438. });
  108439. Object.defineProperty(VRExperienceHelper.prototype, "rightControllerGazeTrackerMesh", {
  108440. /**
  108441. * The gaze tracking mesh corresponding to the right controller
  108442. */
  108443. get: function () {
  108444. if (this._rightController) {
  108445. return this._rightController._gazeTracker;
  108446. }
  108447. return null;
  108448. },
  108449. enumerable: true,
  108450. configurable: true
  108451. });
  108452. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  108453. /**
  108454. * If the ray of the gaze should be displayed.
  108455. */
  108456. get: function () {
  108457. return this._displayGaze;
  108458. },
  108459. /**
  108460. * Sets if the ray of the gaze should be displayed.
  108461. */
  108462. set: function (value) {
  108463. this._displayGaze = value;
  108464. if (!value) {
  108465. this._cameraGazer._gazeTracker.isVisible = false;
  108466. if (this._leftController) {
  108467. this._leftController._gazeTracker.isVisible = false;
  108468. }
  108469. if (this._rightController) {
  108470. this._rightController._gazeTracker.isVisible = false;
  108471. }
  108472. }
  108473. },
  108474. enumerable: true,
  108475. configurable: true
  108476. });
  108477. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  108478. /**
  108479. * If the ray of the LaserPointer should be displayed.
  108480. */
  108481. get: function () {
  108482. return this._displayLaserPointer;
  108483. },
  108484. /**
  108485. * Sets if the ray of the LaserPointer should be displayed.
  108486. */
  108487. set: function (value) {
  108488. this._displayLaserPointer = value;
  108489. if (!value) {
  108490. if (this._rightController) {
  108491. this._rightController._deactivatePointer();
  108492. this._rightController._gazeTracker.isVisible = false;
  108493. }
  108494. if (this._leftController) {
  108495. this._leftController._deactivatePointer();
  108496. this._leftController._gazeTracker.isVisible = false;
  108497. }
  108498. }
  108499. else {
  108500. if (this._rightController) {
  108501. this._rightController._activatePointer();
  108502. }
  108503. if (this._leftController) {
  108504. this._leftController._activatePointer();
  108505. }
  108506. }
  108507. },
  108508. enumerable: true,
  108509. configurable: true
  108510. });
  108511. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  108512. /**
  108513. * The deviceOrientationCamera used as the camera when not in VR.
  108514. */
  108515. get: function () {
  108516. return this._deviceOrientationCamera;
  108517. },
  108518. enumerable: true,
  108519. configurable: true
  108520. });
  108521. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  108522. /**
  108523. * Based on the current WebVR support, returns the current VR camera used.
  108524. */
  108525. get: function () {
  108526. if (this._webVRready) {
  108527. return this._webVRCamera;
  108528. }
  108529. else {
  108530. return this._scene.activeCamera;
  108531. }
  108532. },
  108533. enumerable: true,
  108534. configurable: true
  108535. });
  108536. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  108537. /**
  108538. * The webVRCamera which is used when in VR.
  108539. */
  108540. get: function () {
  108541. return this._webVRCamera;
  108542. },
  108543. enumerable: true,
  108544. configurable: true
  108545. });
  108546. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  108547. /**
  108548. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  108549. */
  108550. get: function () {
  108551. return this._vrDeviceOrientationCamera;
  108552. },
  108553. enumerable: true,
  108554. configurable: true
  108555. });
  108556. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  108557. get: function () {
  108558. var result = this._cameraGazer._teleportationRequestInitiated
  108559. || (this._leftController !== null && this._leftController._teleportationRequestInitiated)
  108560. || (this._rightController !== null && this._rightController._teleportationRequestInitiated);
  108561. return result;
  108562. },
  108563. enumerable: true,
  108564. configurable: true
  108565. });
  108566. // Raised when one of the controller has loaded successfully its associated default mesh
  108567. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  108568. if (this._leftController && this._leftController.webVRController == webVRController) {
  108569. if (webVRController.mesh) {
  108570. this._leftController._setLaserPointerParent(webVRController.mesh);
  108571. }
  108572. }
  108573. if (this._rightController && this._rightController.webVRController == webVRController) {
  108574. if (webVRController.mesh) {
  108575. this._rightController._setLaserPointerParent(webVRController.mesh);
  108576. }
  108577. }
  108578. try {
  108579. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  108580. }
  108581. catch (err) {
  108582. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  108583. }
  108584. };
  108585. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  108586. /**
  108587. * Gets a value indicating if we are currently in VR mode.
  108588. */
  108589. get: function () {
  108590. return this._webVRpresenting || this._fullscreenVRpresenting;
  108591. },
  108592. enumerable: true,
  108593. configurable: true
  108594. });
  108595. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  108596. var vrDisplay = this._scene.getEngine().getVRDevice();
  108597. if (vrDisplay) {
  108598. var wasPresenting = this._webVRpresenting;
  108599. this._webVRpresenting = vrDisplay.isPresenting;
  108600. if (wasPresenting && !this._webVRpresenting) {
  108601. this.exitVR();
  108602. }
  108603. }
  108604. else {
  108605. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  108606. }
  108607. this.updateButtonVisibility();
  108608. };
  108609. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  108610. this._webVRsupported = eventArgs.vrSupported;
  108611. this._webVRready = !!eventArgs.vrDisplay;
  108612. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  108613. this.updateButtonVisibility();
  108614. };
  108615. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  108616. if (this._canvas && !this._useCustomVRButton) {
  108617. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  108618. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  108619. }
  108620. };
  108621. VRExperienceHelper.prototype.displayVRButton = function () {
  108622. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  108623. document.body.appendChild(this._btnVR);
  108624. this._btnVRDisplayed = true;
  108625. }
  108626. };
  108627. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  108628. if (!this._btnVR || this._useCustomVRButton) {
  108629. return;
  108630. }
  108631. this._btnVR.className = "babylonVRicon";
  108632. if (this.isInVRMode) {
  108633. this._btnVR.className += " vrdisplaypresenting";
  108634. }
  108635. else {
  108636. if (this._webVRready) {
  108637. this._btnVR.className += " vrdisplayready";
  108638. }
  108639. if (this._webVRsupported) {
  108640. this._btnVR.className += " vrdisplaysupported";
  108641. }
  108642. if (this._webVRrequesting) {
  108643. this._btnVR.className += " vrdisplayrequesting";
  108644. }
  108645. }
  108646. };
  108647. /**
  108648. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  108649. * Otherwise, will use the fullscreen API.
  108650. */
  108651. VRExperienceHelper.prototype.enterVR = function () {
  108652. if (this.onEnteringVRObservable) {
  108653. try {
  108654. this.onEnteringVRObservable.notifyObservers(this);
  108655. }
  108656. catch (err) {
  108657. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  108658. }
  108659. }
  108660. if (this._scene.activeCamera) {
  108661. this._position = this._scene.activeCamera.position.clone();
  108662. if (this.vrDeviceOrientationCamera) {
  108663. this.vrDeviceOrientationCamera.rotation = BABYLON.Quaternion.FromRotationMatrix(this._scene.activeCamera.getWorldMatrix().getRotationMatrix()).toEulerAngles();
  108664. this.vrDeviceOrientationCamera.angularSensibility = 2000;
  108665. }
  108666. if (this.webVRCamera) {
  108667. var currentYRotation = this.webVRCamera.deviceRotationQuaternion.toEulerAngles().y;
  108668. var desiredYRotation = BABYLON.Quaternion.FromRotationMatrix(this._scene.activeCamera.getWorldMatrix().getRotationMatrix()).toEulerAngles().y;
  108669. var delta = desiredYRotation - currentYRotation;
  108670. var currentGlobalRotation = this.webVRCamera.rotationQuaternion.toEulerAngles().y;
  108671. this.webVRCamera.rotationQuaternion = BABYLON.Quaternion.FromEulerAngles(0, currentGlobalRotation + delta, 0);
  108672. }
  108673. // make sure that we return to the last active camera
  108674. this._existingCamera = this._scene.activeCamera;
  108675. // Remove and cache angular sensability to avoid camera rotation when in VR
  108676. if (this._existingCamera.angularSensibilityX) {
  108677. this._cachedAngularSensibility.angularSensibilityX = this._existingCamera.angularSensibilityX;
  108678. this._existingCamera.angularSensibilityX = Number.MAX_VALUE;
  108679. }
  108680. if (this._existingCamera.angularSensibilityY) {
  108681. this._cachedAngularSensibility.angularSensibilityY = this._existingCamera.angularSensibilityY;
  108682. this._existingCamera.angularSensibilityY = Number.MAX_VALUE;
  108683. }
  108684. if (this._existingCamera.angularSensibility) {
  108685. this._cachedAngularSensibility.angularSensibility = this._existingCamera.angularSensibility;
  108686. this._existingCamera.angularSensibility = Number.MAX_VALUE;
  108687. }
  108688. }
  108689. if (this._webVRrequesting) {
  108690. return;
  108691. }
  108692. // If WebVR is supported and a headset is connected
  108693. if (this._webVRready) {
  108694. if (!this._webVRpresenting) {
  108695. this._webVRCamera.position = this._position;
  108696. this._scene.activeCamera = this._webVRCamera;
  108697. }
  108698. }
  108699. else if (this._vrDeviceOrientationCamera) {
  108700. this._vrDeviceOrientationCamera.position = this._position;
  108701. if (this._scene.activeCamera) {
  108702. this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  108703. }
  108704. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  108705. this._scene.getEngine().switchFullscreen(true);
  108706. this.updateButtonVisibility();
  108707. }
  108708. if (this._scene.activeCamera && this._canvas) {
  108709. this._scene.activeCamera.attachControl(this._canvas);
  108710. }
  108711. if (this._interactionsEnabled) {
  108712. this._scene.registerBeforeRender(this.beforeRender);
  108713. }
  108714. if (this._displayLaserPointer) {
  108715. [this._leftController, this._rightController].forEach(function (controller) {
  108716. if (controller) {
  108717. controller._activatePointer();
  108718. }
  108719. });
  108720. }
  108721. this._hasEnteredVR = true;
  108722. };
  108723. /**
  108724. * Attempt to exit VR, or fullscreen.
  108725. */
  108726. VRExperienceHelper.prototype.exitVR = function () {
  108727. if (this._hasEnteredVR) {
  108728. if (this.onExitingVRObservable) {
  108729. try {
  108730. this.onExitingVRObservable.notifyObservers(this);
  108731. }
  108732. catch (err) {
  108733. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  108734. }
  108735. }
  108736. if (this._webVRpresenting) {
  108737. this._scene.getEngine().disableVR();
  108738. }
  108739. if (this._scene.activeCamera) {
  108740. this._position = this._scene.activeCamera.position.clone();
  108741. }
  108742. if (this.vrDeviceOrientationCamera) {
  108743. this.vrDeviceOrientationCamera.angularSensibility = Number.MAX_VALUE;
  108744. }
  108745. if (this._deviceOrientationCamera) {
  108746. this._deviceOrientationCamera.position = this._position;
  108747. this._scene.activeCamera = this._deviceOrientationCamera;
  108748. if (this._canvas) {
  108749. this._scene.activeCamera.attachControl(this._canvas);
  108750. }
  108751. // Restore angular sensibility
  108752. if (this._cachedAngularSensibility.angularSensibilityX) {
  108753. this._deviceOrientationCamera.angularSensibilityX = this._cachedAngularSensibility.angularSensibilityX;
  108754. this._cachedAngularSensibility.angularSensibilityX = null;
  108755. }
  108756. if (this._cachedAngularSensibility.angularSensibilityY) {
  108757. this._deviceOrientationCamera.angularSensibilityY = this._cachedAngularSensibility.angularSensibilityY;
  108758. this._cachedAngularSensibility.angularSensibilityY = null;
  108759. }
  108760. if (this._cachedAngularSensibility.angularSensibility) {
  108761. this._deviceOrientationCamera.angularSensibility = this._cachedAngularSensibility.angularSensibility;
  108762. this._cachedAngularSensibility.angularSensibility = null;
  108763. }
  108764. }
  108765. else if (this._existingCamera) {
  108766. this._existingCamera.position = this._position;
  108767. this._scene.activeCamera = this._existingCamera;
  108768. // Restore angular sensibility
  108769. if (this._cachedAngularSensibility.angularSensibilityX) {
  108770. this._existingCamera.angularSensibilityX = this._cachedAngularSensibility.angularSensibilityX;
  108771. this._cachedAngularSensibility.angularSensibilityX = null;
  108772. }
  108773. if (this._cachedAngularSensibility.angularSensibilityY) {
  108774. this._existingCamera.angularSensibilityY = this._cachedAngularSensibility.angularSensibilityY;
  108775. this._cachedAngularSensibility.angularSensibilityY = null;
  108776. }
  108777. if (this._cachedAngularSensibility.angularSensibility) {
  108778. this._existingCamera.angularSensibility = this._cachedAngularSensibility.angularSensibility;
  108779. this._cachedAngularSensibility.angularSensibility = null;
  108780. }
  108781. }
  108782. this.updateButtonVisibility();
  108783. if (this._interactionsEnabled) {
  108784. this._scene.unregisterBeforeRender(this.beforeRender);
  108785. this._cameraGazer._gazeTracker.isVisible = false;
  108786. if (this._leftController) {
  108787. this._leftController._gazeTracker.isVisible = false;
  108788. }
  108789. if (this._rightController) {
  108790. this._rightController._gazeTracker.isVisible = false;
  108791. }
  108792. }
  108793. // resize to update width and height when exiting vr exits fullscreen
  108794. this._scene.getEngine().resize();
  108795. [this._leftController, this._rightController].forEach(function (controller) {
  108796. if (controller) {
  108797. controller._deactivatePointer();
  108798. }
  108799. });
  108800. this._hasEnteredVR = false;
  108801. }
  108802. };
  108803. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  108804. /**
  108805. * The position of the vr experience helper.
  108806. */
  108807. get: function () {
  108808. return this._position;
  108809. },
  108810. /**
  108811. * Sets the position of the vr experience helper.
  108812. */
  108813. set: function (value) {
  108814. this._position = value;
  108815. if (this._scene.activeCamera) {
  108816. this._scene.activeCamera.position = value;
  108817. }
  108818. },
  108819. enumerable: true,
  108820. configurable: true
  108821. });
  108822. /**
  108823. * Enables controllers and user interactions such as selecting and object or clicking on an object.
  108824. */
  108825. VRExperienceHelper.prototype.enableInteractions = function () {
  108826. var _this = this;
  108827. if (!this._interactionsEnabled) {
  108828. this._interactionsRequested = true;
  108829. if (this._leftController) {
  108830. this._enableInteractionOnController(this._leftController);
  108831. }
  108832. if (this._rightController) {
  108833. this._enableInteractionOnController(this._rightController);
  108834. }
  108835. this.raySelectionPredicate = function (mesh) {
  108836. return mesh.isVisible && (mesh.isPickable || mesh.name === _this._floorMeshName);
  108837. };
  108838. this.meshSelectionPredicate = function (mesh) {
  108839. return true;
  108840. };
  108841. this._raySelectionPredicate = function (mesh) {
  108842. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  108843. && mesh.name.indexOf("teleportationTarget") === -1
  108844. && mesh.name.indexOf("torusTeleportation") === -1)) {
  108845. return _this.raySelectionPredicate(mesh);
  108846. }
  108847. return false;
  108848. };
  108849. this._interactionsEnabled = true;
  108850. }
  108851. };
  108852. Object.defineProperty(VRExperienceHelper.prototype, "_noControllerIsActive", {
  108853. get: function () {
  108854. return !(this._leftController && this._leftController._activePointer) && !(this._rightController && this._rightController._activePointer);
  108855. },
  108856. enumerable: true,
  108857. configurable: true
  108858. });
  108859. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  108860. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  108861. if (this._floorMeshesCollection[i].id === mesh.id) {
  108862. return true;
  108863. }
  108864. }
  108865. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  108866. return true;
  108867. }
  108868. return false;
  108869. };
  108870. /**
  108871. * Adds a floor mesh to be used for teleportation.
  108872. * @param floorMesh the mesh to be used for teleportation.
  108873. */
  108874. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  108875. if (!this._floorMeshesCollection) {
  108876. return;
  108877. }
  108878. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  108879. return;
  108880. }
  108881. this._floorMeshesCollection.push(floorMesh);
  108882. };
  108883. /**
  108884. * Removes a floor mesh from being used for teleportation.
  108885. * @param floorMesh the mesh to be removed.
  108886. */
  108887. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  108888. if (!this._floorMeshesCollection) {
  108889. return;
  108890. }
  108891. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  108892. if (meshIndex !== -1) {
  108893. this._floorMeshesCollection.splice(meshIndex, 1);
  108894. }
  108895. };
  108896. /**
  108897. * Enables interactions and teleportation using the VR controllers and gaze.
  108898. * @param vrTeleportationOptions options to modify teleportation behavior.
  108899. */
  108900. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  108901. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  108902. if (!this._teleportationInitialized) {
  108903. this._teleportationRequested = true;
  108904. this.enableInteractions();
  108905. if (vrTeleportationOptions.floorMeshName) {
  108906. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  108907. }
  108908. if (vrTeleportationOptions.floorMeshes) {
  108909. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  108910. }
  108911. if (this._leftController != null) {
  108912. this._enableTeleportationOnController(this._leftController);
  108913. }
  108914. if (this._rightController != null) {
  108915. this._enableTeleportationOnController(this._rightController);
  108916. }
  108917. // Creates an image processing post process for the vignette not relying
  108918. // on the main scene configuration for image processing to reduce setup and spaces
  108919. // (gamma/linear) conflicts.
  108920. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  108921. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  108922. imageProcessingConfiguration.vignetteEnabled = true;
  108923. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  108924. this._webVRCamera.detachPostProcess(this._postProcessMove);
  108925. this._teleportationInitialized = true;
  108926. if (this._isDefaultTeleportationTarget) {
  108927. this._createTeleportationCircles();
  108928. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  108929. }
  108930. }
  108931. };
  108932. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  108933. var _this = this;
  108934. var controllerMesh = controller.webVRController.mesh;
  108935. if (controllerMesh) {
  108936. controller._interactionsEnabled = true;
  108937. if (this.isInVRMode && this._displayLaserPointer) {
  108938. controller._activatePointer();
  108939. }
  108940. if (this.webVROptions.laserToggle) {
  108941. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  108942. // Enabling / disabling laserPointer
  108943. if (_this._displayLaserPointer && stateObject.value === 1) {
  108944. if (controller._activePointer) {
  108945. controller._deactivatePointer();
  108946. }
  108947. else {
  108948. controller._activatePointer();
  108949. }
  108950. if (_this.displayGaze) {
  108951. controller._gazeTracker.isVisible = controller._activePointer;
  108952. }
  108953. }
  108954. });
  108955. }
  108956. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  108957. var gazer = controller;
  108958. if (_this._noControllerIsActive) {
  108959. gazer = _this._cameraGazer;
  108960. }
  108961. if (!gazer._pointerDownOnMeshAsked) {
  108962. if (stateObject.value > _this._padSensibilityUp) {
  108963. gazer._selectionPointerDown();
  108964. }
  108965. }
  108966. else if (stateObject.value < _this._padSensibilityDown) {
  108967. gazer._selectionPointerUp();
  108968. }
  108969. });
  108970. }
  108971. };
  108972. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  108973. // Dont teleport if another gaze already requested teleportation
  108974. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  108975. return;
  108976. }
  108977. if (!gazer._teleportationRequestInitiated) {
  108978. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  108979. gazer._activatePointer();
  108980. gazer._teleportationRequestInitiated = true;
  108981. }
  108982. }
  108983. else {
  108984. // Listening to the proper controller values changes to confirm teleportation
  108985. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  108986. if (this._teleportActive) {
  108987. this.teleportCamera(this._haloCenter);
  108988. }
  108989. gazer._teleportationRequestInitiated = false;
  108990. }
  108991. }
  108992. };
  108993. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  108994. // Only rotate when user is not currently selecting a teleportation location
  108995. if (gazer._teleportationRequestInitiated) {
  108996. return;
  108997. }
  108998. if (!gazer._rotationLeftAsked) {
  108999. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  109000. gazer._rotationLeftAsked = true;
  109001. if (this._rotationAllowed) {
  109002. this._rotateCamera(false);
  109003. }
  109004. }
  109005. }
  109006. else {
  109007. if (stateObject.x > -this._padSensibilityDown) {
  109008. gazer._rotationLeftAsked = false;
  109009. }
  109010. }
  109011. if (!gazer._rotationRightAsked) {
  109012. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  109013. gazer._rotationRightAsked = true;
  109014. if (this._rotationAllowed) {
  109015. this._rotateCamera(true);
  109016. }
  109017. }
  109018. }
  109019. else {
  109020. if (stateObject.x < this._padSensibilityDown) {
  109021. gazer._rotationRightAsked = false;
  109022. }
  109023. }
  109024. };
  109025. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  109026. // Only teleport backwards when user is not currently selecting a teleportation location
  109027. if (gazer._teleportationRequestInitiated) {
  109028. return;
  109029. }
  109030. // Teleport backwards
  109031. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  109032. if (!gazer._teleportationBackRequestInitiated) {
  109033. if (!this.currentVRCamera) {
  109034. return;
  109035. }
  109036. // Get rotation and position of the current camera
  109037. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  109038. var position = this.currentVRCamera.position;
  109039. // If the camera has device position, use that instead
  109040. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  109041. rotation = this.currentVRCamera.deviceRotationQuaternion;
  109042. position = this.currentVRCamera.devicePosition;
  109043. }
  109044. // Get matrix with only the y rotation of the device rotation
  109045. rotation.toEulerAnglesToRef(this._workingVector);
  109046. this._workingVector.z = 0;
  109047. this._workingVector.x = 0;
  109048. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  109049. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  109050. // Rotate backwards ray by device rotation to cast at the ground behind the user
  109051. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  109052. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  109053. var ray = new BABYLON.Ray(position, this._workingVector);
  109054. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  109055. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  109056. this.teleportCamera(hit.pickedPoint);
  109057. }
  109058. gazer._teleportationBackRequestInitiated = true;
  109059. }
  109060. }
  109061. else {
  109062. gazer._teleportationBackRequestInitiated = false;
  109063. }
  109064. };
  109065. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  109066. var _this = this;
  109067. var controllerMesh = controller.webVRController.mesh;
  109068. if (controllerMesh) {
  109069. if (!controller._interactionsEnabled) {
  109070. this._enableInteractionOnController(controller);
  109071. }
  109072. controller._interactionsEnabled = true;
  109073. controller._teleportationEnabled = true;
  109074. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  109075. controller._dpadPressed = false;
  109076. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  109077. controller._dpadPressed = stateObject.pressed;
  109078. if (!controller._dpadPressed) {
  109079. controller._rotationLeftAsked = false;
  109080. controller._rotationRightAsked = false;
  109081. controller._teleportationBackRequestInitiated = false;
  109082. }
  109083. });
  109084. }
  109085. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  109086. if (_this.teleportationEnabled) {
  109087. _this._checkTeleportBackwards(stateObject, controller);
  109088. _this._checkTeleportWithRay(stateObject, controller);
  109089. }
  109090. _this._checkRotate(stateObject, controller);
  109091. });
  109092. }
  109093. };
  109094. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  109095. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  109096. this._teleportationTarget.isPickable = false;
  109097. var length = 512;
  109098. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  109099. dynamicTexture.hasAlpha = true;
  109100. var context = dynamicTexture.getContext();
  109101. var centerX = length / 2;
  109102. var centerY = length / 2;
  109103. var radius = 200;
  109104. context.beginPath();
  109105. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  109106. context.fillStyle = this._teleportationFillColor;
  109107. context.fill();
  109108. context.lineWidth = 10;
  109109. context.strokeStyle = this._teleportationBorderColor;
  109110. context.stroke();
  109111. context.closePath();
  109112. dynamicTexture.update();
  109113. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  109114. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  109115. this._teleportationTarget.material = teleportationCircleMaterial;
  109116. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  109117. torus.isPickable = false;
  109118. torus.parent = this._teleportationTarget;
  109119. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  109120. var keys = [];
  109121. keys.push({
  109122. frame: 0,
  109123. value: 0
  109124. });
  109125. keys.push({
  109126. frame: 30,
  109127. value: 0.4
  109128. });
  109129. keys.push({
  109130. frame: 60,
  109131. value: 0
  109132. });
  109133. animationInnerCircle.setKeys(keys);
  109134. var easingFunction = new BABYLON.SineEase();
  109135. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  109136. animationInnerCircle.setEasingFunction(easingFunction);
  109137. torus.animations = [];
  109138. torus.animations.push(animationInnerCircle);
  109139. this._scene.beginAnimation(torus, 0, 60, true);
  109140. this._hideTeleportationTarget();
  109141. };
  109142. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  109143. this._teleportActive = true;
  109144. if (this._teleportationInitialized) {
  109145. this._teleportationTarget.isVisible = true;
  109146. if (this._isDefaultTeleportationTarget) {
  109147. this._teleportationTarget.getChildren()[0].isVisible = true;
  109148. }
  109149. }
  109150. };
  109151. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  109152. this._teleportActive = false;
  109153. if (this._teleportationInitialized) {
  109154. this._teleportationTarget.isVisible = false;
  109155. if (this._isDefaultTeleportationTarget) {
  109156. this._teleportationTarget.getChildren()[0].isVisible = false;
  109157. }
  109158. }
  109159. };
  109160. VRExperienceHelper.prototype._rotateCamera = function (right) {
  109161. var _this = this;
  109162. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  109163. return;
  109164. }
  109165. if (right) {
  109166. this._rotationAngle++;
  109167. }
  109168. else {
  109169. this._rotationAngle--;
  109170. }
  109171. this.currentVRCamera.animations = [];
  109172. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  109173. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  109174. var animationRotationKeys = [];
  109175. animationRotationKeys.push({
  109176. frame: 0,
  109177. value: this.currentVRCamera.rotationQuaternion
  109178. });
  109179. animationRotationKeys.push({
  109180. frame: 6,
  109181. value: target
  109182. });
  109183. animationRotation.setKeys(animationRotationKeys);
  109184. animationRotation.setEasingFunction(this._circleEase);
  109185. this.currentVRCamera.animations.push(animationRotation);
  109186. this._postProcessMove.animations = [];
  109187. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  109188. var vignetteWeightKeys = [];
  109189. vignetteWeightKeys.push({
  109190. frame: 0,
  109191. value: 0
  109192. });
  109193. vignetteWeightKeys.push({
  109194. frame: 3,
  109195. value: 4
  109196. });
  109197. vignetteWeightKeys.push({
  109198. frame: 6,
  109199. value: 0
  109200. });
  109201. animationPP.setKeys(vignetteWeightKeys);
  109202. animationPP.setEasingFunction(this._circleEase);
  109203. this._postProcessMove.animations.push(animationPP);
  109204. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  109205. var vignetteStretchKeys = [];
  109206. vignetteStretchKeys.push({
  109207. frame: 0,
  109208. value: 0
  109209. });
  109210. vignetteStretchKeys.push({
  109211. frame: 3,
  109212. value: 10
  109213. });
  109214. vignetteStretchKeys.push({
  109215. frame: 6,
  109216. value: 0
  109217. });
  109218. animationPP2.setKeys(vignetteStretchKeys);
  109219. animationPP2.setEasingFunction(this._circleEase);
  109220. this._postProcessMove.animations.push(animationPP2);
  109221. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  109222. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  109223. this._postProcessMove.samples = 4;
  109224. this._webVRCamera.attachPostProcess(this._postProcessMove);
  109225. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  109226. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  109227. });
  109228. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  109229. };
  109230. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer, ray) {
  109231. if (hit.pickedPoint) {
  109232. if (gazer._teleportationRequestInitiated) {
  109233. this._displayTeleportationTarget();
  109234. this._haloCenter.copyFrom(hit.pickedPoint);
  109235. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  109236. }
  109237. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(true, false), ray);
  109238. if (pickNormal) {
  109239. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  109240. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  109241. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  109242. }
  109243. this._teleportationTarget.position.y += 0.1;
  109244. }
  109245. };
  109246. /**
  109247. * Teleports the users feet to the desired location
  109248. * @param location The location where the user's feet should be placed
  109249. */
  109250. VRExperienceHelper.prototype.teleportCamera = function (location) {
  109251. var _this = this;
  109252. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  109253. return;
  109254. }
  109255. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  109256. // offset of the headset from the anchor.
  109257. if (this.webVRCamera.leftCamera) {
  109258. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  109259. this._workingVector.subtractInPlace(this.webVRCamera.position);
  109260. location.subtractToRef(this._workingVector, this._workingVector);
  109261. }
  109262. else {
  109263. this._workingVector.copyFrom(location);
  109264. }
  109265. // Add height to account for user's height offset
  109266. if (this.isInVRMode) {
  109267. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  109268. }
  109269. else {
  109270. this._workingVector.y += this._defaultHeight;
  109271. }
  109272. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  109273. // Create animation from the camera's position to the new location
  109274. this.currentVRCamera.animations = [];
  109275. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  109276. var animationCameraTeleportationKeys = [{
  109277. frame: 0,
  109278. value: this.currentVRCamera.position
  109279. },
  109280. {
  109281. frame: 11,
  109282. value: this._workingVector
  109283. }
  109284. ];
  109285. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  109286. animationCameraTeleportation.setEasingFunction(this._circleEase);
  109287. this.currentVRCamera.animations.push(animationCameraTeleportation);
  109288. this._postProcessMove.animations = [];
  109289. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  109290. var vignetteWeightKeys = [];
  109291. vignetteWeightKeys.push({
  109292. frame: 0,
  109293. value: 0
  109294. });
  109295. vignetteWeightKeys.push({
  109296. frame: 5,
  109297. value: 8
  109298. });
  109299. vignetteWeightKeys.push({
  109300. frame: 11,
  109301. value: 0
  109302. });
  109303. animationPP.setKeys(vignetteWeightKeys);
  109304. this._postProcessMove.animations.push(animationPP);
  109305. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  109306. var vignetteStretchKeys = [];
  109307. vignetteStretchKeys.push({
  109308. frame: 0,
  109309. value: 0
  109310. });
  109311. vignetteStretchKeys.push({
  109312. frame: 5,
  109313. value: 10
  109314. });
  109315. vignetteStretchKeys.push({
  109316. frame: 11,
  109317. value: 0
  109318. });
  109319. animationPP2.setKeys(vignetteStretchKeys);
  109320. this._postProcessMove.animations.push(animationPP2);
  109321. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  109322. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  109323. this._webVRCamera.attachPostProcess(this._postProcessMove);
  109324. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  109325. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  109326. });
  109327. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  109328. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  109329. });
  109330. this._hideTeleportationTarget();
  109331. };
  109332. VRExperienceHelper.prototype._convertNormalToDirectionOfRay = function (normal, ray) {
  109333. if (normal) {
  109334. var angle = Math.acos(BABYLON.Vector3.Dot(normal, ray.direction));
  109335. if (angle < Math.PI / 2) {
  109336. normal.scaleInPlace(-1);
  109337. }
  109338. }
  109339. return normal;
  109340. };
  109341. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  109342. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  109343. return;
  109344. }
  109345. var ray = gazer._getForwardRay(this._rayLength);
  109346. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  109347. if (hit) {
  109348. // Populate the contrllers mesh that can be used for drag/drop
  109349. if (gazer._laserPointer) {
  109350. hit.originMesh = gazer._laserPointer.parent;
  109351. }
  109352. this._scene.simulatePointerMove(hit, { pointerId: gazer._id });
  109353. }
  109354. gazer._currentHit = hit;
  109355. // Moving the gazeTracker on the mesh face targetted
  109356. if (hit && hit.pickedPoint) {
  109357. if (this._displayGaze) {
  109358. var multiplier = 1;
  109359. gazer._gazeTracker.isVisible = true;
  109360. if (gazer._isActionableMesh) {
  109361. multiplier = 3;
  109362. }
  109363. if (this.updateGazeTrackerScale) {
  109364. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  109365. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  109366. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  109367. }
  109368. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(), ray);
  109369. // To avoid z-fighting
  109370. var deltaFighting = 0.002;
  109371. if (pickNormal) {
  109372. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  109373. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  109374. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  109375. }
  109376. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  109377. if (gazer._gazeTracker.position.x < 0) {
  109378. gazer._gazeTracker.position.x += deltaFighting;
  109379. }
  109380. else {
  109381. gazer._gazeTracker.position.x -= deltaFighting;
  109382. }
  109383. if (gazer._gazeTracker.position.y < 0) {
  109384. gazer._gazeTracker.position.y += deltaFighting;
  109385. }
  109386. else {
  109387. gazer._gazeTracker.position.y -= deltaFighting;
  109388. }
  109389. if (gazer._gazeTracker.position.z < 0) {
  109390. gazer._gazeTracker.position.z += deltaFighting;
  109391. }
  109392. else {
  109393. gazer._gazeTracker.position.z -= deltaFighting;
  109394. }
  109395. }
  109396. // Changing the size of the laser pointer based on the distance from the targetted point
  109397. gazer._updatePointerDistance(hit.distance);
  109398. }
  109399. else {
  109400. gazer._updatePointerDistance();
  109401. gazer._gazeTracker.isVisible = false;
  109402. }
  109403. if (hit && hit.pickedMesh) {
  109404. // The object selected is the floor, we're in a teleportation scenario
  109405. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  109406. // Moving the teleportation area to this targetted point
  109407. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  109408. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  109409. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  109410. }
  109411. gazer._currentMeshSelected = null;
  109412. if (gazer._teleportationRequestInitiated) {
  109413. this._moveTeleportationSelectorTo(hit, gazer, ray);
  109414. }
  109415. return;
  109416. }
  109417. // If not, we're in a selection scenario
  109418. //this._teleportationAllowed = false;
  109419. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  109420. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  109421. this.onNewMeshPicked.notifyObservers(hit);
  109422. gazer._currentMeshSelected = hit.pickedMesh;
  109423. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  109424. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  109425. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  109426. gazer._isActionableMesh = true;
  109427. }
  109428. else {
  109429. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  109430. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  109431. gazer._isActionableMesh = false;
  109432. }
  109433. try {
  109434. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  109435. }
  109436. catch (err) {
  109437. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  109438. }
  109439. }
  109440. else {
  109441. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  109442. gazer._currentMeshSelected = null;
  109443. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  109444. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  109445. }
  109446. }
  109447. }
  109448. else {
  109449. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  109450. gazer._currentMeshSelected = null;
  109451. //this._teleportationAllowed = false;
  109452. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  109453. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  109454. }
  109455. };
  109456. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  109457. if (mesh) {
  109458. this.onSelectedMeshUnselected.notifyObservers(mesh);
  109459. }
  109460. };
  109461. /**
  109462. * Sets the color of the laser ray from the vr controllers.
  109463. * @param color new color for the ray.
  109464. */
  109465. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  109466. if (this._leftController) {
  109467. this._leftController._setLaserPointerColor(color);
  109468. }
  109469. if (this._rightController) {
  109470. this._rightController._setLaserPointerColor(color);
  109471. }
  109472. };
  109473. /**
  109474. * Sets the color of the ray from the vr headsets gaze.
  109475. * @param color new color for the ray.
  109476. */
  109477. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  109478. if (!this.updateGazeTrackerColor) {
  109479. return;
  109480. }
  109481. if (!this._cameraGazer._gazeTracker.material) {
  109482. return;
  109483. }
  109484. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  109485. if (this._leftController) {
  109486. this._leftController._gazeTracker.material.emissiveColor = color;
  109487. }
  109488. if (this._rightController) {
  109489. this._rightController._gazeTracker.material.emissiveColor = color;
  109490. }
  109491. };
  109492. /**
  109493. * Exits VR and disposes of the vr experience helper
  109494. */
  109495. VRExperienceHelper.prototype.dispose = function () {
  109496. if (this.isInVRMode) {
  109497. this.exitVR();
  109498. }
  109499. if (this._postProcessMove) {
  109500. this._postProcessMove.dispose();
  109501. }
  109502. if (this._webVRCamera) {
  109503. this._webVRCamera.dispose();
  109504. }
  109505. if (this._vrDeviceOrientationCamera) {
  109506. this._vrDeviceOrientationCamera.dispose();
  109507. }
  109508. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  109509. document.body.removeChild(this._btnVR);
  109510. }
  109511. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  109512. this._deviceOrientationCamera.dispose();
  109513. }
  109514. if (this._cameraGazer) {
  109515. this._cameraGazer.dispose();
  109516. }
  109517. if (this._leftController) {
  109518. this._leftController.dispose();
  109519. }
  109520. if (this._rightController) {
  109521. this._rightController.dispose();
  109522. }
  109523. if (this._teleportationTarget) {
  109524. this._teleportationTarget.dispose();
  109525. }
  109526. this._floorMeshesCollection = [];
  109527. document.removeEventListener("keydown", this._onKeyDown);
  109528. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  109529. window.removeEventListener("resize", this._onResize);
  109530. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  109531. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  109532. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  109533. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  109534. document.onmsfullscreenchange = null;
  109535. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  109536. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  109537. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  109538. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  109539. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  109540. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  109541. this._scene.unregisterBeforeRender(this.beforeRender);
  109542. };
  109543. /**
  109544. * Gets the name of the VRExperienceHelper class
  109545. * @returns "VRExperienceHelper"
  109546. */
  109547. VRExperienceHelper.prototype.getClassName = function () {
  109548. return "VRExperienceHelper";
  109549. };
  109550. return VRExperienceHelper;
  109551. }());
  109552. BABYLON.VRExperienceHelper = VRExperienceHelper;
  109553. })(BABYLON || (BABYLON = {}));
  109554. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  109555. var BABYLON;
  109556. (function (BABYLON) {
  109557. /**
  109558. * WebXR Camera which holds the views for the xrSession
  109559. * @see https://doc.babylonjs.com/how_to/webxr
  109560. */
  109561. var WebXRCamera = /** @class */ (function (_super) {
  109562. __extends(WebXRCamera, _super);
  109563. /**
  109564. * Creates a new webXRCamera, this should only be set at the camera after it has been updated by the xrSessionManager
  109565. * @param name the name of the camera
  109566. * @param scene the scene to add the camera to
  109567. */
  109568. function WebXRCamera(name, scene) {
  109569. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  109570. // Initial camera configuration
  109571. _this.minZ = 0;
  109572. _this.rotationQuaternion = new BABYLON.Quaternion();
  109573. _this.cameraRigMode = BABYLON.Camera.RIG_MODE_CUSTOM;
  109574. _this.updateUpVectorFromRotation = true;
  109575. _this._updateNumberOfRigCameras(1);
  109576. return _this;
  109577. }
  109578. WebXRCamera.prototype._updateNumberOfRigCameras = function (viewCount) {
  109579. if (viewCount === void 0) { viewCount = 1; }
  109580. while (this.rigCameras.length < viewCount) {
  109581. var newCamera = new BABYLON.TargetCamera("view: " + this.rigCameras.length, BABYLON.Vector3.Zero(), this.getScene());
  109582. newCamera.minZ = 0;
  109583. newCamera.parent = this;
  109584. newCamera.rotationQuaternion = new BABYLON.Quaternion();
  109585. newCamera.updateUpVectorFromRotation = true;
  109586. this.rigCameras.push(newCamera);
  109587. }
  109588. while (this.rigCameras.length > viewCount) {
  109589. var removedCamera = this.rigCameras.pop();
  109590. if (removedCamera) {
  109591. removedCamera.dispose();
  109592. }
  109593. }
  109594. };
  109595. /** @hidden */
  109596. WebXRCamera.prototype._updateForDualEyeDebugging = function (pupilDistance) {
  109597. if (pupilDistance === void 0) { pupilDistance = 0.01; }
  109598. // Create initial camera rigs
  109599. this._updateNumberOfRigCameras(2);
  109600. this.rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  109601. this.rigCameras[0].position.x = -pupilDistance / 2;
  109602. this.rigCameras[0].outputRenderTarget = null;
  109603. this.rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  109604. this.rigCameras[1].position.x = pupilDistance / 2;
  109605. this.rigCameras[1].outputRenderTarget = null;
  109606. };
  109607. /**
  109608. * Updates the cameras position from the current pose information of the XR session
  109609. * @param xrSessionManager the session containing pose information
  109610. * @returns true if the camera has been updated, false if the session did not contain pose or frame data
  109611. */
  109612. WebXRCamera.prototype.updateFromXRSessionManager = function (xrSessionManager) {
  109613. var _this = this;
  109614. // Ensure all frame data is available
  109615. if (!xrSessionManager._currentXRFrame || !xrSessionManager._currentXRFrame.getDevicePose) {
  109616. return false;
  109617. }
  109618. var pose = xrSessionManager._currentXRFrame.getDevicePose(xrSessionManager._frameOfReference);
  109619. if (!pose || !pose.poseModelMatrix) {
  109620. return false;
  109621. }
  109622. // Update the parent cameras matrix
  109623. BABYLON.Matrix.FromFloat32ArrayToRefScaled(pose.poseModelMatrix, 0, 1, WebXRCamera._TmpMatrix);
  109624. if (!this._scene.useRightHandedSystem) {
  109625. WebXRCamera._TmpMatrix.toggleModelMatrixHandInPlace();
  109626. }
  109627. WebXRCamera._TmpMatrix.getTranslationToRef(this.position);
  109628. WebXRCamera._TmpMatrix.getRotationMatrixToRef(WebXRCamera._TmpMatrix);
  109629. BABYLON.Quaternion.FromRotationMatrixToRef(WebXRCamera._TmpMatrix, this.rotationQuaternion);
  109630. this.computeWorldMatrix();
  109631. // Update camera rigs
  109632. this._updateNumberOfRigCameras(xrSessionManager._currentXRFrame.views.length);
  109633. xrSessionManager._currentXRFrame.views.forEach(function (view, i) {
  109634. // Update view/projection matrix
  109635. BABYLON.Matrix.FromFloat32ArrayToRefScaled(pose.getViewMatrix(view), 0, 1, _this.rigCameras[i]._computedViewMatrix);
  109636. BABYLON.Matrix.FromFloat32ArrayToRefScaled(view.projectionMatrix, 0, 1, _this.rigCameras[i]._projectionMatrix);
  109637. if (!_this._scene.useRightHandedSystem) {
  109638. _this.rigCameras[i]._computedViewMatrix.toggleModelMatrixHandInPlace();
  109639. _this.rigCameras[i]._projectionMatrix.toggleProjectionMatrixHandInPlace();
  109640. }
  109641. // Update viewport
  109642. var viewport = xrSessionManager._xrSession.baseLayer.getViewport(view);
  109643. var width = xrSessionManager._xrSession.baseLayer.framebufferWidth;
  109644. var height = xrSessionManager._xrSession.baseLayer.framebufferHeight;
  109645. _this.rigCameras[i].viewport.width = viewport.width / width;
  109646. _this.rigCameras[i].viewport.height = viewport.height / height;
  109647. _this.rigCameras[i].viewport.x = viewport.x / width;
  109648. _this.rigCameras[i].viewport.y = viewport.y / height;
  109649. // Set cameras to render to the session's render target
  109650. _this.rigCameras[i].outputRenderTarget = xrSessionManager._sessionRenderTargetTexture;
  109651. });
  109652. return true;
  109653. };
  109654. WebXRCamera._TmpMatrix = new BABYLON.Matrix();
  109655. return WebXRCamera;
  109656. }(BABYLON.FreeCamera));
  109657. BABYLON.WebXRCamera = WebXRCamera;
  109658. })(BABYLON || (BABYLON = {}));
  109659. //# sourceMappingURL=babylon.webXRCamera.js.map
  109660. var BABYLON;
  109661. (function (BABYLON) {
  109662. /**
  109663. * Manages an XRSession
  109664. * @see https://doc.babylonjs.com/how_to/webxr
  109665. */
  109666. var WebXRSessionManager = /** @class */ (function () {
  109667. /**
  109668. * Constructs a WebXRSessionManager, this must be initialized within a user action before usage
  109669. * @param scene The scene which the session should be created for
  109670. */
  109671. function WebXRSessionManager(scene) {
  109672. this.scene = scene;
  109673. /**
  109674. * Fires every time a new xrFrame arrives which can be used to update the camera
  109675. */
  109676. this.onXRFrameObservable = new BABYLON.Observable();
  109677. /**
  109678. * Fires when the xr session is ended either by the device or manually done
  109679. */
  109680. this.onXRSessionEnded = new BABYLON.Observable();
  109681. /** @hidden */
  109682. this._sessionRenderTargetTexture = null;
  109683. this._tmpMatrix = new BABYLON.Matrix();
  109684. }
  109685. /**
  109686. * Initializes the manager
  109687. * After initialization enterXR can be called to start an XR session
  109688. * @returns Promise which resolves after it is initialized
  109689. */
  109690. WebXRSessionManager.prototype.initializeAsync = function () {
  109691. var _this = this;
  109692. BABYLON.Tools.Warn("The WebXR APIs are still under development and are subject to change in the future.");
  109693. // Check if the browser supports webXR
  109694. this._xrNavigator = navigator;
  109695. if (!this._xrNavigator.xr) {
  109696. return Promise.reject("webXR not supported by this browser");
  109697. }
  109698. // Request the webXR device
  109699. return this._xrNavigator.xr.requestDevice().then(function (device) {
  109700. _this._xrDevice = device;
  109701. return _this.scene.getEngine()._gl.setCompatibleXRDevice(_this._xrDevice);
  109702. });
  109703. };
  109704. /**
  109705. * Enters XR with the desired XR session options, this must be done with a user action (eg. button click event)
  109706. * @param sessionCreationOptions xr options to create the session with
  109707. * @param frameOfReferenceType option to configure how the xr pose is expressed
  109708. * @returns Promise which resolves after it enters XR
  109709. */
  109710. WebXRSessionManager.prototype.enterXRAsync = function (sessionCreationOptions, frameOfReferenceType) {
  109711. var _this = this;
  109712. // initialize session
  109713. return this._xrDevice.requestSession(sessionCreationOptions).then(function (session) {
  109714. _this._xrSession = session;
  109715. // handle when the session is ended (By calling session.end or device ends its own session eg. pressing home button on phone)
  109716. _this._xrSession.addEventListener("end", function () {
  109717. // Remove render target texture and notify frame obervers
  109718. _this._sessionRenderTargetTexture = null;
  109719. // Restore frame buffer to avoid clear on xr framebuffer after session end
  109720. _this.scene.getEngine().restoreDefaultFramebuffer();
  109721. // Need to restart render loop as after the session is ended the last request for new frame will never call callback
  109722. _this.scene.getEngine().customAnimationFrameRequester = null;
  109723. _this.onXRSessionEnded.notifyObservers(null);
  109724. _this.scene.getEngine()._renderLoop();
  109725. }, { once: true });
  109726. _this._xrSession.baseLayer = new XRWebGLLayer(_this._xrSession, _this.scene.getEngine()._gl);
  109727. return _this._xrSession.requestFrameOfReference(frameOfReferenceType);
  109728. }).then(function (frameOfRef) {
  109729. _this._frameOfReference = frameOfRef;
  109730. // Tell the engine's render loop to be driven by the xr session's refresh rate and provide xr pose information
  109731. _this.scene.getEngine().customAnimationFrameRequester = {
  109732. requestAnimationFrame: _this._xrSession.requestAnimationFrame.bind(_this._xrSession),
  109733. renderFunction: function (timestamp, xrFrame) {
  109734. // Store the XR frame in the manager to be consumed by the XR camera to update pose
  109735. _this._currentXRFrame = xrFrame;
  109736. _this.onXRFrameObservable.notifyObservers(null);
  109737. _this.scene.getEngine()._renderLoop();
  109738. }
  109739. };
  109740. // Create render target texture from xr's webgl render target
  109741. _this._sessionRenderTargetTexture = WebXRSessionManager._CreateRenderTargetTextureFromSession(_this._xrSession, _this.scene);
  109742. // Stop window's animation frame and trigger sessions animation frame
  109743. window.cancelAnimationFrame(_this.scene.getEngine()._frameHandler);
  109744. _this.scene.getEngine()._renderLoop();
  109745. });
  109746. };
  109747. /**
  109748. * Stops the xrSession and restores the renderloop
  109749. * @returns Promise which resolves after it exits XR
  109750. */
  109751. WebXRSessionManager.prototype.exitXRAsync = function () {
  109752. return this._xrSession.end();
  109753. };
  109754. /**
  109755. * Fires a ray and returns the closest hit in the xr sessions enviornment, useful to place objects in AR
  109756. * @param ray ray to cast into the environment
  109757. * @returns Promise which resolves with a collision point in the environment if it exists
  109758. */
  109759. WebXRSessionManager.prototype.environmentPointHitTestAsync = function (ray) {
  109760. var _this = this;
  109761. return new Promise(function (res, rej) {
  109762. // Compute left handed inputs to request hit test
  109763. var origin = new Float32Array([ray.origin.x, ray.origin.y, ray.origin.z]);
  109764. var direction = new Float32Array([ray.direction.x, ray.direction.y, ray.direction.z]);
  109765. if (!_this.scene.useRightHandedSystem) {
  109766. origin[2] *= -1;
  109767. direction[2] *= -1;
  109768. }
  109769. // Fire hittest
  109770. _this._xrSession.requestHitTest(origin, direction, _this._frameOfReference)
  109771. .then(function (hits) {
  109772. if (hits.length > 0) {
  109773. BABYLON.Matrix.FromFloat32ArrayToRefScaled(hits[0].hitMatrix, 0, 1.0, _this._tmpMatrix);
  109774. var hitPoint = _this._tmpMatrix.getTranslation();
  109775. if (!_this.scene.useRightHandedSystem) {
  109776. hitPoint.z *= -1;
  109777. }
  109778. res(hitPoint);
  109779. }
  109780. else {
  109781. res(null);
  109782. }
  109783. }).catch(function (e) {
  109784. res(null);
  109785. });
  109786. });
  109787. };
  109788. /**
  109789. * Checks if a session would be supported for the creation options specified
  109790. * @param options creation options to check if they are supported
  109791. * @returns true if supported
  109792. */
  109793. WebXRSessionManager.prototype.supportsSessionAsync = function (options) {
  109794. return this._xrDevice.supportsSession(options).then(function () {
  109795. return true;
  109796. }).catch(function (e) {
  109797. return false;
  109798. });
  109799. };
  109800. /**
  109801. * @hidden
  109802. * Converts the render layer of xrSession to a render target
  109803. * @param session session to create render target for
  109804. * @param scene scene the new render target should be created for
  109805. */
  109806. WebXRSessionManager._CreateRenderTargetTextureFromSession = function (session, scene) {
  109807. // Create internal texture
  109808. var internalTexture = new BABYLON.InternalTexture(scene.getEngine(), BABYLON.InternalTexture.DATASOURCE_UNKNOWN, true);
  109809. internalTexture.width = session.baseLayer.framebufferWidth;
  109810. internalTexture.height = session.baseLayer.framebufferHeight;
  109811. internalTexture._framebuffer = session.baseLayer.framebuffer;
  109812. // Create render target texture from the internal texture
  109813. var renderTargetTexture = new BABYLON.RenderTargetTexture("XR renderTargetTexture", { width: internalTexture.width, height: internalTexture.height }, scene, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, true);
  109814. renderTargetTexture._texture = internalTexture;
  109815. return renderTargetTexture;
  109816. };
  109817. /**
  109818. * Disposes of the session manager
  109819. */
  109820. WebXRSessionManager.prototype.dispose = function () {
  109821. this.onXRFrameObservable.clear();
  109822. this.onXRSessionEnded.clear();
  109823. };
  109824. return WebXRSessionManager;
  109825. }());
  109826. BABYLON.WebXRSessionManager = WebXRSessionManager;
  109827. })(BABYLON || (BABYLON = {}));
  109828. //# sourceMappingURL=babylon.webXRSessionManager.js.map
  109829. var BABYLON;
  109830. (function (BABYLON) {
  109831. /**
  109832. * States of the webXR experience
  109833. */
  109834. var WebXRState;
  109835. (function (WebXRState) {
  109836. /**
  109837. * Transitioning to being in XR mode
  109838. */
  109839. WebXRState[WebXRState["ENTERING_XR"] = 0] = "ENTERING_XR";
  109840. /**
  109841. * Transitioning to non XR mode
  109842. */
  109843. WebXRState[WebXRState["EXITING_XR"] = 1] = "EXITING_XR";
  109844. /**
  109845. * In XR mode and presenting
  109846. */
  109847. WebXRState[WebXRState["IN_XR"] = 2] = "IN_XR";
  109848. /**
  109849. * Not entered XR mode
  109850. */
  109851. WebXRState[WebXRState["NOT_IN_XR"] = 3] = "NOT_IN_XR";
  109852. })(WebXRState = BABYLON.WebXRState || (BABYLON.WebXRState = {}));
  109853. /**
  109854. * Helper class used to enable XR
  109855. * @see https://doc.babylonjs.com/how_to/webxr
  109856. */
  109857. var WebXRExperienceHelper = /** @class */ (function () {
  109858. /**
  109859. * Creates a WebXRExperienceHelper
  109860. * @param scene The scene the helper should be created in
  109861. */
  109862. function WebXRExperienceHelper(scene) {
  109863. this.scene = scene;
  109864. /**
  109865. * The current state of the XR experience (eg. transitioning, in XR or not in XR)
  109866. */
  109867. this.state = WebXRState.NOT_IN_XR;
  109868. /**
  109869. * Fires when the state of the experience helper has changed
  109870. */
  109871. this.onStateChangedObservable = new BABYLON.Observable();
  109872. this._nonVRCamera = null;
  109873. this._originalSceneAutoClear = true;
  109874. this._supported = false;
  109875. this.camera = new BABYLON.WebXRCamera("", scene);
  109876. this._sessionManager = new BABYLON.WebXRSessionManager(scene);
  109877. this.container = new BABYLON.AbstractMesh("", scene);
  109878. this.camera.parent = this.container;
  109879. }
  109880. WebXRExperienceHelper.prototype._setState = function (val) {
  109881. this.state = val;
  109882. this.onStateChangedObservable.notifyObservers(this.state);
  109883. };
  109884. /**
  109885. * Creates the experience helper
  109886. * @param scene the scene to attach the experience helper to
  109887. * @returns a promise for the experience helper
  109888. */
  109889. WebXRExperienceHelper.CreateAsync = function (scene) {
  109890. var helper = new WebXRExperienceHelper(scene);
  109891. return helper._sessionManager.initializeAsync().then(function () {
  109892. helper._supported = true;
  109893. return helper;
  109894. }).catch(function () {
  109895. return helper;
  109896. });
  109897. };
  109898. /**
  109899. * Exits XR mode and returns the scene to its original state
  109900. * @returns promise that resolves after xr mode has exited
  109901. */
  109902. WebXRExperienceHelper.prototype.exitXRAsync = function () {
  109903. this._setState(WebXRState.EXITING_XR);
  109904. return this._sessionManager.exitXRAsync();
  109905. };
  109906. /**
  109907. * Enters XR mode (This must be done within a user interaction in most browsers eg. button click)
  109908. * @param sessionCreationOptions options for the XR session
  109909. * @param frameOfReference frame of reference of the XR session
  109910. * @returns promise that resolves after xr mode has entered
  109911. */
  109912. WebXRExperienceHelper.prototype.enterXRAsync = function (sessionCreationOptions, frameOfReference) {
  109913. var _this = this;
  109914. if (!this._supported) {
  109915. throw "XR session not supported by this browser";
  109916. }
  109917. this._setState(WebXRState.ENTERING_XR);
  109918. return this._sessionManager.enterXRAsync(sessionCreationOptions, frameOfReference).then(function () {
  109919. // Cache pre xr scene settings
  109920. _this._originalSceneAutoClear = _this.scene.autoClear;
  109921. _this._nonVRCamera = _this.scene.activeCamera;
  109922. // Overwrite current scene settings
  109923. _this.scene.autoClear = false;
  109924. _this.scene.activeCamera = _this.camera;
  109925. _this._sessionManager.onXRFrameObservable.add(function () {
  109926. _this.camera.updateFromXRSessionManager(_this._sessionManager);
  109927. });
  109928. _this._sessionManager.onXRSessionEnded.addOnce(function () {
  109929. // Reset camera rigs output render target to ensure sessions render target is not drawn after it ends
  109930. _this.camera.rigCameras.forEach(function (c) {
  109931. c.outputRenderTarget = null;
  109932. });
  109933. // Restore scene settings
  109934. _this.scene.autoClear = _this._originalSceneAutoClear;
  109935. _this.scene.activeCamera = _this._nonVRCamera;
  109936. _this._sessionManager.onXRFrameObservable.clear();
  109937. _this._setState(WebXRState.NOT_IN_XR);
  109938. });
  109939. _this._setState(WebXRState.IN_XR);
  109940. });
  109941. };
  109942. /**
  109943. * Fires a ray and returns the closest hit in the xr sessions enviornment, useful to place objects in AR
  109944. * @param ray ray to cast into the environment
  109945. * @returns Promise which resolves with a collision point in the environment if it exists
  109946. */
  109947. WebXRExperienceHelper.prototype.environmentPointHitTestAsync = function (ray) {
  109948. return this._sessionManager.environmentPointHitTestAsync(ray);
  109949. };
  109950. /**
  109951. * Updates the global position of the camera by moving the camera's container
  109952. * This should be used instead of modifying the camera's position as it will be overwritten by an xrSessions's update frame
  109953. * @param position The desired global position of the camera
  109954. */
  109955. WebXRExperienceHelper.prototype.setPositionOfCameraUsingContainer = function (position) {
  109956. this.camera.globalPosition.subtractToRef(position, WebXRExperienceHelper._TmpVector);
  109957. this.container.position.subtractInPlace(WebXRExperienceHelper._TmpVector);
  109958. };
  109959. /**
  109960. * Rotates the xr camera by rotating the camera's container around the camera's position
  109961. * This should be used instead of modifying the camera's rotation as it will be overwritten by an xrSessions's update frame
  109962. * @param rotation the desired quaternion rotation to apply to the camera
  109963. */
  109964. WebXRExperienceHelper.prototype.rotateCameraByQuaternionUsingContainer = function (rotation) {
  109965. if (!this.container.rotationQuaternion) {
  109966. this.container.rotationQuaternion = BABYLON.Quaternion.FromEulerVector(this.container.rotation);
  109967. }
  109968. this.container.rotationQuaternion.multiplyInPlace(rotation);
  109969. this.container.position.rotateByQuaternionAroundPointToRef(rotation, this.camera.globalPosition, this.container.position);
  109970. };
  109971. /**
  109972. * Checks if the creation options are supported by the xr session
  109973. * @param options creation options
  109974. * @returns true if supported
  109975. */
  109976. WebXRExperienceHelper.prototype.supportsSessionAsync = function (options) {
  109977. if (!this._supported) {
  109978. return Promise.resolve(false);
  109979. }
  109980. return this._sessionManager.supportsSessionAsync(options);
  109981. };
  109982. /**
  109983. * Disposes of the experience helper
  109984. */
  109985. WebXRExperienceHelper.prototype.dispose = function () {
  109986. this.camera.dispose();
  109987. this.container.dispose();
  109988. this.onStateChangedObservable.clear();
  109989. this._sessionManager.dispose();
  109990. };
  109991. WebXRExperienceHelper._TmpVector = new BABYLON.Vector3();
  109992. return WebXRExperienceHelper;
  109993. }());
  109994. BABYLON.WebXRExperienceHelper = WebXRExperienceHelper;
  109995. })(BABYLON || (BABYLON = {}));
  109996. //# sourceMappingURL=babylon.webXRExperienceHelper.js.map
  109997. var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
  109998. return new (P || (P = Promise))(function (resolve, reject) {
  109999. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  110000. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  110001. function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
  110002. step((generator = generator.apply(thisArg, _arguments || [])).next());
  110003. });
  110004. };
  110005. var __generator = (this && this.__generator) || function (thisArg, body) {
  110006. var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
  110007. return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
  110008. function verb(n) { return function (v) { return step([n, v]); }; }
  110009. function step(op) {
  110010. if (f) throw new TypeError("Generator is already executing.");
  110011. while (_) try {
  110012. if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
  110013. if (y = 0, t) op = [op[0] & 2, t.value];
  110014. switch (op[0]) {
  110015. case 0: case 1: t = op; break;
  110016. case 4: _.label++; return { value: op[1], done: false };
  110017. case 5: _.label++; y = op[1]; op = [0]; continue;
  110018. case 7: op = _.ops.pop(); _.trys.pop(); continue;
  110019. default:
  110020. if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
  110021. if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
  110022. if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
  110023. if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
  110024. if (t[2]) _.ops.pop();
  110025. _.trys.pop(); continue;
  110026. }
  110027. op = body.call(thisArg, _);
  110028. } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
  110029. if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
  110030. }
  110031. };
  110032. var BABYLON;
  110033. (function (BABYLON) {
  110034. /**
  110035. * Button which can be used to enter a different mode of XR
  110036. */
  110037. var WebXREnterExitUIButton = /** @class */ (function () {
  110038. /**
  110039. * Creates a WebXREnterExitUIButton
  110040. * @param element button element
  110041. * @param initializationOptions XR initialization options for the button
  110042. */
  110043. function WebXREnterExitUIButton(
  110044. /** button element */
  110045. element,
  110046. /** XR initialization options for the button */
  110047. initializationOptions) {
  110048. this.element = element;
  110049. this.initializationOptions = initializationOptions;
  110050. }
  110051. /**
  110052. * Overwritable function which can be used to update the button's visuals when the state changes
  110053. * @param activeButton the current active button in the UI
  110054. */
  110055. WebXREnterExitUIButton.prototype.update = function (activeButton) {
  110056. };
  110057. return WebXREnterExitUIButton;
  110058. }());
  110059. BABYLON.WebXREnterExitUIButton = WebXREnterExitUIButton;
  110060. /**
  110061. * Options to create the webXR UI
  110062. */
  110063. var WebXREnterExitUIOptions = /** @class */ (function () {
  110064. function WebXREnterExitUIOptions() {
  110065. }
  110066. return WebXREnterExitUIOptions;
  110067. }());
  110068. BABYLON.WebXREnterExitUIOptions = WebXREnterExitUIOptions;
  110069. /**
  110070. * UI to allow the user to enter/exit XR mode
  110071. */
  110072. var WebXREnterExitUI = /** @class */ (function () {
  110073. function WebXREnterExitUI(scene, options) {
  110074. var _this = this;
  110075. this.scene = scene;
  110076. this._buttons = [];
  110077. this._activeButton = null;
  110078. /**
  110079. * Fired every time the active button is changed.
  110080. *
  110081. * When xr is entered via a button that launches xr that button will be the callback parameter
  110082. *
  110083. * When exiting xr the callback parameter will be null)
  110084. */
  110085. this.activeButtonChangedObservable = new BABYLON.Observable();
  110086. this._overlay = document.createElement("div");
  110087. this._overlay.style.cssText = "z-index:11;position: absolute; right: 20px;bottom: 50px;";
  110088. if (options.customButtons) {
  110089. this._buttons = options.customButtons;
  110090. }
  110091. else {
  110092. var hmdBtn = document.createElement("button");
  110093. hmdBtn.style.cssText = "color: #868686; border-color: #868686; border-style: solid; margin-left: 10px; height: 50px; width: 80px; background-color: rgba(51,51,51,0.7); background-repeat:no-repeat; background-position: center; outline: none;";
  110094. hmdBtn.innerText = "HMD";
  110095. this._buttons.push(new WebXREnterExitUIButton(hmdBtn, { immersive: true, outputContext: options.outputCanvasContext }));
  110096. this._buttons[this._buttons.length - 1].update = function (activeButton) {
  110097. this.element.style.display = (activeButton === null || activeButton === this) ? "" : "none";
  110098. this.element.innerText = activeButton === this ? "EXIT" : "HMD";
  110099. };
  110100. var windowBtn = document.createElement("button");
  110101. windowBtn.style.cssText = hmdBtn.style.cssText;
  110102. windowBtn.innerText = "Window";
  110103. this._buttons.push(new WebXREnterExitUIButton(windowBtn, { immersive: false, environmentIntegration: true, outputContext: options.outputCanvasContext }));
  110104. this._buttons[this._buttons.length - 1].update = function (activeButton) {
  110105. this.element.style.display = (activeButton === null || activeButton === this) ? "" : "none";
  110106. this.element.innerText = activeButton === this ? "EXIT" : "Window";
  110107. };
  110108. this._updateButtons(null);
  110109. }
  110110. var renderCanvas = scene.getEngine().getRenderingCanvas();
  110111. if (renderCanvas && renderCanvas.parentNode) {
  110112. renderCanvas.parentNode.appendChild(this._overlay);
  110113. scene.onDisposeObservable.addOnce(function () {
  110114. _this.dispose();
  110115. });
  110116. }
  110117. }
  110118. /**
  110119. * Creates UI to allow the user to enter/exit XR mode
  110120. * @param scene the scene to add the ui to
  110121. * @param helper the xr experience helper to enter/exit xr with
  110122. * @param options options to configure the UI
  110123. * @returns the created ui
  110124. */
  110125. WebXREnterExitUI.CreateAsync = function (scene, helper, options) {
  110126. var _this = this;
  110127. var ui = new WebXREnterExitUI(scene, options);
  110128. var supportedPromises = ui._buttons.map(function (btn) {
  110129. return helper.supportsSessionAsync(btn.initializationOptions);
  110130. });
  110131. helper.onStateChangedObservable.add(function (state) {
  110132. if (state == BABYLON.WebXRState.NOT_IN_XR) {
  110133. ui._updateButtons(null);
  110134. }
  110135. });
  110136. return Promise.all(supportedPromises).then(function (results) {
  110137. results.forEach(function (supported, i) {
  110138. if (supported) {
  110139. ui._overlay.appendChild(ui._buttons[i].element);
  110140. ui._buttons[i].element.onclick = function () { return __awaiter(_this, void 0, void 0, function () {
  110141. return __generator(this, function (_a) {
  110142. switch (_a.label) {
  110143. case 0:
  110144. if (!(helper.state == BABYLON.WebXRState.IN_XR)) return [3 /*break*/, 2];
  110145. ui._updateButtons(null);
  110146. return [4 /*yield*/, helper.exitXRAsync()];
  110147. case 1:
  110148. _a.sent();
  110149. return [2 /*return*/];
  110150. case 2:
  110151. if (!(helper.state == BABYLON.WebXRState.NOT_IN_XR)) return [3 /*break*/, 4];
  110152. ui._updateButtons(ui._buttons[i]);
  110153. return [4 /*yield*/, helper.enterXRAsync(ui._buttons[i].initializationOptions, "eye-level")];
  110154. case 3:
  110155. _a.sent();
  110156. _a.label = 4;
  110157. case 4: return [2 /*return*/];
  110158. }
  110159. });
  110160. }); };
  110161. }
  110162. });
  110163. return ui;
  110164. });
  110165. };
  110166. WebXREnterExitUI.prototype._updateButtons = function (activeButton) {
  110167. var _this = this;
  110168. this._activeButton = activeButton;
  110169. this._buttons.forEach(function (b) {
  110170. b.update(_this._activeButton);
  110171. });
  110172. this.activeButtonChangedObservable.notifyObservers(this._activeButton);
  110173. };
  110174. /**
  110175. * Disposes of the object
  110176. */
  110177. WebXREnterExitUI.prototype.dispose = function () {
  110178. var renderCanvas = this.scene.getEngine().getRenderingCanvas();
  110179. if (renderCanvas && renderCanvas.parentNode && renderCanvas.parentNode.contains(this._overlay)) {
  110180. renderCanvas.parentNode.removeChild(this._overlay);
  110181. }
  110182. this.activeButtonChangedObservable.clear();
  110183. };
  110184. return WebXREnterExitUI;
  110185. }());
  110186. BABYLON.WebXREnterExitUI = WebXREnterExitUI;
  110187. })(BABYLON || (BABYLON = {}));
  110188. //# sourceMappingURL=babylon.webXREnterExitUI.js.map
  110189. var BABYLON;
  110190. (function (BABYLON) {
  110191. /**
  110192. * Creates a canvas that is added/removed from the webpage when entering/exiting XR
  110193. */
  110194. var WebXRManagedOutputCanvas = /** @class */ (function () {
  110195. /**
  110196. * Initializes the canvas to be added/removed upon entering/exiting xr
  110197. * @param helper the xr experience helper used to trigger adding/removing of the canvas
  110198. * @param canvas The canvas to be added/removed (If not specified a full screen canvas will be created)
  110199. */
  110200. function WebXRManagedOutputCanvas(helper, canvas) {
  110201. var _this = this;
  110202. this._canvas = null;
  110203. /**
  110204. * xrpresent context of the canvas which can be used to display/mirror xr content
  110205. */
  110206. this.canvasContext = null;
  110207. if (!canvas) {
  110208. canvas = document.createElement('canvas');
  110209. canvas.style.cssText = "position:absolute; bottom:0px;right:0px;z-index:10;width:100%;height:100%;background-color: #000000;";
  110210. }
  110211. this._setManagedOutputCanvas(canvas);
  110212. helper.onStateChangedObservable.add(function (stateInfo) {
  110213. if (stateInfo == BABYLON.WebXRState.ENTERING_XR) {
  110214. // The canvas is added to the screen before entering XR because currently the xr session must be initialized while the canvas is added render properly
  110215. _this._addCanvas();
  110216. }
  110217. else if (helper.state == BABYLON.WebXRState.NOT_IN_XR) {
  110218. _this._removeCanvas();
  110219. }
  110220. });
  110221. }
  110222. /**
  110223. * Disposes of the object
  110224. */
  110225. WebXRManagedOutputCanvas.prototype.dispose = function () {
  110226. this._removeCanvas();
  110227. this._setManagedOutputCanvas(null);
  110228. };
  110229. WebXRManagedOutputCanvas.prototype._setManagedOutputCanvas = function (canvas) {
  110230. this._removeCanvas();
  110231. if (!canvas) {
  110232. this._canvas = null;
  110233. this.canvasContext = null;
  110234. }
  110235. else {
  110236. this._canvas = canvas;
  110237. this.canvasContext = this._canvas.getContext('xrpresent');
  110238. }
  110239. };
  110240. WebXRManagedOutputCanvas.prototype._addCanvas = function () {
  110241. if (this._canvas) {
  110242. document.body.appendChild(this._canvas);
  110243. }
  110244. };
  110245. WebXRManagedOutputCanvas.prototype._removeCanvas = function () {
  110246. if (this._canvas && document.body.contains(this._canvas)) {
  110247. document.body.removeChild(this._canvas);
  110248. }
  110249. };
  110250. return WebXRManagedOutputCanvas;
  110251. }());
  110252. BABYLON.WebXRManagedOutputCanvas = WebXRManagedOutputCanvas;
  110253. })(BABYLON || (BABYLON = {}));
  110254. //# sourceMappingURL=babylon.webXRManagedOutputCanvas.js.map
  110255. var BABYLON;
  110256. (function (BABYLON) {
  110257. /**
  110258. * Represents an XR input
  110259. */
  110260. var WebXRController = /** @class */ (function () {
  110261. /**
  110262. * Creates the controller
  110263. * @see https://doc.babylonjs.com/how_to/webxr
  110264. * @param scene the scene which the controller should be associated to
  110265. */
  110266. function WebXRController(scene) {
  110267. this.pointer = new BABYLON.AbstractMesh("controllerPointer", scene);
  110268. }
  110269. /**
  110270. * Disposes of the object
  110271. */
  110272. WebXRController.prototype.dispose = function () {
  110273. if (this.grip) {
  110274. this.grip.dispose();
  110275. }
  110276. this.pointer.dispose();
  110277. };
  110278. return WebXRController;
  110279. }());
  110280. BABYLON.WebXRController = WebXRController;
  110281. /**
  110282. * XR input used to track XR inputs such as controllers/rays
  110283. */
  110284. var WebXRInput = /** @class */ (function () {
  110285. /**
  110286. * Initializes the WebXRInput
  110287. * @param helper experience helper which the input should be created for
  110288. */
  110289. function WebXRInput(helper) {
  110290. var _this = this;
  110291. this.helper = helper;
  110292. /**
  110293. * XR controllers being tracked
  110294. */
  110295. this.controllers = [];
  110296. this._tmpMatrix = new BABYLON.Matrix();
  110297. this._frameObserver = helper._sessionManager.onXRFrameObservable.add(function () {
  110298. if (!helper._sessionManager._currentXRFrame || !helper._sessionManager._currentXRFrame.getDevicePose) {
  110299. return;
  110300. }
  110301. var xrFrame = helper._sessionManager._currentXRFrame;
  110302. var inputSources = helper._sessionManager._xrSession.getInputSources();
  110303. inputSources.forEach(function (input, i) {
  110304. var inputPose = xrFrame.getInputPose(input, helper._sessionManager._frameOfReference);
  110305. if (inputPose) {
  110306. if (_this.controllers.length <= i) {
  110307. _this.controllers.push(new WebXRController(helper.container.getScene()));
  110308. }
  110309. var controller = _this.controllers[i];
  110310. // Manage the grip if it exists
  110311. if (inputPose.gripMatrix) {
  110312. if (!controller.grip) {
  110313. controller.grip = new BABYLON.AbstractMesh("controllerGrip", helper.container.getScene());
  110314. }
  110315. BABYLON.Matrix.FromFloat32ArrayToRefScaled(inputPose.gripMatrix, 0, 1, _this._tmpMatrix);
  110316. if (!controller.grip.getScene().useRightHandedSystem) {
  110317. _this._tmpMatrix.toggleModelMatrixHandInPlace();
  110318. }
  110319. if (!controller.grip.rotationQuaternion) {
  110320. controller.grip.rotationQuaternion = new BABYLON.Quaternion();
  110321. }
  110322. _this._tmpMatrix.decompose(controller.grip.scaling, controller.grip.rotationQuaternion, controller.grip.position);
  110323. }
  110324. // Manager pointer of controller
  110325. BABYLON.Matrix.FromFloat32ArrayToRefScaled(inputPose.targetRay.transformMatrix, 0, 1, _this._tmpMatrix);
  110326. if (!controller.pointer.getScene().useRightHandedSystem) {
  110327. _this._tmpMatrix.toggleModelMatrixHandInPlace();
  110328. }
  110329. if (!controller.pointer.rotationQuaternion) {
  110330. controller.pointer.rotationQuaternion = new BABYLON.Quaternion();
  110331. }
  110332. _this._tmpMatrix.decompose(controller.pointer.scaling, controller.pointer.rotationQuaternion, controller.pointer.position);
  110333. }
  110334. });
  110335. });
  110336. }
  110337. /**
  110338. * Disposes of the object
  110339. */
  110340. WebXRInput.prototype.dispose = function () {
  110341. this.controllers.forEach(function (c) {
  110342. c.dispose();
  110343. });
  110344. this.helper._sessionManager.onXRFrameObservable.remove(this._frameObserver);
  110345. };
  110346. return WebXRInput;
  110347. }());
  110348. BABYLON.WebXRInput = WebXRInput;
  110349. })(BABYLON || (BABYLON = {}));
  110350. //# sourceMappingURL=babylon.webXRInput.js.map
  110351. // Mainly based on these 2 articles :
  110352. // 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
  110353. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  110354. var BABYLON;
  110355. (function (BABYLON) {
  110356. /**
  110357. * Defines the potential axis of a Joystick
  110358. */
  110359. var JoystickAxis;
  110360. (function (JoystickAxis) {
  110361. /** X axis */
  110362. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  110363. /** Y axis */
  110364. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  110365. /** Z axis */
  110366. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  110367. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  110368. /**
  110369. * Class used to define virtual joystick (used in touch mode)
  110370. */
  110371. var VirtualJoystick = /** @class */ (function () {
  110372. /**
  110373. * Creates a new virtual joystick
  110374. * @param leftJoystick defines that the joystick is for left hand (false by default)
  110375. */
  110376. function VirtualJoystick(leftJoystick) {
  110377. var _this = this;
  110378. if (leftJoystick) {
  110379. this._leftJoystick = true;
  110380. }
  110381. else {
  110382. this._leftJoystick = false;
  110383. }
  110384. VirtualJoystick._globalJoystickIndex++;
  110385. // By default left & right arrow keys are moving the X
  110386. // and up & down keys are moving the Y
  110387. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  110388. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  110389. this.reverseLeftRight = false;
  110390. this.reverseUpDown = false;
  110391. // collections of pointers
  110392. this._touches = new BABYLON.StringDictionary();
  110393. this.deltaPosition = BABYLON.Vector3.Zero();
  110394. this._joystickSensibility = 25;
  110395. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  110396. this._onResize = function (evt) {
  110397. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  110398. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  110399. if (VirtualJoystick.Canvas) {
  110400. VirtualJoystick.Canvas.width = VirtualJoystick.vjCanvasWidth;
  110401. VirtualJoystick.Canvas.height = VirtualJoystick.vjCanvasHeight;
  110402. }
  110403. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  110404. };
  110405. // injecting a canvas element on top of the canvas 3D game
  110406. if (!VirtualJoystick.Canvas) {
  110407. window.addEventListener("resize", this._onResize, false);
  110408. VirtualJoystick.Canvas = document.createElement("canvas");
  110409. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  110410. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  110411. VirtualJoystick.Canvas.width = window.innerWidth;
  110412. VirtualJoystick.Canvas.height = window.innerHeight;
  110413. VirtualJoystick.Canvas.style.width = "100%";
  110414. VirtualJoystick.Canvas.style.height = "100%";
  110415. VirtualJoystick.Canvas.style.position = "absolute";
  110416. VirtualJoystick.Canvas.style.backgroundColor = "transparent";
  110417. VirtualJoystick.Canvas.style.top = "0px";
  110418. VirtualJoystick.Canvas.style.left = "0px";
  110419. VirtualJoystick.Canvas.style.zIndex = "5";
  110420. VirtualJoystick.Canvas.style.msTouchAction = "none";
  110421. // Support for jQuery PEP polyfill
  110422. VirtualJoystick.Canvas.setAttribute("touch-action", "none");
  110423. var context = VirtualJoystick.Canvas.getContext('2d');
  110424. if (!context) {
  110425. throw new Error("Unable to create canvas for virtual joystick");
  110426. }
  110427. VirtualJoystick.vjCanvasContext = context;
  110428. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  110429. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  110430. document.body.appendChild(VirtualJoystick.Canvas);
  110431. }
  110432. VirtualJoystick.halfWidth = VirtualJoystick.Canvas.width / 2;
  110433. this.pressed = false;
  110434. // default joystick color
  110435. this._joystickColor = "cyan";
  110436. this._joystickPointerID = -1;
  110437. // current joystick position
  110438. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  110439. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  110440. // origin joystick position
  110441. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  110442. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  110443. this._onPointerDownHandlerRef = function (evt) {
  110444. _this._onPointerDown(evt);
  110445. };
  110446. this._onPointerMoveHandlerRef = function (evt) {
  110447. _this._onPointerMove(evt);
  110448. };
  110449. this._onPointerUpHandlerRef = function (evt) {
  110450. _this._onPointerUp(evt);
  110451. };
  110452. VirtualJoystick.Canvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  110453. VirtualJoystick.Canvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  110454. VirtualJoystick.Canvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  110455. VirtualJoystick.Canvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  110456. VirtualJoystick.Canvas.addEventListener("contextmenu", function (evt) {
  110457. evt.preventDefault(); // Disables system menu
  110458. }, false);
  110459. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  110460. }
  110461. /**
  110462. * Defines joystick sensibility (ie. the ratio beteen a physical move and virtual joystick position change)
  110463. * @param newJoystickSensibility defines the new sensibility
  110464. */
  110465. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  110466. this._joystickSensibility = newJoystickSensibility;
  110467. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  110468. };
  110469. VirtualJoystick.prototype._onPointerDown = function (e) {
  110470. var positionOnScreenCondition;
  110471. e.preventDefault();
  110472. if (this._leftJoystick === true) {
  110473. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  110474. }
  110475. else {
  110476. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  110477. }
  110478. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  110479. // First contact will be dedicated to the virtual joystick
  110480. this._joystickPointerID = e.pointerId;
  110481. this._joystickPointerStartPos.x = e.clientX;
  110482. this._joystickPointerStartPos.y = e.clientY;
  110483. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  110484. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  110485. this._deltaJoystickVector.x = 0;
  110486. this._deltaJoystickVector.y = 0;
  110487. this.pressed = true;
  110488. this._touches.add(e.pointerId.toString(), e);
  110489. }
  110490. else {
  110491. // You can only trigger the action buttons with a joystick declared
  110492. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  110493. this._action();
  110494. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  110495. }
  110496. }
  110497. };
  110498. VirtualJoystick.prototype._onPointerMove = function (e) {
  110499. // If the current pointer is the one associated to the joystick (first touch contact)
  110500. if (this._joystickPointerID == e.pointerId) {
  110501. this._joystickPointerPos.x = e.clientX;
  110502. this._joystickPointerPos.y = e.clientY;
  110503. this._deltaJoystickVector = this._joystickPointerPos.clone();
  110504. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  110505. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  110506. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  110507. switch (this._axisTargetedByLeftAndRight) {
  110508. case JoystickAxis.X:
  110509. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  110510. break;
  110511. case JoystickAxis.Y:
  110512. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  110513. break;
  110514. case JoystickAxis.Z:
  110515. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  110516. break;
  110517. }
  110518. var directionUpDown = this.reverseUpDown ? 1 : -1;
  110519. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  110520. switch (this._axisTargetedByUpAndDown) {
  110521. case JoystickAxis.X:
  110522. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  110523. break;
  110524. case JoystickAxis.Y:
  110525. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  110526. break;
  110527. case JoystickAxis.Z:
  110528. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  110529. break;
  110530. }
  110531. }
  110532. else {
  110533. var data = this._touches.get(e.pointerId.toString());
  110534. if (data) {
  110535. data.x = e.clientX;
  110536. data.y = e.clientY;
  110537. }
  110538. }
  110539. };
  110540. VirtualJoystick.prototype._onPointerUp = function (e) {
  110541. if (this._joystickPointerID == e.pointerId) {
  110542. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  110543. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  110544. this._joystickPointerID = -1;
  110545. this.pressed = false;
  110546. }
  110547. else {
  110548. var touch = this._touches.get(e.pointerId.toString());
  110549. if (touch) {
  110550. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  110551. }
  110552. }
  110553. this._deltaJoystickVector.x = 0;
  110554. this._deltaJoystickVector.y = 0;
  110555. this._touches.remove(e.pointerId.toString());
  110556. };
  110557. /**
  110558. * Change the color of the virtual joystick
  110559. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  110560. */
  110561. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  110562. this._joystickColor = newColor;
  110563. };
  110564. /**
  110565. * Defines a callback to call when the joystick is touched
  110566. * @param action defines the callback
  110567. */
  110568. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  110569. this._action = action;
  110570. };
  110571. /**
  110572. * Defines which axis you'd like to control for left & right
  110573. * @param axis defines the axis to use
  110574. */
  110575. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  110576. switch (axis) {
  110577. case JoystickAxis.X:
  110578. case JoystickAxis.Y:
  110579. case JoystickAxis.Z:
  110580. this._axisTargetedByLeftAndRight = axis;
  110581. break;
  110582. default:
  110583. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  110584. break;
  110585. }
  110586. };
  110587. /**
  110588. * Defines which axis you'd like to control for up & down
  110589. * @param axis defines the axis to use
  110590. */
  110591. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  110592. switch (axis) {
  110593. case JoystickAxis.X:
  110594. case JoystickAxis.Y:
  110595. case JoystickAxis.Z:
  110596. this._axisTargetedByUpAndDown = axis;
  110597. break;
  110598. default:
  110599. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  110600. break;
  110601. }
  110602. };
  110603. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  110604. var _this = this;
  110605. if (this.pressed) {
  110606. this._touches.forEach(function (key, touch) {
  110607. if (touch.pointerId === _this._joystickPointerID) {
  110608. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  110609. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  110610. VirtualJoystick.vjCanvasContext.beginPath();
  110611. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  110612. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  110613. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  110614. VirtualJoystick.vjCanvasContext.stroke();
  110615. VirtualJoystick.vjCanvasContext.closePath();
  110616. VirtualJoystick.vjCanvasContext.beginPath();
  110617. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  110618. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  110619. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  110620. VirtualJoystick.vjCanvasContext.stroke();
  110621. VirtualJoystick.vjCanvasContext.closePath();
  110622. VirtualJoystick.vjCanvasContext.beginPath();
  110623. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  110624. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  110625. VirtualJoystick.vjCanvasContext.stroke();
  110626. VirtualJoystick.vjCanvasContext.closePath();
  110627. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  110628. }
  110629. else {
  110630. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  110631. VirtualJoystick.vjCanvasContext.beginPath();
  110632. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  110633. VirtualJoystick.vjCanvasContext.beginPath();
  110634. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  110635. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  110636. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  110637. VirtualJoystick.vjCanvasContext.stroke();
  110638. VirtualJoystick.vjCanvasContext.closePath();
  110639. touch.prevX = touch.x;
  110640. touch.prevY = touch.y;
  110641. }
  110642. });
  110643. }
  110644. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  110645. };
  110646. /**
  110647. * Release internal HTML canvas
  110648. */
  110649. VirtualJoystick.prototype.releaseCanvas = function () {
  110650. if (VirtualJoystick.Canvas) {
  110651. VirtualJoystick.Canvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  110652. VirtualJoystick.Canvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  110653. VirtualJoystick.Canvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  110654. VirtualJoystick.Canvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  110655. window.removeEventListener("resize", this._onResize);
  110656. document.body.removeChild(VirtualJoystick.Canvas);
  110657. VirtualJoystick.Canvas = null;
  110658. }
  110659. };
  110660. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  110661. VirtualJoystick._globalJoystickIndex = 0;
  110662. return VirtualJoystick;
  110663. }());
  110664. BABYLON.VirtualJoystick = VirtualJoystick;
  110665. })(BABYLON || (BABYLON = {}));
  110666. //# sourceMappingURL=babylon.virtualJoystick.js.map
  110667. var BABYLON;
  110668. (function (BABYLON) {
  110669. BABYLON.Node.AddNodeConstructor("VirtualJoysticksCamera", function (name, scene) {
  110670. return function () { return new VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  110671. });
  110672. /**
  110673. * This represents a free type of camera. It can be useful in First Person Shooter game for instance.
  110674. * It is identical to the Free Camera and simply adds by default a virtual joystick.
  110675. * Virtual Joysticks are on-screen 2D graphics that are used to control the camera or other scene items.
  110676. * @see http://doc.babylonjs.com/features/cameras#virtual-joysticks-camera
  110677. */
  110678. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  110679. __extends(VirtualJoysticksCamera, _super);
  110680. /**
  110681. * Intantiates a VirtualJoysticksCamera. It can be useful in First Person Shooter game for instance.
  110682. * It is identical to the Free Camera and simply adds by default a virtual joystick.
  110683. * Virtual Joysticks are on-screen 2D graphics that are used to control the camera or other scene items.
  110684. * @see http://doc.babylonjs.com/features/cameras#virtual-joysticks-camera
  110685. * @param name Define the name of the camera in the scene
  110686. * @param position Define the start position of the camera in the scene
  110687. * @param scene Define the scene the camera belongs to
  110688. */
  110689. function VirtualJoysticksCamera(name, position, scene) {
  110690. var _this = _super.call(this, name, position, scene) || this;
  110691. _this.inputs.addVirtualJoystick();
  110692. return _this;
  110693. }
  110694. /**
  110695. * Gets the current object class name.
  110696. * @return the class name
  110697. */
  110698. VirtualJoysticksCamera.prototype.getClassName = function () {
  110699. return "VirtualJoysticksCamera";
  110700. };
  110701. return VirtualJoysticksCamera;
  110702. }(BABYLON.FreeCamera));
  110703. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  110704. })(BABYLON || (BABYLON = {}));
  110705. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  110706. var BABYLON;
  110707. (function (BABYLON) {
  110708. /**
  110709. * Manage the Virtual Joystick inputs to control the movement of a free camera.
  110710. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  110711. */
  110712. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  110713. function FreeCameraVirtualJoystickInput() {
  110714. }
  110715. /**
  110716. * Gets the left stick of the virtual joystick.
  110717. * @returns The virtual Joystick
  110718. */
  110719. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  110720. return this._leftjoystick;
  110721. };
  110722. /**
  110723. * Gets the right stick of the virtual joystick.
  110724. * @returns The virtual Joystick
  110725. */
  110726. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  110727. return this._rightjoystick;
  110728. };
  110729. /**
  110730. * Update the current camera state depending on the inputs that have been used this frame.
  110731. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  110732. */
  110733. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  110734. if (this._leftjoystick) {
  110735. var camera = this.camera;
  110736. var speed = camera._computeLocalCameraSpeed() * 50;
  110737. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  110738. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  110739. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  110740. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  110741. if (!this._leftjoystick.pressed) {
  110742. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  110743. }
  110744. if (!this._rightjoystick.pressed) {
  110745. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  110746. }
  110747. }
  110748. };
  110749. /**
  110750. * Attach the input controls to a specific dom element to get the input from.
  110751. * @param element Defines the element the controls should be listened from
  110752. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  110753. */
  110754. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  110755. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  110756. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  110757. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  110758. this._leftjoystick.setJoystickSensibility(0.15);
  110759. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  110760. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  110761. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  110762. this._rightjoystick.reverseUpDown = true;
  110763. this._rightjoystick.setJoystickSensibility(0.05);
  110764. this._rightjoystick.setJoystickColor("yellow");
  110765. };
  110766. /**
  110767. * Detach the current controls from the specified dom element.
  110768. * @param element Defines the element to stop listening the inputs from
  110769. */
  110770. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  110771. this._leftjoystick.releaseCanvas();
  110772. this._rightjoystick.releaseCanvas();
  110773. };
  110774. /**
  110775. * Gets the class name of the current intput.
  110776. * @returns the class name
  110777. */
  110778. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  110779. return "FreeCameraVirtualJoystickInput";
  110780. };
  110781. /**
  110782. * Get the friendly name associated with the input class.
  110783. * @returns the input friendly name
  110784. */
  110785. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  110786. return "virtualJoystick";
  110787. };
  110788. return FreeCameraVirtualJoystickInput;
  110789. }());
  110790. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  110791. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  110792. })(BABYLON || (BABYLON = {}));
  110793. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  110794. var BABYLON;
  110795. (function (BABYLON) {
  110796. /**
  110797. * Class used to specify simplification options
  110798. * @see http://doc.babylonjs.com/how_to/in-browser_mesh_simplification
  110799. */
  110800. var SimplificationSettings = /** @class */ (function () {
  110801. /**
  110802. * Creates a SimplificationSettings
  110803. * @param quality expected quality
  110804. * @param distance distance when this optimized version should be used
  110805. * @param optimizeMesh already optimized mesh
  110806. */
  110807. function SimplificationSettings(
  110808. /** expected quality */
  110809. quality,
  110810. /** distance when this optimized version should be used */
  110811. distance,
  110812. /** already optimized mesh */
  110813. optimizeMesh) {
  110814. this.quality = quality;
  110815. this.distance = distance;
  110816. this.optimizeMesh = optimizeMesh;
  110817. }
  110818. return SimplificationSettings;
  110819. }());
  110820. BABYLON.SimplificationSettings = SimplificationSettings;
  110821. /**
  110822. * Queue used to order the simplification tasks
  110823. * @see http://doc.babylonjs.com/how_to/in-browser_mesh_simplification
  110824. */
  110825. var SimplificationQueue = /** @class */ (function () {
  110826. /**
  110827. * Creates a new queue
  110828. */
  110829. function SimplificationQueue() {
  110830. this.running = false;
  110831. this._simplificationArray = [];
  110832. }
  110833. /**
  110834. * Adds a new simplification task
  110835. * @param task defines a task to add
  110836. */
  110837. SimplificationQueue.prototype.addTask = function (task) {
  110838. this._simplificationArray.push(task);
  110839. };
  110840. /**
  110841. * Execute next task
  110842. */
  110843. SimplificationQueue.prototype.executeNext = function () {
  110844. var task = this._simplificationArray.pop();
  110845. if (task) {
  110846. this.running = true;
  110847. this.runSimplification(task);
  110848. }
  110849. else {
  110850. this.running = false;
  110851. }
  110852. };
  110853. /**
  110854. * Execute a simplification task
  110855. * @param task defines the task to run
  110856. */
  110857. SimplificationQueue.prototype.runSimplification = function (task) {
  110858. var _this = this;
  110859. if (task.parallelProcessing) {
  110860. //parallel simplifier
  110861. task.settings.forEach(function (setting) {
  110862. var simplifier = _this.getSimplifier(task);
  110863. simplifier.simplify(setting, function (newMesh) {
  110864. task.mesh.addLODLevel(setting.distance, newMesh);
  110865. newMesh.isVisible = true;
  110866. //check if it is the last
  110867. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  110868. //all done, run the success callback.
  110869. task.successCallback();
  110870. }
  110871. _this.executeNext();
  110872. });
  110873. });
  110874. }
  110875. else {
  110876. //single simplifier.
  110877. var simplifier = this.getSimplifier(task);
  110878. var runDecimation = function (setting, callback) {
  110879. simplifier.simplify(setting, function (newMesh) {
  110880. task.mesh.addLODLevel(setting.distance, newMesh);
  110881. newMesh.isVisible = true;
  110882. //run the next quality level
  110883. callback();
  110884. });
  110885. };
  110886. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  110887. runDecimation(task.settings[loop.index], function () {
  110888. loop.executeNext();
  110889. });
  110890. }, function () {
  110891. //execution ended, run the success callback.
  110892. if (task.successCallback) {
  110893. task.successCallback();
  110894. }
  110895. _this.executeNext();
  110896. });
  110897. }
  110898. };
  110899. SimplificationQueue.prototype.getSimplifier = function (task) {
  110900. switch (task.simplificationType) {
  110901. case SimplificationType.QUADRATIC:
  110902. default:
  110903. return new QuadraticErrorSimplification(task.mesh);
  110904. }
  110905. };
  110906. return SimplificationQueue;
  110907. }());
  110908. BABYLON.SimplificationQueue = SimplificationQueue;
  110909. /**
  110910. * The implemented types of simplification
  110911. * At the moment only Quadratic Error Decimation is implemented
  110912. * @see http://doc.babylonjs.com/how_to/in-browser_mesh_simplification
  110913. */
  110914. var SimplificationType;
  110915. (function (SimplificationType) {
  110916. /** Quadratic error decimation */
  110917. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  110918. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  110919. var DecimationTriangle = /** @class */ (function () {
  110920. function DecimationTriangle(vertices) {
  110921. this.vertices = vertices;
  110922. this.error = new Array(4);
  110923. this.deleted = false;
  110924. this.isDirty = false;
  110925. this.deletePending = false;
  110926. this.borderFactor = 0;
  110927. }
  110928. return DecimationTriangle;
  110929. }());
  110930. var DecimationVertex = /** @class */ (function () {
  110931. function DecimationVertex(position, id) {
  110932. this.position = position;
  110933. this.id = id;
  110934. this.isBorder = true;
  110935. this.q = new QuadraticMatrix();
  110936. this.triangleCount = 0;
  110937. this.triangleStart = 0;
  110938. this.originalOffsets = [];
  110939. }
  110940. DecimationVertex.prototype.updatePosition = function (newPosition) {
  110941. this.position.copyFrom(newPosition);
  110942. };
  110943. return DecimationVertex;
  110944. }());
  110945. var QuadraticMatrix = /** @class */ (function () {
  110946. function QuadraticMatrix(data) {
  110947. this.data = new Array(10);
  110948. for (var i = 0; i < 10; ++i) {
  110949. if (data && data[i]) {
  110950. this.data[i] = data[i];
  110951. }
  110952. else {
  110953. this.data[i] = 0;
  110954. }
  110955. }
  110956. }
  110957. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  110958. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  110959. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  110960. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  110961. return det;
  110962. };
  110963. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  110964. for (var i = 0; i < 10; ++i) {
  110965. this.data[i] += matrix.data[i];
  110966. }
  110967. };
  110968. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  110969. for (var i = 0; i < 10; ++i) {
  110970. this.data[i] += data[i];
  110971. }
  110972. };
  110973. QuadraticMatrix.prototype.add = function (matrix) {
  110974. var m = new QuadraticMatrix();
  110975. for (var i = 0; i < 10; ++i) {
  110976. m.data[i] = this.data[i] + matrix.data[i];
  110977. }
  110978. return m;
  110979. };
  110980. QuadraticMatrix.FromData = function (a, b, c, d) {
  110981. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  110982. };
  110983. //returning an array to avoid garbage collection
  110984. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  110985. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  110986. };
  110987. return QuadraticMatrix;
  110988. }());
  110989. var Reference = /** @class */ (function () {
  110990. function Reference(vertexId, triangleId) {
  110991. this.vertexId = vertexId;
  110992. this.triangleId = triangleId;
  110993. }
  110994. return Reference;
  110995. }());
  110996. /**
  110997. * An implementation of the Quadratic Error simplification algorithm.
  110998. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  110999. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  111000. * @author RaananW
  111001. * @see http://doc.babylonjs.com/how_to/in-browser_mesh_simplification
  111002. */
  111003. var QuadraticErrorSimplification = /** @class */ (function () {
  111004. function QuadraticErrorSimplification(_mesh) {
  111005. this._mesh = _mesh;
  111006. this.syncIterations = 5000;
  111007. this.aggressiveness = 7;
  111008. this.decimationIterations = 100;
  111009. this.boundingBoxEpsilon = BABYLON.Epsilon;
  111010. }
  111011. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  111012. var _this = this;
  111013. this.initDecimatedMesh();
  111014. //iterating through the submeshes array, one after the other.
  111015. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  111016. _this.initWithMesh(loop.index, function () {
  111017. _this.runDecimation(settings, loop.index, function () {
  111018. loop.executeNext();
  111019. });
  111020. }, settings.optimizeMesh);
  111021. }, function () {
  111022. setTimeout(function () {
  111023. successCallback(_this._reconstructedMesh);
  111024. }, 0);
  111025. });
  111026. };
  111027. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  111028. var _this = this;
  111029. var targetCount = ~~(this.triangles.length * settings.quality);
  111030. var deletedTriangles = 0;
  111031. var triangleCount = this.triangles.length;
  111032. var iterationFunction = function (iteration, callback) {
  111033. setTimeout(function () {
  111034. if (iteration % 5 === 0) {
  111035. _this.updateMesh(iteration === 0);
  111036. }
  111037. for (var i = 0; i < _this.triangles.length; ++i) {
  111038. _this.triangles[i].isDirty = false;
  111039. }
  111040. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  111041. var trianglesIterator = function (i) {
  111042. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  111043. var t = _this.triangles[tIdx];
  111044. if (!t) {
  111045. return;
  111046. }
  111047. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  111048. return;
  111049. }
  111050. for (var j = 0; j < 3; ++j) {
  111051. if (t.error[j] < threshold) {
  111052. var deleted0 = [];
  111053. var deleted1 = [];
  111054. var v0 = t.vertices[j];
  111055. var v1 = t.vertices[(j + 1) % 3];
  111056. if (v0.isBorder || v1.isBorder) {
  111057. continue;
  111058. }
  111059. var p = BABYLON.Vector3.Zero();
  111060. var n = BABYLON.Vector3.Zero();
  111061. var uv = BABYLON.Vector2.Zero();
  111062. var color = new BABYLON.Color4(0, 0, 0, 1);
  111063. _this.calculateError(v0, v1, p, n, uv, color);
  111064. var delTr = new Array();
  111065. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr)) {
  111066. continue;
  111067. }
  111068. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr)) {
  111069. continue;
  111070. }
  111071. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0) {
  111072. continue;
  111073. }
  111074. var uniqueArray = new Array();
  111075. delTr.forEach(function (deletedT) {
  111076. if (uniqueArray.indexOf(deletedT) === -1) {
  111077. deletedT.deletePending = true;
  111078. uniqueArray.push(deletedT);
  111079. }
  111080. });
  111081. if (uniqueArray.length % 2 !== 0) {
  111082. continue;
  111083. }
  111084. v0.q = v1.q.add(v0.q);
  111085. v0.updatePosition(p);
  111086. var tStart = _this.references.length;
  111087. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  111088. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  111089. var tCount = _this.references.length - tStart;
  111090. if (tCount <= v0.triangleCount) {
  111091. if (tCount) {
  111092. for (var c = 0; c < tCount; c++) {
  111093. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  111094. }
  111095. }
  111096. }
  111097. else {
  111098. v0.triangleStart = tStart;
  111099. }
  111100. v0.triangleCount = tCount;
  111101. break;
  111102. }
  111103. }
  111104. };
  111105. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  111106. }, 0);
  111107. };
  111108. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  111109. if (triangleCount - deletedTriangles <= targetCount) {
  111110. loop.breakLoop();
  111111. }
  111112. else {
  111113. iterationFunction(loop.index, function () {
  111114. loop.executeNext();
  111115. });
  111116. }
  111117. }, function () {
  111118. setTimeout(function () {
  111119. //reconstruct this part of the mesh
  111120. _this.reconstructMesh(submeshIndex);
  111121. successCallback();
  111122. }, 0);
  111123. });
  111124. };
  111125. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  111126. var _this = this;
  111127. this.vertices = [];
  111128. this.triangles = [];
  111129. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  111130. var indices = this._mesh.getIndices();
  111131. var submesh = this._mesh.subMeshes[submeshIndex];
  111132. var findInVertices = function (positionToSearch) {
  111133. if (optimizeMesh) {
  111134. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  111135. if (_this.vertices[ii].position.equals(positionToSearch)) {
  111136. return _this.vertices[ii];
  111137. }
  111138. }
  111139. }
  111140. return null;
  111141. };
  111142. var vertexReferences = [];
  111143. var vertexInit = function (i) {
  111144. if (!positionData) {
  111145. return;
  111146. }
  111147. var offset = i + submesh.verticesStart;
  111148. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  111149. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  111150. vertex.originalOffsets.push(offset);
  111151. if (vertex.id === _this.vertices.length) {
  111152. _this.vertices.push(vertex);
  111153. }
  111154. vertexReferences.push(vertex.id);
  111155. };
  111156. //var totalVertices = mesh.getTotalVertices();
  111157. var totalVertices = submesh.verticesCount;
  111158. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  111159. var indicesInit = function (i) {
  111160. if (!indices) {
  111161. return;
  111162. }
  111163. var offset = (submesh.indexStart / 3) + i;
  111164. var pos = (offset * 3);
  111165. var i0 = indices[pos + 0];
  111166. var i1 = indices[pos + 1];
  111167. var i2 = indices[pos + 2];
  111168. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  111169. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  111170. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  111171. var triangle = new DecimationTriangle([v0, v1, v2]);
  111172. triangle.originalOffset = pos;
  111173. _this.triangles.push(triangle);
  111174. };
  111175. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  111176. _this.init(callback);
  111177. });
  111178. });
  111179. };
  111180. QuadraticErrorSimplification.prototype.init = function (callback) {
  111181. var _this = this;
  111182. var triangleInit1 = function (i) {
  111183. var t = _this.triangles[i];
  111184. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  111185. for (var j = 0; j < 3; j++) {
  111186. 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))));
  111187. }
  111188. };
  111189. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  111190. var triangleInit2 = function (i) {
  111191. var t = _this.triangles[i];
  111192. for (var j = 0; j < 3; ++j) {
  111193. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  111194. }
  111195. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  111196. };
  111197. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  111198. callback();
  111199. });
  111200. });
  111201. };
  111202. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  111203. var newTriangles = [];
  111204. var i;
  111205. for (i = 0; i < this.vertices.length; ++i) {
  111206. this.vertices[i].triangleCount = 0;
  111207. }
  111208. var t;
  111209. var j;
  111210. for (i = 0; i < this.triangles.length; ++i) {
  111211. if (!this.triangles[i].deleted) {
  111212. t = this.triangles[i];
  111213. for (j = 0; j < 3; ++j) {
  111214. t.vertices[j].triangleCount = 1;
  111215. }
  111216. newTriangles.push(t);
  111217. }
  111218. }
  111219. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  111220. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  111221. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  111222. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  111223. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  111224. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  111225. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  111226. var vertexCount = 0;
  111227. for (i = 0; i < this.vertices.length; ++i) {
  111228. var vertex = this.vertices[i];
  111229. vertex.id = vertexCount;
  111230. if (vertex.triangleCount) {
  111231. vertex.originalOffsets.forEach(function (originalOffset) {
  111232. if (!normalData) {
  111233. return;
  111234. }
  111235. newPositionData.push(vertex.position.x);
  111236. newPositionData.push(vertex.position.y);
  111237. newPositionData.push(vertex.position.z);
  111238. newNormalData.push(normalData[originalOffset * 3]);
  111239. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  111240. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  111241. if (uvs && uvs.length) {
  111242. newUVsData.push(uvs[(originalOffset * 2)]);
  111243. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  111244. }
  111245. else if (colorsData && colorsData.length) {
  111246. newColorsData.push(colorsData[(originalOffset * 4)]);
  111247. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  111248. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  111249. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  111250. }
  111251. ++vertexCount;
  111252. });
  111253. }
  111254. }
  111255. var startingIndex = this._reconstructedMesh.getTotalIndices();
  111256. var startingVertex = this._reconstructedMesh.getTotalVertices();
  111257. var submeshesArray = this._reconstructedMesh.subMeshes;
  111258. this._reconstructedMesh.subMeshes = [];
  111259. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  111260. var originalIndices = this._mesh.getIndices();
  111261. for (i = 0; i < newTriangles.length; ++i) {
  111262. t = newTriangles[i]; //now get the new referencing point for each vertex
  111263. [0, 1, 2].forEach(function (idx) {
  111264. var id = originalIndices[t.originalOffset + idx];
  111265. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  111266. if (offset < 0) {
  111267. offset = 0;
  111268. }
  111269. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  111270. });
  111271. }
  111272. //overwriting the old vertex buffers and indices.
  111273. this._reconstructedMesh.setIndices(newIndicesArray);
  111274. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  111275. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  111276. if (newUVsData.length > 0) {
  111277. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  111278. }
  111279. if (newColorsData.length > 0) {
  111280. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  111281. }
  111282. //create submesh
  111283. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  111284. if (submeshIndex > 0) {
  111285. this._reconstructedMesh.subMeshes = [];
  111286. submeshesArray.forEach(function (submesh) {
  111287. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  111288. });
  111289. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  111290. }
  111291. };
  111292. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  111293. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  111294. this._reconstructedMesh.material = this._mesh.material;
  111295. this._reconstructedMesh.parent = this._mesh.parent;
  111296. this._reconstructedMesh.isVisible = false;
  111297. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  111298. };
  111299. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  111300. for (var i = 0; i < vertex1.triangleCount; ++i) {
  111301. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  111302. if (t.deleted) {
  111303. continue;
  111304. }
  111305. var s = this.references[vertex1.triangleStart + i].vertexId;
  111306. var v1 = t.vertices[(s + 1) % 3];
  111307. var v2 = t.vertices[(s + 2) % 3];
  111308. if ((v1 === vertex2 || v2 === vertex2)) {
  111309. deletedArray[i] = true;
  111310. delTr.push(t);
  111311. continue;
  111312. }
  111313. var d1 = v1.position.subtract(point);
  111314. d1 = d1.normalize();
  111315. var d2 = v2.position.subtract(point);
  111316. d2 = d2.normalize();
  111317. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999) {
  111318. return true;
  111319. }
  111320. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  111321. deletedArray[i] = false;
  111322. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2) {
  111323. return true;
  111324. }
  111325. }
  111326. return false;
  111327. };
  111328. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  111329. var newDeleted = deletedTriangles;
  111330. for (var i = 0; i < vertex.triangleCount; ++i) {
  111331. var ref = this.references[vertex.triangleStart + i];
  111332. var t = this.triangles[ref.triangleId];
  111333. if (t.deleted) {
  111334. continue;
  111335. }
  111336. if (deletedArray[i] && t.deletePending) {
  111337. t.deleted = true;
  111338. newDeleted++;
  111339. continue;
  111340. }
  111341. t.vertices[ref.vertexId] = origVertex;
  111342. t.isDirty = true;
  111343. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  111344. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  111345. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  111346. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  111347. this.references.push(ref);
  111348. }
  111349. return newDeleted;
  111350. };
  111351. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  111352. for (var i = 0; i < this.vertices.length; ++i) {
  111353. var vCount = [];
  111354. var vId = [];
  111355. var v = this.vertices[i];
  111356. var j;
  111357. for (j = 0; j < v.triangleCount; ++j) {
  111358. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  111359. for (var ii = 0; ii < 3; ii++) {
  111360. var ofs = 0;
  111361. var vv = triangle.vertices[ii];
  111362. while (ofs < vCount.length) {
  111363. if (vId[ofs] === vv.id) {
  111364. break;
  111365. }
  111366. ++ofs;
  111367. }
  111368. if (ofs === vCount.length) {
  111369. vCount.push(1);
  111370. vId.push(vv.id);
  111371. }
  111372. else {
  111373. vCount[ofs]++;
  111374. }
  111375. }
  111376. }
  111377. for (j = 0; j < vCount.length; ++j) {
  111378. if (vCount[j] === 1) {
  111379. this.vertices[vId[j]].isBorder = true;
  111380. }
  111381. else {
  111382. this.vertices[vId[j]].isBorder = false;
  111383. }
  111384. }
  111385. }
  111386. };
  111387. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  111388. if (identifyBorders === void 0) { identifyBorders = false; }
  111389. var i;
  111390. if (!identifyBorders) {
  111391. var newTrianglesVector = [];
  111392. for (i = 0; i < this.triangles.length; ++i) {
  111393. if (!this.triangles[i].deleted) {
  111394. newTrianglesVector.push(this.triangles[i]);
  111395. }
  111396. }
  111397. this.triangles = newTrianglesVector;
  111398. }
  111399. for (i = 0; i < this.vertices.length; ++i) {
  111400. this.vertices[i].triangleCount = 0;
  111401. this.vertices[i].triangleStart = 0;
  111402. }
  111403. var t;
  111404. var j;
  111405. var v;
  111406. for (i = 0; i < this.triangles.length; ++i) {
  111407. t = this.triangles[i];
  111408. for (j = 0; j < 3; ++j) {
  111409. v = t.vertices[j];
  111410. v.triangleCount++;
  111411. }
  111412. }
  111413. var tStart = 0;
  111414. for (i = 0; i < this.vertices.length; ++i) {
  111415. this.vertices[i].triangleStart = tStart;
  111416. tStart += this.vertices[i].triangleCount;
  111417. this.vertices[i].triangleCount = 0;
  111418. }
  111419. var newReferences = new Array(this.triangles.length * 3);
  111420. for (i = 0; i < this.triangles.length; ++i) {
  111421. t = this.triangles[i];
  111422. for (j = 0; j < 3; ++j) {
  111423. v = t.vertices[j];
  111424. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  111425. v.triangleCount++;
  111426. }
  111427. }
  111428. this.references = newReferences;
  111429. if (identifyBorders) {
  111430. this.identifyBorder();
  111431. }
  111432. };
  111433. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  111434. var x = point.x;
  111435. var y = point.y;
  111436. var z = point.z;
  111437. 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
  111438. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  111439. };
  111440. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  111441. var q = vertex1.q.add(vertex2.q);
  111442. var border = vertex1.isBorder && vertex2.isBorder;
  111443. var error = 0;
  111444. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  111445. if (qDet !== 0 && !border) {
  111446. if (!pointResult) {
  111447. pointResult = BABYLON.Vector3.Zero();
  111448. }
  111449. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  111450. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  111451. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  111452. error = this.vertexError(q, pointResult);
  111453. }
  111454. else {
  111455. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  111456. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  111457. var error1 = this.vertexError(q, vertex1.position);
  111458. var error2 = this.vertexError(q, vertex2.position);
  111459. var error3 = this.vertexError(q, p3);
  111460. error = Math.min(error1, error2, error3);
  111461. if (error === error1) {
  111462. if (pointResult) {
  111463. pointResult.copyFrom(vertex1.position);
  111464. }
  111465. }
  111466. else if (error === error2) {
  111467. if (pointResult) {
  111468. pointResult.copyFrom(vertex2.position);
  111469. }
  111470. }
  111471. else {
  111472. if (pointResult) {
  111473. pointResult.copyFrom(p3);
  111474. }
  111475. }
  111476. }
  111477. return error;
  111478. };
  111479. return QuadraticErrorSimplification;
  111480. }());
  111481. })(BABYLON || (BABYLON = {}));
  111482. //# sourceMappingURL=babylon.meshSimplification.js.map
  111483. var BABYLON;
  111484. (function (BABYLON) {
  111485. Object.defineProperty(BABYLON.Scene.prototype, "simplificationQueue", {
  111486. get: function () {
  111487. if (!this._simplificationQueue) {
  111488. this._simplificationQueue = new BABYLON.SimplificationQueue();
  111489. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE);
  111490. if (!component) {
  111491. component = new SimplicationQueueSceneComponent(this);
  111492. this._addComponent(component);
  111493. }
  111494. }
  111495. return this._simplificationQueue;
  111496. },
  111497. set: function (value) {
  111498. this._simplificationQueue = value;
  111499. },
  111500. enumerable: true,
  111501. configurable: true
  111502. });
  111503. BABYLON.Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  111504. if (parallelProcessing === void 0) { parallelProcessing = true; }
  111505. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  111506. this.getScene().simplificationQueue.addTask({
  111507. settings: settings,
  111508. parallelProcessing: parallelProcessing,
  111509. mesh: this,
  111510. simplificationType: simplificationType,
  111511. successCallback: successCallback
  111512. });
  111513. return this;
  111514. };
  111515. /**
  111516. * Defines the simplification queue scene component responsible to help scheduling the various simplification task
  111517. * created in a scene
  111518. */
  111519. var SimplicationQueueSceneComponent = /** @class */ (function () {
  111520. /**
  111521. * Creates a new instance of the component for the given scene
  111522. * @param scene Defines the scene to register the component in
  111523. */
  111524. function SimplicationQueueSceneComponent(scene) {
  111525. /**
  111526. * The component name helpfull to identify the component in the list of scene components.
  111527. */
  111528. this.name = BABYLON.SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE;
  111529. this.scene = scene;
  111530. }
  111531. /**
  111532. * Registers the component in a given scene
  111533. */
  111534. SimplicationQueueSceneComponent.prototype.register = function () {
  111535. this.scene._beforeCameraUpdateStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE, this, this._beforeCameraUpdate);
  111536. };
  111537. /**
  111538. * Rebuilds the elements related to this component in case of
  111539. * context lost for instance.
  111540. */
  111541. SimplicationQueueSceneComponent.prototype.rebuild = function () {
  111542. // Nothing to do for this component
  111543. };
  111544. /**
  111545. * Disposes the component and the associated ressources
  111546. */
  111547. SimplicationQueueSceneComponent.prototype.dispose = function () {
  111548. // Nothing to do for this component
  111549. };
  111550. SimplicationQueueSceneComponent.prototype._beforeCameraUpdate = function () {
  111551. if (this.scene._simplificationQueue && !this.scene._simplificationQueue.running) {
  111552. this.scene._simplificationQueue.executeNext();
  111553. }
  111554. };
  111555. return SimplicationQueueSceneComponent;
  111556. }());
  111557. BABYLON.SimplicationQueueSceneComponent = SimplicationQueueSceneComponent;
  111558. })(BABYLON || (BABYLON = {}));
  111559. //# sourceMappingURL=babylon.meshSimplificationSceneComponent.js.map
  111560. var BABYLON;
  111561. (function (BABYLON) {
  111562. /**
  111563. * Class used to represent a specific level of detail of a mesh
  111564. * @see http://doc.babylonjs.com/how_to/how_to_use_lod
  111565. */
  111566. var MeshLODLevel = /** @class */ (function () {
  111567. /**
  111568. * Creates a new LOD level
  111569. * @param distance defines the distance where this level should star being displayed
  111570. * @param mesh defines the mesh to use to render this level
  111571. */
  111572. function MeshLODLevel(
  111573. /** Defines the distance where this level should star being displayed */
  111574. distance,
  111575. /** Defines the mesh to use to render this level */
  111576. mesh) {
  111577. this.distance = distance;
  111578. this.mesh = mesh;
  111579. }
  111580. return MeshLODLevel;
  111581. }());
  111582. BABYLON.MeshLODLevel = MeshLODLevel;
  111583. })(BABYLON || (BABYLON = {}));
  111584. //# sourceMappingURL=babylon.meshLODLevel.js.map
  111585. var BABYLON;
  111586. (function (BABYLON) {
  111587. /**
  111588. * Defines the root class used to create scene optimization to use with SceneOptimizer
  111589. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  111590. */
  111591. var SceneOptimization = /** @class */ (function () {
  111592. /**
  111593. * Creates the SceneOptimization object
  111594. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  111595. * @param desc defines the description associated with the optimization
  111596. */
  111597. function SceneOptimization(
  111598. /**
  111599. * Defines the priority of this optimization (0 by default which means first in the list)
  111600. */
  111601. priority) {
  111602. if (priority === void 0) { priority = 0; }
  111603. this.priority = priority;
  111604. }
  111605. /**
  111606. * Gets a string describing the action executed by the current optimization
  111607. * @returns description string
  111608. */
  111609. SceneOptimization.prototype.getDescription = function () {
  111610. return "";
  111611. };
  111612. /**
  111613. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  111614. * @param scene defines the current scene where to apply this optimization
  111615. * @param optimizer defines the current optimizer
  111616. * @returns true if everything that can be done was applied
  111617. */
  111618. SceneOptimization.prototype.apply = function (scene, optimizer) {
  111619. return true;
  111620. };
  111621. return SceneOptimization;
  111622. }());
  111623. BABYLON.SceneOptimization = SceneOptimization;
  111624. /**
  111625. * Defines an optimization used to reduce the size of render target textures
  111626. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  111627. */
  111628. var TextureOptimization = /** @class */ (function (_super) {
  111629. __extends(TextureOptimization, _super);
  111630. /**
  111631. * Creates the TextureOptimization object
  111632. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  111633. * @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
  111634. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  111635. */
  111636. function TextureOptimization(
  111637. /**
  111638. * Defines the priority of this optimization (0 by default which means first in the list)
  111639. */
  111640. priority,
  111641. /**
  111642. * 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
  111643. */
  111644. maximumSize,
  111645. /**
  111646. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  111647. */
  111648. step) {
  111649. if (priority === void 0) { priority = 0; }
  111650. if (maximumSize === void 0) { maximumSize = 1024; }
  111651. if (step === void 0) { step = 0.5; }
  111652. var _this = _super.call(this, priority) || this;
  111653. _this.priority = priority;
  111654. _this.maximumSize = maximumSize;
  111655. _this.step = step;
  111656. return _this;
  111657. }
  111658. /**
  111659. * Gets a string describing the action executed by the current optimization
  111660. * @returns description string
  111661. */
  111662. TextureOptimization.prototype.getDescription = function () {
  111663. return "Reducing render target texture size to " + this.maximumSize;
  111664. };
  111665. /**
  111666. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  111667. * @param scene defines the current scene where to apply this optimization
  111668. * @param optimizer defines the current optimizer
  111669. * @returns true if everything that can be done was applied
  111670. */
  111671. TextureOptimization.prototype.apply = function (scene, optimizer) {
  111672. var allDone = true;
  111673. for (var index = 0; index < scene.textures.length; index++) {
  111674. var texture = scene.textures[index];
  111675. if (!texture.canRescale || texture.getContext) {
  111676. continue;
  111677. }
  111678. var currentSize = texture.getSize();
  111679. var maxDimension = Math.max(currentSize.width, currentSize.height);
  111680. if (maxDimension > this.maximumSize) {
  111681. texture.scale(this.step);
  111682. allDone = false;
  111683. }
  111684. }
  111685. return allDone;
  111686. };
  111687. return TextureOptimization;
  111688. }(SceneOptimization));
  111689. BABYLON.TextureOptimization = TextureOptimization;
  111690. /**
  111691. * Defines an optimization used to increase or decrease the rendering resolution
  111692. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  111693. */
  111694. var HardwareScalingOptimization = /** @class */ (function (_super) {
  111695. __extends(HardwareScalingOptimization, _super);
  111696. /**
  111697. * Creates the HardwareScalingOptimization object
  111698. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  111699. * @param maximumScale defines the maximum scale to use (2 by default)
  111700. * @param step defines the step to use between two passes (0.5 by default)
  111701. */
  111702. function HardwareScalingOptimization(
  111703. /**
  111704. * Defines the priority of this optimization (0 by default which means first in the list)
  111705. */
  111706. priority,
  111707. /**
  111708. * Defines the maximum scale to use (2 by default)
  111709. */
  111710. maximumScale,
  111711. /**
  111712. * Defines the step to use between two passes (0.5 by default)
  111713. */
  111714. step) {
  111715. if (priority === void 0) { priority = 0; }
  111716. if (maximumScale === void 0) { maximumScale = 2; }
  111717. if (step === void 0) { step = 0.25; }
  111718. var _this = _super.call(this, priority) || this;
  111719. _this.priority = priority;
  111720. _this.maximumScale = maximumScale;
  111721. _this.step = step;
  111722. _this._currentScale = -1;
  111723. _this._directionOffset = 1;
  111724. return _this;
  111725. }
  111726. /**
  111727. * Gets a string describing the action executed by the current optimization
  111728. * @return description string
  111729. */
  111730. HardwareScalingOptimization.prototype.getDescription = function () {
  111731. return "Setting hardware scaling level to " + this._currentScale;
  111732. };
  111733. /**
  111734. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  111735. * @param scene defines the current scene where to apply this optimization
  111736. * @param optimizer defines the current optimizer
  111737. * @returns true if everything that can be done was applied
  111738. */
  111739. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  111740. if (this._currentScale === -1) {
  111741. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  111742. if (this._currentScale > this.maximumScale) {
  111743. this._directionOffset = -1;
  111744. }
  111745. }
  111746. this._currentScale += this._directionOffset * this.step;
  111747. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  111748. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  111749. };
  111750. return HardwareScalingOptimization;
  111751. }(SceneOptimization));
  111752. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  111753. /**
  111754. * Defines an optimization used to remove shadows
  111755. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  111756. */
  111757. var ShadowsOptimization = /** @class */ (function (_super) {
  111758. __extends(ShadowsOptimization, _super);
  111759. function ShadowsOptimization() {
  111760. return _super !== null && _super.apply(this, arguments) || this;
  111761. }
  111762. /**
  111763. * Gets a string describing the action executed by the current optimization
  111764. * @return description string
  111765. */
  111766. ShadowsOptimization.prototype.getDescription = function () {
  111767. return "Turning shadows on/off";
  111768. };
  111769. /**
  111770. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  111771. * @param scene defines the current scene where to apply this optimization
  111772. * @param optimizer defines the current optimizer
  111773. * @returns true if everything that can be done was applied
  111774. */
  111775. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  111776. scene.shadowsEnabled = optimizer.isInImprovementMode;
  111777. return true;
  111778. };
  111779. return ShadowsOptimization;
  111780. }(SceneOptimization));
  111781. BABYLON.ShadowsOptimization = ShadowsOptimization;
  111782. /**
  111783. * Defines an optimization used to turn post-processes off
  111784. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  111785. */
  111786. var PostProcessesOptimization = /** @class */ (function (_super) {
  111787. __extends(PostProcessesOptimization, _super);
  111788. function PostProcessesOptimization() {
  111789. return _super !== null && _super.apply(this, arguments) || this;
  111790. }
  111791. /**
  111792. * Gets a string describing the action executed by the current optimization
  111793. * @return description string
  111794. */
  111795. PostProcessesOptimization.prototype.getDescription = function () {
  111796. return "Turning post-processes on/off";
  111797. };
  111798. /**
  111799. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  111800. * @param scene defines the current scene where to apply this optimization
  111801. * @param optimizer defines the current optimizer
  111802. * @returns true if everything that can be done was applied
  111803. */
  111804. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  111805. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  111806. return true;
  111807. };
  111808. return PostProcessesOptimization;
  111809. }(SceneOptimization));
  111810. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  111811. /**
  111812. * Defines an optimization used to turn lens flares off
  111813. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  111814. */
  111815. var LensFlaresOptimization = /** @class */ (function (_super) {
  111816. __extends(LensFlaresOptimization, _super);
  111817. function LensFlaresOptimization() {
  111818. return _super !== null && _super.apply(this, arguments) || this;
  111819. }
  111820. /**
  111821. * Gets a string describing the action executed by the current optimization
  111822. * @return description string
  111823. */
  111824. LensFlaresOptimization.prototype.getDescription = function () {
  111825. return "Turning lens flares on/off";
  111826. };
  111827. /**
  111828. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  111829. * @param scene defines the current scene where to apply this optimization
  111830. * @param optimizer defines the current optimizer
  111831. * @returns true if everything that can be done was applied
  111832. */
  111833. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  111834. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  111835. return true;
  111836. };
  111837. return LensFlaresOptimization;
  111838. }(SceneOptimization));
  111839. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  111840. /**
  111841. * Defines an optimization based on user defined callback.
  111842. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  111843. */
  111844. var CustomOptimization = /** @class */ (function (_super) {
  111845. __extends(CustomOptimization, _super);
  111846. function CustomOptimization() {
  111847. return _super !== null && _super.apply(this, arguments) || this;
  111848. }
  111849. /**
  111850. * Gets a string describing the action executed by the current optimization
  111851. * @returns description string
  111852. */
  111853. CustomOptimization.prototype.getDescription = function () {
  111854. if (this.onGetDescription) {
  111855. return this.onGetDescription();
  111856. }
  111857. return "Running user defined callback";
  111858. };
  111859. /**
  111860. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  111861. * @param scene defines the current scene where to apply this optimization
  111862. * @param optimizer defines the current optimizer
  111863. * @returns true if everything that can be done was applied
  111864. */
  111865. CustomOptimization.prototype.apply = function (scene, optimizer) {
  111866. if (this.onApply) {
  111867. return this.onApply(scene, optimizer);
  111868. }
  111869. return true;
  111870. };
  111871. return CustomOptimization;
  111872. }(SceneOptimization));
  111873. BABYLON.CustomOptimization = CustomOptimization;
  111874. /**
  111875. * Defines an optimization used to turn particles off
  111876. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  111877. */
  111878. var ParticlesOptimization = /** @class */ (function (_super) {
  111879. __extends(ParticlesOptimization, _super);
  111880. function ParticlesOptimization() {
  111881. return _super !== null && _super.apply(this, arguments) || this;
  111882. }
  111883. /**
  111884. * Gets a string describing the action executed by the current optimization
  111885. * @return description string
  111886. */
  111887. ParticlesOptimization.prototype.getDescription = function () {
  111888. return "Turning particles on/off";
  111889. };
  111890. /**
  111891. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  111892. * @param scene defines the current scene where to apply this optimization
  111893. * @param optimizer defines the current optimizer
  111894. * @returns true if everything that can be done was applied
  111895. */
  111896. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  111897. scene.particlesEnabled = optimizer.isInImprovementMode;
  111898. return true;
  111899. };
  111900. return ParticlesOptimization;
  111901. }(SceneOptimization));
  111902. BABYLON.ParticlesOptimization = ParticlesOptimization;
  111903. /**
  111904. * Defines an optimization used to turn render targets off
  111905. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  111906. */
  111907. var RenderTargetsOptimization = /** @class */ (function (_super) {
  111908. __extends(RenderTargetsOptimization, _super);
  111909. function RenderTargetsOptimization() {
  111910. return _super !== null && _super.apply(this, arguments) || this;
  111911. }
  111912. /**
  111913. * Gets a string describing the action executed by the current optimization
  111914. * @return description string
  111915. */
  111916. RenderTargetsOptimization.prototype.getDescription = function () {
  111917. return "Turning render targets off";
  111918. };
  111919. /**
  111920. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  111921. * @param scene defines the current scene where to apply this optimization
  111922. * @param optimizer defines the current optimizer
  111923. * @returns true if everything that can be done was applied
  111924. */
  111925. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  111926. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  111927. return true;
  111928. };
  111929. return RenderTargetsOptimization;
  111930. }(SceneOptimization));
  111931. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  111932. /**
  111933. * Defines an optimization used to merge meshes with compatible materials
  111934. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  111935. */
  111936. var MergeMeshesOptimization = /** @class */ (function (_super) {
  111937. __extends(MergeMeshesOptimization, _super);
  111938. function MergeMeshesOptimization() {
  111939. var _this = _super !== null && _super.apply(this, arguments) || this;
  111940. _this._canBeMerged = function (abstractMesh) {
  111941. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  111942. return false;
  111943. }
  111944. var mesh = abstractMesh;
  111945. if (mesh.isDisposed()) {
  111946. return false;
  111947. }
  111948. if (!mesh.isVisible || !mesh.isEnabled()) {
  111949. return false;
  111950. }
  111951. if (mesh.instances.length > 0) {
  111952. return false;
  111953. }
  111954. if (mesh.skeleton || mesh.hasLODLevels) {
  111955. return false;
  111956. }
  111957. return true;
  111958. };
  111959. return _this;
  111960. }
  111961. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  111962. /**
  111963. * Gets or sets a boolean which defines if optimization octree has to be updated
  111964. */
  111965. get: function () {
  111966. return MergeMeshesOptimization._UpdateSelectionTree;
  111967. },
  111968. /**
  111969. * Gets or sets a boolean which defines if optimization octree has to be updated
  111970. */
  111971. set: function (value) {
  111972. MergeMeshesOptimization._UpdateSelectionTree = value;
  111973. },
  111974. enumerable: true,
  111975. configurable: true
  111976. });
  111977. /**
  111978. * Gets a string describing the action executed by the current optimization
  111979. * @return description string
  111980. */
  111981. MergeMeshesOptimization.prototype.getDescription = function () {
  111982. return "Merging similar meshes together";
  111983. };
  111984. /**
  111985. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  111986. * @param scene defines the current scene where to apply this optimization
  111987. * @param optimizer defines the current optimizer
  111988. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  111989. * @returns true if everything that can be done was applied
  111990. */
  111991. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  111992. var globalPool = scene.meshes.slice(0);
  111993. var globalLength = globalPool.length;
  111994. for (var index = 0; index < globalLength; index++) {
  111995. var currentPool = new Array();
  111996. var current = globalPool[index];
  111997. // Checks
  111998. if (!this._canBeMerged(current)) {
  111999. continue;
  112000. }
  112001. currentPool.push(current);
  112002. // Find compatible meshes
  112003. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  112004. var otherMesh = globalPool[subIndex];
  112005. if (!this._canBeMerged(otherMesh)) {
  112006. continue;
  112007. }
  112008. if (otherMesh.material !== current.material) {
  112009. continue;
  112010. }
  112011. if (otherMesh.checkCollisions !== current.checkCollisions) {
  112012. continue;
  112013. }
  112014. currentPool.push(otherMesh);
  112015. globalLength--;
  112016. globalPool.splice(subIndex, 1);
  112017. subIndex--;
  112018. }
  112019. if (currentPool.length < 2) {
  112020. continue;
  112021. }
  112022. // Merge meshes
  112023. BABYLON.Mesh.MergeMeshes(currentPool, undefined, true);
  112024. }
  112025. // Call the octree system optimization if it is defined.
  112026. var sceneAsAny = scene;
  112027. if (sceneAsAny.createOrUpdateSelectionOctree) {
  112028. if (updateSelectionTree != undefined) {
  112029. if (updateSelectionTree) {
  112030. sceneAsAny.createOrUpdateSelectionOctree();
  112031. }
  112032. }
  112033. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  112034. sceneAsAny.createOrUpdateSelectionOctree();
  112035. }
  112036. }
  112037. return true;
  112038. };
  112039. MergeMeshesOptimization._UpdateSelectionTree = false;
  112040. return MergeMeshesOptimization;
  112041. }(SceneOptimization));
  112042. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  112043. /**
  112044. * Defines a list of options used by SceneOptimizer
  112045. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  112046. */
  112047. var SceneOptimizerOptions = /** @class */ (function () {
  112048. /**
  112049. * Creates a new list of options used by SceneOptimizer
  112050. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  112051. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  112052. */
  112053. function SceneOptimizerOptions(
  112054. /**
  112055. * Defines the target frame rate to reach (60 by default)
  112056. */
  112057. targetFrameRate,
  112058. /**
  112059. * Defines the interval between two checkes (2000ms by default)
  112060. */
  112061. trackerDuration) {
  112062. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  112063. if (trackerDuration === void 0) { trackerDuration = 2000; }
  112064. this.targetFrameRate = targetFrameRate;
  112065. this.trackerDuration = trackerDuration;
  112066. /**
  112067. * Gets the list of optimizations to apply
  112068. */
  112069. this.optimizations = new Array();
  112070. }
  112071. /**
  112072. * Add a new optimization
  112073. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  112074. * @returns the current SceneOptimizerOptions
  112075. */
  112076. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  112077. this.optimizations.push(optimization);
  112078. return this;
  112079. };
  112080. /**
  112081. * Add a new custom optimization
  112082. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  112083. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  112084. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  112085. * @returns the current SceneOptimizerOptions
  112086. */
  112087. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  112088. if (priority === void 0) { priority = 0; }
  112089. var optimization = new CustomOptimization(priority);
  112090. optimization.onApply = onApply;
  112091. optimization.onGetDescription = onGetDescription;
  112092. this.optimizations.push(optimization);
  112093. return this;
  112094. };
  112095. /**
  112096. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  112097. * @param targetFrameRate defines the target frame rate (60 by default)
  112098. * @returns a SceneOptimizerOptions object
  112099. */
  112100. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  112101. var result = new SceneOptimizerOptions(targetFrameRate);
  112102. var priority = 0;
  112103. result.addOptimization(new MergeMeshesOptimization(priority));
  112104. result.addOptimization(new ShadowsOptimization(priority));
  112105. result.addOptimization(new LensFlaresOptimization(priority));
  112106. // Next priority
  112107. priority++;
  112108. result.addOptimization(new PostProcessesOptimization(priority));
  112109. result.addOptimization(new ParticlesOptimization(priority));
  112110. // Next priority
  112111. priority++;
  112112. result.addOptimization(new TextureOptimization(priority, 1024));
  112113. return result;
  112114. };
  112115. /**
  112116. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  112117. * @param targetFrameRate defines the target frame rate (60 by default)
  112118. * @returns a SceneOptimizerOptions object
  112119. */
  112120. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  112121. var result = new SceneOptimizerOptions(targetFrameRate);
  112122. var priority = 0;
  112123. result.addOptimization(new MergeMeshesOptimization(priority));
  112124. result.addOptimization(new ShadowsOptimization(priority));
  112125. result.addOptimization(new LensFlaresOptimization(priority));
  112126. // Next priority
  112127. priority++;
  112128. result.addOptimization(new PostProcessesOptimization(priority));
  112129. result.addOptimization(new ParticlesOptimization(priority));
  112130. // Next priority
  112131. priority++;
  112132. result.addOptimization(new TextureOptimization(priority, 512));
  112133. // Next priority
  112134. priority++;
  112135. result.addOptimization(new RenderTargetsOptimization(priority));
  112136. // Next priority
  112137. priority++;
  112138. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  112139. return result;
  112140. };
  112141. /**
  112142. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  112143. * @param targetFrameRate defines the target frame rate (60 by default)
  112144. * @returns a SceneOptimizerOptions object
  112145. */
  112146. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  112147. var result = new SceneOptimizerOptions(targetFrameRate);
  112148. var priority = 0;
  112149. result.addOptimization(new MergeMeshesOptimization(priority));
  112150. result.addOptimization(new ShadowsOptimization(priority));
  112151. result.addOptimization(new LensFlaresOptimization(priority));
  112152. // Next priority
  112153. priority++;
  112154. result.addOptimization(new PostProcessesOptimization(priority));
  112155. result.addOptimization(new ParticlesOptimization(priority));
  112156. // Next priority
  112157. priority++;
  112158. result.addOptimization(new TextureOptimization(priority, 256));
  112159. // Next priority
  112160. priority++;
  112161. result.addOptimization(new RenderTargetsOptimization(priority));
  112162. // Next priority
  112163. priority++;
  112164. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  112165. return result;
  112166. };
  112167. return SceneOptimizerOptions;
  112168. }());
  112169. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  112170. /**
  112171. * Class used to run optimizations in order to reach a target frame rate
  112172. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  112173. */
  112174. var SceneOptimizer = /** @class */ (function () {
  112175. /**
  112176. * Creates a new SceneOptimizer
  112177. * @param scene defines the scene to work on
  112178. * @param options defines the options to use with the SceneOptimizer
  112179. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  112180. * @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)
  112181. */
  112182. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  112183. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  112184. if (improvementMode === void 0) { improvementMode = false; }
  112185. var _this = this;
  112186. this._isRunning = false;
  112187. this._currentPriorityLevel = 0;
  112188. this._targetFrameRate = 60;
  112189. this._trackerDuration = 2000;
  112190. this._currentFrameRate = 0;
  112191. this._improvementMode = false;
  112192. /**
  112193. * Defines an observable called when the optimizer reaches the target frame rate
  112194. */
  112195. this.onSuccessObservable = new BABYLON.Observable();
  112196. /**
  112197. * Defines an observable called when the optimizer enables an optimization
  112198. */
  112199. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  112200. /**
  112201. * Defines an observable called when the optimizer is not able to reach the target frame rate
  112202. */
  112203. this.onFailureObservable = new BABYLON.Observable();
  112204. if (!options) {
  112205. this._options = new SceneOptimizerOptions();
  112206. }
  112207. else {
  112208. this._options = options;
  112209. }
  112210. if (this._options.targetFrameRate) {
  112211. this._targetFrameRate = this._options.targetFrameRate;
  112212. }
  112213. if (this._options.trackerDuration) {
  112214. this._trackerDuration = this._options.trackerDuration;
  112215. }
  112216. if (autoGeneratePriorities) {
  112217. var priority = 0;
  112218. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  112219. var optim = _a[_i];
  112220. optim.priority = priority++;
  112221. }
  112222. }
  112223. this._improvementMode = improvementMode;
  112224. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  112225. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  112226. _this._sceneDisposeObserver = null;
  112227. _this.dispose();
  112228. });
  112229. }
  112230. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  112231. /**
  112232. * Gets a boolean indicating if the optimizer is in improvement mode
  112233. */
  112234. get: function () {
  112235. return this._improvementMode;
  112236. },
  112237. enumerable: true,
  112238. configurable: true
  112239. });
  112240. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  112241. /**
  112242. * Gets the current priority level (0 at start)
  112243. */
  112244. get: function () {
  112245. return this._currentPriorityLevel;
  112246. },
  112247. enumerable: true,
  112248. configurable: true
  112249. });
  112250. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  112251. /**
  112252. * Gets the current frame rate checked by the SceneOptimizer
  112253. */
  112254. get: function () {
  112255. return this._currentFrameRate;
  112256. },
  112257. enumerable: true,
  112258. configurable: true
  112259. });
  112260. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  112261. /**
  112262. * Gets or sets the current target frame rate (60 by default)
  112263. */
  112264. get: function () {
  112265. return this._targetFrameRate;
  112266. },
  112267. /**
  112268. * Gets or sets the current target frame rate (60 by default)
  112269. */
  112270. set: function (value) {
  112271. this._targetFrameRate = value;
  112272. },
  112273. enumerable: true,
  112274. configurable: true
  112275. });
  112276. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  112277. /**
  112278. * Gets or sets the current interval between two checks (every 2000ms by default)
  112279. */
  112280. get: function () {
  112281. return this._trackerDuration;
  112282. },
  112283. /**
  112284. * Gets or sets the current interval between two checks (every 2000ms by default)
  112285. */
  112286. set: function (value) {
  112287. this._trackerDuration = value;
  112288. },
  112289. enumerable: true,
  112290. configurable: true
  112291. });
  112292. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  112293. /**
  112294. * Gets the list of active optimizations
  112295. */
  112296. get: function () {
  112297. return this._options.optimizations;
  112298. },
  112299. enumerable: true,
  112300. configurable: true
  112301. });
  112302. /**
  112303. * Stops the current optimizer
  112304. */
  112305. SceneOptimizer.prototype.stop = function () {
  112306. this._isRunning = false;
  112307. };
  112308. /**
  112309. * Reset the optimizer to initial step (current priority level = 0)
  112310. */
  112311. SceneOptimizer.prototype.reset = function () {
  112312. this._currentPriorityLevel = 0;
  112313. };
  112314. /**
  112315. * Start the optimizer. By default it will try to reach a specific framerate
  112316. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  112317. */
  112318. SceneOptimizer.prototype.start = function () {
  112319. var _this = this;
  112320. if (this._isRunning) {
  112321. return;
  112322. }
  112323. this._isRunning = true;
  112324. // Let's wait for the scene to be ready before running our check
  112325. this._scene.executeWhenReady(function () {
  112326. setTimeout(function () {
  112327. _this._checkCurrentState();
  112328. }, _this._trackerDuration);
  112329. });
  112330. };
  112331. SceneOptimizer.prototype._checkCurrentState = function () {
  112332. var _this = this;
  112333. if (!this._isRunning) {
  112334. return;
  112335. }
  112336. var scene = this._scene;
  112337. var options = this._options;
  112338. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  112339. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  112340. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  112341. this._isRunning = false;
  112342. this.onSuccessObservable.notifyObservers(this);
  112343. return;
  112344. }
  112345. // Apply current level of optimizations
  112346. var allDone = true;
  112347. var noOptimizationApplied = true;
  112348. for (var index = 0; index < options.optimizations.length; index++) {
  112349. var optimization = options.optimizations[index];
  112350. if (optimization.priority === this._currentPriorityLevel) {
  112351. noOptimizationApplied = false;
  112352. allDone = allDone && optimization.apply(scene, this);
  112353. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  112354. }
  112355. }
  112356. // If no optimization was applied, this is a failure :(
  112357. if (noOptimizationApplied) {
  112358. this._isRunning = false;
  112359. this.onFailureObservable.notifyObservers(this);
  112360. return;
  112361. }
  112362. // If all optimizations were done, move to next level
  112363. if (allDone) {
  112364. this._currentPriorityLevel++;
  112365. }
  112366. // Let's the system running for a specific amount of time before checking FPS
  112367. scene.executeWhenReady(function () {
  112368. setTimeout(function () {
  112369. _this._checkCurrentState();
  112370. }, _this._trackerDuration);
  112371. });
  112372. };
  112373. /**
  112374. * Release all resources
  112375. */
  112376. SceneOptimizer.prototype.dispose = function () {
  112377. this.stop();
  112378. this.onSuccessObservable.clear();
  112379. this.onFailureObservable.clear();
  112380. this.onNewOptimizationAppliedObservable.clear();
  112381. if (this._sceneDisposeObserver) {
  112382. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  112383. }
  112384. };
  112385. /**
  112386. * Helper function to create a SceneOptimizer with one single line of code
  112387. * @param scene defines the scene to work on
  112388. * @param options defines the options to use with the SceneOptimizer
  112389. * @param onSuccess defines a callback to call on success
  112390. * @param onFailure defines a callback to call on failure
  112391. * @returns the new SceneOptimizer object
  112392. */
  112393. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  112394. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  112395. if (onSuccess) {
  112396. optimizer.onSuccessObservable.add(function () {
  112397. onSuccess();
  112398. });
  112399. }
  112400. if (onFailure) {
  112401. optimizer.onFailureObservable.add(function () {
  112402. onFailure();
  112403. });
  112404. }
  112405. optimizer.start();
  112406. return optimizer;
  112407. };
  112408. return SceneOptimizer;
  112409. }());
  112410. BABYLON.SceneOptimizer = SceneOptimizer;
  112411. })(BABYLON || (BABYLON = {}));
  112412. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  112413. var BABYLON;
  112414. (function (BABYLON) {
  112415. /**
  112416. * Gets the outline renderer associated with the scene
  112417. * @returns a OutlineRenderer
  112418. */
  112419. BABYLON.Scene.prototype.getOutlineRenderer = function () {
  112420. if (!this._outlineRenderer) {
  112421. this._outlineRenderer = new OutlineRenderer(this);
  112422. }
  112423. return this._outlineRenderer;
  112424. };
  112425. Object.defineProperty(BABYLON.AbstractMesh.prototype, "renderOutline", {
  112426. get: function () {
  112427. return this._renderOutline;
  112428. },
  112429. set: function (value) {
  112430. if (value) {
  112431. // Lazy Load the component.
  112432. this.getScene().getOutlineRenderer();
  112433. }
  112434. this._renderOutline = value;
  112435. },
  112436. enumerable: true,
  112437. configurable: true
  112438. });
  112439. Object.defineProperty(BABYLON.AbstractMesh.prototype, "renderOverlay", {
  112440. get: function () {
  112441. return this._renderOverlay;
  112442. },
  112443. set: function (value) {
  112444. if (value) {
  112445. // Lazy Load the component.
  112446. this.getScene().getOutlineRenderer();
  112447. }
  112448. this._renderOverlay = value;
  112449. },
  112450. enumerable: true,
  112451. configurable: true
  112452. });
  112453. /**
  112454. * This class is responsible to draw bothe outline/overlay of meshes.
  112455. * It should not be used directly but through the available method on mesh.
  112456. */
  112457. var OutlineRenderer = /** @class */ (function () {
  112458. /**
  112459. * Instantiates a new outline renderer. (There could be only one per scene).
  112460. * @param scene Defines the scene it belongs to
  112461. */
  112462. function OutlineRenderer(scene) {
  112463. /**
  112464. * The name of the component. Each component must have a unique name.
  112465. */
  112466. this.name = BABYLON.SceneComponentConstants.NAME_OUTLINERENDERER;
  112467. /**
  112468. * Defines a zOffset to prevent zFighting between the overlay and the mesh.
  112469. */
  112470. this.zOffset = 1;
  112471. this.scene = scene;
  112472. this._engine = scene.getEngine();
  112473. this.scene._addComponent(this);
  112474. }
  112475. /**
  112476. * Register the component to one instance of a scene.
  112477. */
  112478. OutlineRenderer.prototype.register = function () {
  112479. this.scene._beforeRenderingMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORERENDERINGMESH_OUTLINE, this, this._beforeRenderingMesh);
  112480. this.scene._afterRenderingMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGMESH_OUTLINE, this, this._afterRenderingMesh);
  112481. };
  112482. /**
  112483. * Rebuilds the elements related to this component in case of
  112484. * context lost for instance.
  112485. */
  112486. OutlineRenderer.prototype.rebuild = function () {
  112487. // Nothing to do here.
  112488. };
  112489. /**
  112490. * Disposes the component and the associated ressources.
  112491. */
  112492. OutlineRenderer.prototype.dispose = function () {
  112493. // Nothing to do here.
  112494. };
  112495. /**
  112496. * Renders the outline in the canvas.
  112497. * @param subMesh Defines the sumesh to render
  112498. * @param batch Defines the batch of meshes in case of instances
  112499. * @param useOverlay Defines if the rendering is for the overlay or the outline
  112500. */
  112501. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  112502. var _this = this;
  112503. if (useOverlay === void 0) { useOverlay = false; }
  112504. var scene = this.scene;
  112505. var engine = scene.getEngine();
  112506. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  112507. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  112508. return;
  112509. }
  112510. var mesh = subMesh.getRenderingMesh();
  112511. var material = subMesh.getMaterial();
  112512. if (!material || !scene.activeCamera) {
  112513. return;
  112514. }
  112515. engine.enableEffect(this._effect);
  112516. // Logarithmic depth
  112517. if (material.useLogarithmicDepth) {
  112518. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  112519. }
  112520. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  112521. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  112522. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  112523. // Bones
  112524. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  112525. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  112526. }
  112527. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  112528. // Alpha test
  112529. if (material && material.needAlphaTesting()) {
  112530. var alphaTexture = material.getAlphaTestTexture();
  112531. if (alphaTexture) {
  112532. this._effect.setTexture("diffuseSampler", alphaTexture);
  112533. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  112534. }
  112535. }
  112536. engine.setZOffset(-this.zOffset);
  112537. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  112538. engine.setZOffset(0);
  112539. };
  112540. /**
  112541. * Returns whether or not the outline renderer is ready for a given submesh.
  112542. * All the dependencies e.g. submeshes, texture, effect... mus be ready
  112543. * @param subMesh Defines the submesh to check readyness for
  112544. * @param useInstances Defines wheter wee are trying to render instances or not
  112545. * @returns true if ready otherwise false
  112546. */
  112547. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  112548. var defines = [];
  112549. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  112550. var mesh = subMesh.getMesh();
  112551. var material = subMesh.getMaterial();
  112552. if (material) {
  112553. // Alpha test
  112554. if (material.needAlphaTesting()) {
  112555. defines.push("#define ALPHATEST");
  112556. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  112557. attribs.push(BABYLON.VertexBuffer.UVKind);
  112558. defines.push("#define UV1");
  112559. }
  112560. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  112561. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  112562. defines.push("#define UV2");
  112563. }
  112564. }
  112565. //Logarithmic depth
  112566. if (material.useLogarithmicDepth) {
  112567. defines.push("#define LOGARITHMICDEPTH");
  112568. }
  112569. }
  112570. // Bones
  112571. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  112572. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  112573. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  112574. if (mesh.numBoneInfluencers > 4) {
  112575. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  112576. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  112577. }
  112578. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  112579. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  112580. }
  112581. else {
  112582. defines.push("#define NUM_BONE_INFLUENCERS 0");
  112583. }
  112584. // Instances
  112585. if (useInstances) {
  112586. defines.push("#define INSTANCES");
  112587. attribs.push("world0");
  112588. attribs.push("world1");
  112589. attribs.push("world2");
  112590. attribs.push("world3");
  112591. }
  112592. // Get correct effect
  112593. var join = defines.join("\n");
  112594. if (this._cachedDefines !== join) {
  112595. this._cachedDefines = join;
  112596. this._effect = this.scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  112597. }
  112598. return this._effect.isReady();
  112599. };
  112600. OutlineRenderer.prototype._beforeRenderingMesh = function (mesh, subMesh, batch) {
  112601. // Outline - step 1
  112602. this._savedDepthWrite = this._engine.getDepthWrite();
  112603. if (mesh.renderOutline) {
  112604. this._engine.setDepthWrite(false);
  112605. this.render(subMesh, batch);
  112606. this._engine.setDepthWrite(this._savedDepthWrite);
  112607. }
  112608. };
  112609. OutlineRenderer.prototype._afterRenderingMesh = function (mesh, subMesh, batch) {
  112610. // Outline - step 2
  112611. if (mesh.renderOutline && this._savedDepthWrite) {
  112612. this._engine.setDepthWrite(true);
  112613. this._engine.setColorWrite(false);
  112614. this.render(subMesh, batch);
  112615. this._engine.setColorWrite(true);
  112616. }
  112617. // Overlay
  112618. if (mesh.renderOverlay) {
  112619. var currentMode = this._engine.getAlphaMode();
  112620. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  112621. this.render(subMesh, batch, true);
  112622. this._engine.setAlphaMode(currentMode);
  112623. }
  112624. };
  112625. return OutlineRenderer;
  112626. }());
  112627. BABYLON.OutlineRenderer = OutlineRenderer;
  112628. })(BABYLON || (BABYLON = {}));
  112629. //# sourceMappingURL=babylon.outlineRenderer.js.map
  112630. var BABYLON;
  112631. (function (BABYLON) {
  112632. BABYLON.AbstractMesh.prototype.disableEdgesRendering = function () {
  112633. if (this._edgesRenderer) {
  112634. this._edgesRenderer.dispose();
  112635. this._edgesRenderer = null;
  112636. }
  112637. return this;
  112638. };
  112639. BABYLON.AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  112640. if (epsilon === void 0) { epsilon = 0.95; }
  112641. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  112642. this.disableEdgesRendering();
  112643. this._edgesRenderer = new EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  112644. return this;
  112645. };
  112646. Object.defineProperty(BABYLON.AbstractMesh.prototype, "edgesRenderer", {
  112647. get: function () {
  112648. return this._edgesRenderer;
  112649. },
  112650. enumerable: true,
  112651. configurable: true
  112652. });
  112653. BABYLON.LinesMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  112654. if (epsilon === void 0) { epsilon = 0.95; }
  112655. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  112656. this.disableEdgesRendering();
  112657. this._edgesRenderer = new BABYLON.LineEdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  112658. return this;
  112659. };
  112660. BABYLON.InstancedLinesMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  112661. if (epsilon === void 0) { epsilon = 0.95; }
  112662. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  112663. BABYLON.LinesMesh.prototype.enableEdgesRendering.apply(this, arguments);
  112664. return this;
  112665. };
  112666. /**
  112667. * FaceAdjacencies Helper class to generate edges
  112668. */
  112669. var FaceAdjacencies = /** @class */ (function () {
  112670. function FaceAdjacencies() {
  112671. this.edges = new Array();
  112672. this.edgesConnectedCount = 0;
  112673. }
  112674. return FaceAdjacencies;
  112675. }());
  112676. /**
  112677. * This class is used to generate edges of the mesh that could then easily be rendered in a scene.
  112678. */
  112679. var EdgesRenderer = /** @class */ (function () {
  112680. /**
  112681. * Creates an instance of the EdgesRenderer. It is primarily use to display edges of a mesh.
  112682. * Beware when you use this class with complex objects as the adjacencies computation can be really long
  112683. * @param source Mesh used to create edges
  112684. * @param epsilon sum of angles in adjacency to check for edge
  112685. * @param checkVerticesInsteadOfIndices
  112686. * @param generateEdgesLines - should generate Lines or only prepare resources.
  112687. */
  112688. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices, generateEdgesLines) {
  112689. if (epsilon === void 0) { epsilon = 0.95; }
  112690. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  112691. if (generateEdgesLines === void 0) { generateEdgesLines = true; }
  112692. var _this = this;
  112693. /**
  112694. * Define the size of the edges with an orthographic camera
  112695. */
  112696. this.edgesWidthScalerForOrthographic = 1000.0;
  112697. /**
  112698. * Define the size of the edges with a perspective camera
  112699. */
  112700. this.edgesWidthScalerForPerspective = 50.0;
  112701. this._linesPositions = new Array();
  112702. this._linesNormals = new Array();
  112703. this._linesIndices = new Array();
  112704. this._buffers = {};
  112705. this._checkVerticesInsteadOfIndices = false;
  112706. /** Gets or sets a boolean indicating if the edgesRenderer is active */
  112707. this.isEnabled = true;
  112708. this._source = source;
  112709. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  112710. this._epsilon = epsilon;
  112711. this._prepareRessources();
  112712. if (generateEdgesLines) {
  112713. this._generateEdgesLines();
  112714. }
  112715. this._meshRebuildObserver = this._source.onRebuildObservable.add(function () {
  112716. _this._rebuild();
  112717. });
  112718. this._meshDisposeObserver = this._source.onDisposeObservable.add(function () {
  112719. _this.dispose();
  112720. });
  112721. }
  112722. EdgesRenderer.prototype._prepareRessources = function () {
  112723. if (this._lineShader) {
  112724. return;
  112725. }
  112726. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  112727. attributes: ["position", "normal"],
  112728. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  112729. });
  112730. this._lineShader.disableDepthWrite = true;
  112731. this._lineShader.backFaceCulling = false;
  112732. };
  112733. /** @hidden */
  112734. EdgesRenderer.prototype._rebuild = function () {
  112735. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  112736. if (buffer) {
  112737. buffer._rebuild();
  112738. }
  112739. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  112740. if (buffer) {
  112741. buffer._rebuild();
  112742. }
  112743. var scene = this._source.getScene();
  112744. var engine = scene.getEngine();
  112745. this._ib = engine.createIndexBuffer(this._linesIndices);
  112746. };
  112747. /**
  112748. * Releases the required resources for the edges renderer
  112749. */
  112750. EdgesRenderer.prototype.dispose = function () {
  112751. this._source.onRebuildObservable.remove(this._meshRebuildObserver);
  112752. this._source.onDisposeObservable.remove(this._meshDisposeObserver);
  112753. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  112754. if (buffer) {
  112755. buffer.dispose();
  112756. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  112757. }
  112758. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  112759. if (buffer) {
  112760. buffer.dispose();
  112761. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  112762. }
  112763. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  112764. this._lineShader.dispose();
  112765. };
  112766. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  112767. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  112768. return 0;
  112769. }
  112770. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  112771. return 1;
  112772. }
  112773. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  112774. return 2;
  112775. }
  112776. return -1;
  112777. };
  112778. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  112779. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  112780. return 0;
  112781. }
  112782. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  112783. return 1;
  112784. }
  112785. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  112786. return 2;
  112787. }
  112788. return -1;
  112789. };
  112790. /**
  112791. * Checks if the pair of p0 and p1 is en edge
  112792. * @param faceIndex
  112793. * @param edge
  112794. * @param faceNormals
  112795. * @param p0
  112796. * @param p1
  112797. * @private
  112798. */
  112799. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  112800. var needToCreateLine;
  112801. if (edge === undefined) {
  112802. needToCreateLine = true;
  112803. }
  112804. else {
  112805. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  112806. needToCreateLine = dotProduct < this._epsilon;
  112807. }
  112808. if (needToCreateLine) {
  112809. this.createLine(p0, p1, this._linesPositions.length / 3);
  112810. }
  112811. };
  112812. /**
  112813. * push line into the position, normal and index buffer
  112814. * @protected
  112815. */
  112816. EdgesRenderer.prototype.createLine = function (p0, p1, offset) {
  112817. // Positions
  112818. this._linesPositions.push(p0.x, p0.y, p0.z, p0.x, p0.y, p0.z, p1.x, p1.y, p1.z, p1.x, p1.y, p1.z);
  112819. // Normals
  112820. this._linesNormals.push(p1.x, p1.y, p1.z, -1, p1.x, p1.y, p1.z, 1, p0.x, p0.y, p0.z, -1, p0.x, p0.y, p0.z, 1);
  112821. // Indices
  112822. this._linesIndices.push(offset, offset + 1, offset + 2, offset, offset + 2, offset + 3);
  112823. };
  112824. /**
  112825. * Generates lines edges from adjacencjes
  112826. * @private
  112827. */
  112828. EdgesRenderer.prototype._generateEdgesLines = function () {
  112829. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  112830. var indices = this._source.getIndices();
  112831. if (!indices || !positions) {
  112832. return;
  112833. }
  112834. // First let's find adjacencies
  112835. var adjacencies = new Array();
  112836. var faceNormals = new Array();
  112837. var index;
  112838. var faceAdjacencies;
  112839. // Prepare faces
  112840. for (index = 0; index < indices.length; index += 3) {
  112841. faceAdjacencies = new FaceAdjacencies();
  112842. var p0Index = indices[index];
  112843. var p1Index = indices[index + 1];
  112844. var p2Index = indices[index + 2];
  112845. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  112846. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  112847. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  112848. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  112849. faceNormal.normalize();
  112850. faceNormals.push(faceNormal);
  112851. adjacencies.push(faceAdjacencies);
  112852. }
  112853. // Scan
  112854. for (index = 0; index < adjacencies.length; index++) {
  112855. faceAdjacencies = adjacencies[index];
  112856. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  112857. var otherFaceAdjacencies = adjacencies[otherIndex];
  112858. if (faceAdjacencies.edgesConnectedCount === 3) { // Full
  112859. break;
  112860. }
  112861. if (otherFaceAdjacencies.edgesConnectedCount === 3) { // Full
  112862. continue;
  112863. }
  112864. var otherP0 = indices[otherIndex * 3];
  112865. var otherP1 = indices[otherIndex * 3 + 1];
  112866. var otherP2 = indices[otherIndex * 3 + 2];
  112867. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  112868. var otherEdgeIndex = 0;
  112869. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  112870. continue;
  112871. }
  112872. switch (edgeIndex) {
  112873. case 0:
  112874. if (this._checkVerticesInsteadOfIndices) {
  112875. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  112876. }
  112877. else {
  112878. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  112879. }
  112880. break;
  112881. case 1:
  112882. if (this._checkVerticesInsteadOfIndices) {
  112883. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  112884. }
  112885. else {
  112886. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  112887. }
  112888. break;
  112889. case 2:
  112890. if (this._checkVerticesInsteadOfIndices) {
  112891. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  112892. }
  112893. else {
  112894. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  112895. }
  112896. break;
  112897. }
  112898. if (otherEdgeIndex === -1) {
  112899. continue;
  112900. }
  112901. faceAdjacencies.edges[edgeIndex] = otherIndex;
  112902. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  112903. faceAdjacencies.edgesConnectedCount++;
  112904. otherFaceAdjacencies.edgesConnectedCount++;
  112905. if (faceAdjacencies.edgesConnectedCount === 3) {
  112906. break;
  112907. }
  112908. }
  112909. }
  112910. }
  112911. // Create lines
  112912. for (index = 0; index < adjacencies.length; index++) {
  112913. // 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
  112914. var current = adjacencies[index];
  112915. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  112916. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  112917. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  112918. }
  112919. // Merge into a single mesh
  112920. var engine = this._source.getScene().getEngine();
  112921. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  112922. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  112923. this._ib = engine.createIndexBuffer(this._linesIndices);
  112924. this._indicesCount = this._linesIndices.length;
  112925. };
  112926. /**
  112927. * Checks wether or not the edges renderer is ready to render.
  112928. * @return true if ready, otherwise false.
  112929. */
  112930. EdgesRenderer.prototype.isReady = function () {
  112931. return this._lineShader.isReady();
  112932. };
  112933. /**
  112934. * Renders the edges of the attached mesh,
  112935. */
  112936. EdgesRenderer.prototype.render = function () {
  112937. var scene = this._source.getScene();
  112938. if (!this.isReady() || !scene.activeCamera) {
  112939. return;
  112940. }
  112941. var engine = scene.getEngine();
  112942. this._lineShader._preBind();
  112943. if (this._source.edgesColor.a !== 1) {
  112944. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  112945. }
  112946. else {
  112947. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  112948. }
  112949. // VBOs
  112950. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  112951. scene.resetCachedMaterial();
  112952. this._lineShader.setColor4("color", this._source.edgesColor);
  112953. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  112954. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  112955. }
  112956. else {
  112957. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  112958. }
  112959. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  112960. this._lineShader.bind(this._source.getWorldMatrix());
  112961. // Draw order
  112962. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  112963. this._lineShader.unbind();
  112964. };
  112965. return EdgesRenderer;
  112966. }());
  112967. BABYLON.EdgesRenderer = EdgesRenderer;
  112968. })(BABYLON || (BABYLON = {}));
  112969. //# sourceMappingURL=babylon.edgesRenderer.js.map
  112970. var BABYLON;
  112971. (function (BABYLON) {
  112972. /**
  112973. * LineEdgesRenderer for LineMeshes to remove unnecessary triangulation
  112974. */
  112975. var LineEdgesRenderer = /** @class */ (function (_super) {
  112976. __extends(LineEdgesRenderer, _super);
  112977. /**
  112978. * This constructor turns off auto generating edges line in Edges Renderer to make it here.
  112979. * @param source LineMesh used to generate edges
  112980. * @param epsilon not important (specified angle for edge detection)
  112981. * @param checkVerticesInsteadOfIndices not important for LineMesh
  112982. */
  112983. function LineEdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  112984. if (epsilon === void 0) { epsilon = 0.95; }
  112985. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  112986. var _this = _super.call(this, source, epsilon, checkVerticesInsteadOfIndices, false) || this;
  112987. _this._generateEdgesLines();
  112988. return _this;
  112989. }
  112990. /**
  112991. * Generate edges for each line in LinesMesh. Every Line should be rendered as edge.
  112992. */
  112993. LineEdgesRenderer.prototype._generateEdgesLines = function () {
  112994. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  112995. var indices = this._source.getIndices();
  112996. if (!indices || !positions) {
  112997. return;
  112998. }
  112999. var p0 = BABYLON.Tmp.Vector3[0];
  113000. var p1 = BABYLON.Tmp.Vector3[1];
  113001. var len = indices.length - 1;
  113002. for (var i = 0, offset = 0; i < len; i += 2, offset += 4) {
  113003. BABYLON.Vector3.FromArrayToRef(positions, 3 * indices[i], p0);
  113004. BABYLON.Vector3.FromArrayToRef(positions, 3 * indices[i + 1], p1);
  113005. this.createLine(p0, p1, offset);
  113006. }
  113007. // Merge into a single mesh
  113008. var engine = this._source.getScene().getEngine();
  113009. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  113010. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  113011. this._ib = engine.createIndexBuffer(this._linesIndices);
  113012. this._indicesCount = this._linesIndices.length;
  113013. };
  113014. return LineEdgesRenderer;
  113015. }(BABYLON.EdgesRenderer));
  113016. BABYLON.LineEdgesRenderer = LineEdgesRenderer;
  113017. })(BABYLON || (BABYLON = {}));
  113018. //# sourceMappingURL=babylon.lineEdgesRenderer.js.map
  113019. var BABYLON;
  113020. (function (BABYLON) {
  113021. // Adds the parser to the scene parsers.
  113022. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER, function (parsedData, scene, container, rootUrl) {
  113023. if (parsedData.effectLayers) {
  113024. if (!container.effectLayers) {
  113025. container.effectLayers = new Array();
  113026. }
  113027. for (var index = 0; index < parsedData.effectLayers.length; index++) {
  113028. var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
  113029. container.effectLayers.push(effectLayer);
  113030. }
  113031. }
  113032. });
  113033. BABYLON.AbstractScene.prototype.removeEffectLayer = function (toRemove) {
  113034. var index = this.effectLayers.indexOf(toRemove);
  113035. if (index !== -1) {
  113036. this.effectLayers.splice(index, 1);
  113037. }
  113038. return index;
  113039. };
  113040. BABYLON.AbstractScene.prototype.addEffectLayer = function (newEffectLayer) {
  113041. this.effectLayers.push(newEffectLayer);
  113042. };
  113043. /**
  113044. * Defines the layer scene component responsible to manage any effect layers
  113045. * in a given scene.
  113046. */
  113047. var EffectLayerSceneComponent = /** @class */ (function () {
  113048. /**
  113049. * Creates a new instance of the component for the given scene
  113050. * @param scene Defines the scene to register the component in
  113051. */
  113052. function EffectLayerSceneComponent(scene) {
  113053. /**
  113054. * The component name helpfull to identify the component in the list of scene components.
  113055. */
  113056. this.name = BABYLON.SceneComponentConstants.NAME_EFFECTLAYER;
  113057. this._renderEffects = false;
  113058. this._needStencil = false;
  113059. this._previousStencilState = false;
  113060. this.scene = scene;
  113061. this._engine = scene.getEngine();
  113062. scene.effectLayers = new Array();
  113063. }
  113064. /**
  113065. * Registers the component in a given scene
  113066. */
  113067. EffectLayerSceneComponent.prototype.register = function () {
  113068. this.scene._isReadyForMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER, this, this._isReadyForMesh);
  113069. this.scene._cameraDrawRenderTargetStage.registerStep(BABYLON.SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER, this, this._renderMainTexture);
  113070. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER, this, this._setStencil);
  113071. this.scene._afterRenderingGroupDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW, this, this._drawRenderingGroup);
  113072. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER, this, this._setStencilBack);
  113073. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW, this, this._drawCamera);
  113074. };
  113075. /**
  113076. * Rebuilds the elements related to this component in case of
  113077. * context lost for instance.
  113078. */
  113079. EffectLayerSceneComponent.prototype.rebuild = function () {
  113080. var layers = this.scene.effectLayers;
  113081. for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
  113082. var effectLayer = layers_1[_i];
  113083. effectLayer._rebuild();
  113084. }
  113085. };
  113086. /**
  113087. * Serializes the component data to the specified json object
  113088. * @param serializationObject The object to serialize to
  113089. */
  113090. EffectLayerSceneComponent.prototype.serialize = function (serializationObject) {
  113091. // Effect layers
  113092. serializationObject.effectLayers = [];
  113093. var layers = this.scene.effectLayers;
  113094. for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
  113095. var effectLayer = layers_2[_i];
  113096. if (effectLayer.serialize) {
  113097. serializationObject.effectLayers.push(effectLayer.serialize());
  113098. }
  113099. }
  113100. };
  113101. /**
  113102. * Adds all the element from the container to the scene
  113103. * @param container the container holding the elements
  113104. */
  113105. EffectLayerSceneComponent.prototype.addFromContainer = function (container) {
  113106. var _this = this;
  113107. if (!container.effectLayers) {
  113108. return;
  113109. }
  113110. container.effectLayers.forEach(function (o) {
  113111. _this.scene.addEffectLayer(o);
  113112. });
  113113. };
  113114. /**
  113115. * Removes all the elements in the container from the scene
  113116. * @param container contains the elements to remove
  113117. */
  113118. EffectLayerSceneComponent.prototype.removeFromContainer = function (container) {
  113119. var _this = this;
  113120. if (!container.effectLayers) {
  113121. return;
  113122. }
  113123. container.effectLayers.forEach(function (o) {
  113124. _this.scene.removeEffectLayer(o);
  113125. });
  113126. };
  113127. /**
  113128. * Disposes the component and the associated ressources.
  113129. */
  113130. EffectLayerSceneComponent.prototype.dispose = function () {
  113131. var layers = this.scene.effectLayers;
  113132. while (layers.length) {
  113133. layers[0].dispose();
  113134. }
  113135. };
  113136. EffectLayerSceneComponent.prototype._isReadyForMesh = function (mesh, hardwareInstancedRendering) {
  113137. var layers = this.scene.effectLayers;
  113138. for (var _i = 0, layers_3 = layers; _i < layers_3.length; _i++) {
  113139. var layer = layers_3[_i];
  113140. if (!layer.hasMesh(mesh)) {
  113141. continue;
  113142. }
  113143. for (var _a = 0, _b = mesh.subMeshes; _a < _b.length; _a++) {
  113144. var subMesh = _b[_a];
  113145. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  113146. return false;
  113147. }
  113148. }
  113149. }
  113150. return true;
  113151. };
  113152. EffectLayerSceneComponent.prototype._renderMainTexture = function (camera) {
  113153. this._renderEffects = false;
  113154. this._needStencil = false;
  113155. var layers = this.scene.effectLayers;
  113156. if (layers && layers.length > 0) {
  113157. this._previousStencilState = this._engine.getStencilBuffer();
  113158. for (var _i = 0, layers_4 = layers; _i < layers_4.length; _i++) {
  113159. var effectLayer = layers_4[_i];
  113160. if (effectLayer.shouldRender() &&
  113161. (!effectLayer.camera ||
  113162. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  113163. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  113164. this._renderEffects = true;
  113165. this._needStencil = this._needStencil || effectLayer.needStencil();
  113166. var renderTarget = effectLayer._mainTexture;
  113167. if (renderTarget._shouldRender()) {
  113168. this.scene.incrementRenderId();
  113169. renderTarget.render(false, false);
  113170. }
  113171. }
  113172. }
  113173. this.scene.incrementRenderId();
  113174. }
  113175. };
  113176. EffectLayerSceneComponent.prototype._setStencil = function (camera) {
  113177. // Activate effect Layer stencil
  113178. if (this._needStencil) {
  113179. this._engine.setStencilBuffer(true);
  113180. }
  113181. };
  113182. EffectLayerSceneComponent.prototype._setStencilBack = function (camera) {
  113183. // Restore effect Layer stencil
  113184. if (this._needStencil) {
  113185. this._engine.setStencilBuffer(this._previousStencilState);
  113186. }
  113187. };
  113188. EffectLayerSceneComponent.prototype._draw = function (renderingGroupId) {
  113189. if (this._renderEffects) {
  113190. this._engine.setDepthBuffer(false);
  113191. var layers = this.scene.effectLayers;
  113192. for (var i = 0; i < layers.length; i++) {
  113193. var effectLayer = layers[i];
  113194. if (effectLayer.renderingGroupId === renderingGroupId) {
  113195. if (effectLayer.shouldRender()) {
  113196. effectLayer.render();
  113197. }
  113198. }
  113199. }
  113200. this._engine.setDepthBuffer(true);
  113201. }
  113202. };
  113203. EffectLayerSceneComponent.prototype._drawCamera = function (camera) {
  113204. if (this._renderEffects) {
  113205. this._draw(-1);
  113206. }
  113207. };
  113208. EffectLayerSceneComponent.prototype._drawRenderingGroup = function (index) {
  113209. if (!this.scene._isInIntermediateRendering() && this._renderEffects) {
  113210. this._draw(index);
  113211. }
  113212. };
  113213. return EffectLayerSceneComponent;
  113214. }());
  113215. BABYLON.EffectLayerSceneComponent = EffectLayerSceneComponent;
  113216. })(BABYLON || (BABYLON = {}));
  113217. //# sourceMappingURL=babylon.effectLayerSceneComponent.js.map
  113218. var __assign = (this && this.__assign) || function () {
  113219. __assign = Object.assign || function(t) {
  113220. for (var s, i = 1, n = arguments.length; i < n; i++) {
  113221. s = arguments[i];
  113222. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  113223. t[p] = s[p];
  113224. }
  113225. return t;
  113226. };
  113227. return __assign.apply(this, arguments);
  113228. };
  113229. var BABYLON;
  113230. (function (BABYLON) {
  113231. /**
  113232. * The effect layer Helps adding post process effect blended with the main pass.
  113233. *
  113234. * This can be for instance use to generate glow or higlight effects on the scene.
  113235. *
  113236. * The effect layer class can not be used directly and is intented to inherited from to be
  113237. * customized per effects.
  113238. */
  113239. var EffectLayer = /** @class */ (function () {
  113240. /**
  113241. * Instantiates a new effect Layer and references it in the scene.
  113242. * @param name The name of the layer
  113243. * @param scene The scene to use the layer in
  113244. */
  113245. function EffectLayer(
  113246. /** The Friendly of the effect in the scene */
  113247. name, scene) {
  113248. this._vertexBuffers = {};
  113249. this._maxSize = 0;
  113250. this._mainTextureDesiredSize = { width: 0, height: 0 };
  113251. this._shouldRender = true;
  113252. this._postProcesses = [];
  113253. this._textures = [];
  113254. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  113255. /**
  113256. * The clear color of the texture used to generate the glow map.
  113257. */
  113258. this.neutralColor = new BABYLON.Color4();
  113259. /**
  113260. * Specifies wether the highlight layer is enabled or not.
  113261. */
  113262. this.isEnabled = true;
  113263. /**
  113264. * An event triggered when the effect layer has been disposed.
  113265. */
  113266. this.onDisposeObservable = new BABYLON.Observable();
  113267. /**
  113268. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  113269. */
  113270. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  113271. /**
  113272. * An event triggered when the generated texture is being merged in the scene.
  113273. */
  113274. this.onBeforeComposeObservable = new BABYLON.Observable();
  113275. /**
  113276. * An event triggered when the generated texture has been merged in the scene.
  113277. */
  113278. this.onAfterComposeObservable = new BABYLON.Observable();
  113279. /**
  113280. * An event triggered when the efffect layer changes its size.
  113281. */
  113282. this.onSizeChangedObservable = new BABYLON.Observable();
  113283. this.name = name;
  113284. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  113285. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER);
  113286. if (!component) {
  113287. component = new BABYLON.EffectLayerSceneComponent(this._scene);
  113288. this._scene._addComponent(component);
  113289. }
  113290. this._engine = this._scene.getEngine();
  113291. this._maxSize = this._engine.getCaps().maxTextureSize;
  113292. this._scene.effectLayers.push(this);
  113293. // Generate Buffers
  113294. this._generateIndexBuffer();
  113295. this._genrateVertexBuffer();
  113296. }
  113297. Object.defineProperty(EffectLayer.prototype, "camera", {
  113298. /**
  113299. * Gets the camera attached to the layer.
  113300. */
  113301. get: function () {
  113302. return this._effectLayerOptions.camera;
  113303. },
  113304. enumerable: true,
  113305. configurable: true
  113306. });
  113307. Object.defineProperty(EffectLayer.prototype, "renderingGroupId", {
  113308. /**
  113309. * Gets the rendering group id the layer should render in.
  113310. */
  113311. get: function () {
  113312. return this._effectLayerOptions.renderingGroupId;
  113313. },
  113314. enumerable: true,
  113315. configurable: true
  113316. });
  113317. /**
  113318. * Initializes the effect layer with the required options.
  113319. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  113320. */
  113321. EffectLayer.prototype._init = function (options) {
  113322. // Adapt options
  113323. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null, renderingGroupId: -1 }, options);
  113324. this._setMainTextureSize();
  113325. this._createMainTexture();
  113326. this._createTextureAndPostProcesses();
  113327. this._mergeEffect = this._createMergeEffect();
  113328. };
  113329. /**
  113330. * Generates the index buffer of the full screen quad blending to the main canvas.
  113331. */
  113332. EffectLayer.prototype._generateIndexBuffer = function () {
  113333. // Indices
  113334. var indices = [];
  113335. indices.push(0);
  113336. indices.push(1);
  113337. indices.push(2);
  113338. indices.push(0);
  113339. indices.push(2);
  113340. indices.push(3);
  113341. this._indexBuffer = this._engine.createIndexBuffer(indices);
  113342. };
  113343. /**
  113344. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  113345. */
  113346. EffectLayer.prototype._genrateVertexBuffer = function () {
  113347. // VBO
  113348. var vertices = [];
  113349. vertices.push(1, 1);
  113350. vertices.push(-1, 1);
  113351. vertices.push(-1, -1);
  113352. vertices.push(1, -1);
  113353. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  113354. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  113355. };
  113356. /**
  113357. * Sets the main texture desired size which is the closest power of two
  113358. * of the engine canvas size.
  113359. */
  113360. EffectLayer.prototype._setMainTextureSize = function () {
  113361. if (this._effectLayerOptions.mainTextureFixedSize) {
  113362. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  113363. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  113364. }
  113365. else {
  113366. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  113367. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  113368. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  113369. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  113370. }
  113371. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  113372. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  113373. };
  113374. /**
  113375. * Creates the main texture for the effect layer.
  113376. */
  113377. EffectLayer.prototype._createMainTexture = function () {
  113378. var _this = this;
  113379. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  113380. width: this._mainTextureDesiredSize.width,
  113381. height: this._mainTextureDesiredSize.height
  113382. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  113383. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  113384. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  113385. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  113386. this._mainTexture.anisotropicFilteringLevel = 1;
  113387. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  113388. this._mainTexture.renderParticles = false;
  113389. this._mainTexture.renderList = null;
  113390. this._mainTexture.ignoreCameraViewport = true;
  113391. // Custom render function
  113392. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  113393. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  113394. var index;
  113395. var engine = _this._scene.getEngine();
  113396. if (depthOnlySubMeshes.length) {
  113397. engine.setColorWrite(false);
  113398. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  113399. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  113400. }
  113401. engine.setColorWrite(true);
  113402. }
  113403. for (index = 0; index < opaqueSubMeshes.length; index++) {
  113404. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  113405. }
  113406. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  113407. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  113408. }
  113409. for (index = 0; index < transparentSubMeshes.length; index++) {
  113410. _this._renderSubMesh(transparentSubMeshes.data[index]);
  113411. }
  113412. };
  113413. this._mainTexture.onClearObservable.add(function (engine) {
  113414. engine.clear(_this.neutralColor, true, true, true);
  113415. });
  113416. };
  113417. /**
  113418. * Checks for the readiness of the element composing the layer.
  113419. * @param subMesh the mesh to check for
  113420. * @param useInstances specify wether or not to use instances to render the mesh
  113421. * @param emissiveTexture the associated emissive texture used to generate the glow
  113422. * @return true if ready otherwise, false
  113423. */
  113424. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  113425. var material = subMesh.getMaterial();
  113426. if (!material) {
  113427. return false;
  113428. }
  113429. if (!material.isReadyForSubMesh(subMesh.getMesh(), subMesh, useInstances)) {
  113430. return false;
  113431. }
  113432. var defines = [];
  113433. var attribs = [BABYLON.VertexBuffer.PositionKind];
  113434. var mesh = subMesh.getMesh();
  113435. var uv1 = false;
  113436. var uv2 = false;
  113437. // Alpha test
  113438. if (material && material.needAlphaTesting()) {
  113439. var alphaTexture = material.getAlphaTestTexture();
  113440. if (alphaTexture) {
  113441. defines.push("#define ALPHATEST");
  113442. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  113443. alphaTexture.coordinatesIndex === 1) {
  113444. defines.push("#define DIFFUSEUV2");
  113445. uv2 = true;
  113446. }
  113447. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  113448. defines.push("#define DIFFUSEUV1");
  113449. uv1 = true;
  113450. }
  113451. }
  113452. }
  113453. // Emissive
  113454. if (emissiveTexture) {
  113455. defines.push("#define EMISSIVE");
  113456. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  113457. emissiveTexture.coordinatesIndex === 1) {
  113458. defines.push("#define EMISSIVEUV2");
  113459. uv2 = true;
  113460. }
  113461. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  113462. defines.push("#define EMISSIVEUV1");
  113463. uv1 = true;
  113464. }
  113465. }
  113466. if (uv1) {
  113467. attribs.push(BABYLON.VertexBuffer.UVKind);
  113468. defines.push("#define UV1");
  113469. }
  113470. if (uv2) {
  113471. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  113472. defines.push("#define UV2");
  113473. }
  113474. // Bones
  113475. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  113476. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  113477. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  113478. if (mesh.numBoneInfluencers > 4) {
  113479. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  113480. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  113481. }
  113482. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  113483. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  113484. }
  113485. else {
  113486. defines.push("#define NUM_BONE_INFLUENCERS 0");
  113487. }
  113488. // Morph targets
  113489. var manager = mesh.morphTargetManager;
  113490. var morphInfluencers = 0;
  113491. if (manager) {
  113492. if (manager.numInfluencers > 0) {
  113493. defines.push("#define MORPHTARGETS");
  113494. morphInfluencers = manager.numInfluencers;
  113495. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  113496. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  113497. }
  113498. }
  113499. // Instances
  113500. if (useInstances) {
  113501. defines.push("#define INSTANCES");
  113502. attribs.push("world0");
  113503. attribs.push("world1");
  113504. attribs.push("world2");
  113505. attribs.push("world3");
  113506. }
  113507. // Get correct effect
  113508. var join = defines.join("\n");
  113509. if (this._cachedDefines !== join) {
  113510. this._cachedDefines = join;
  113511. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  113512. }
  113513. return this._effectLayerMapGenerationEffect.isReady();
  113514. };
  113515. /**
  113516. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  113517. */
  113518. EffectLayer.prototype.render = function () {
  113519. var currentEffect = this._mergeEffect;
  113520. // Check
  113521. if (!currentEffect.isReady()) {
  113522. return;
  113523. }
  113524. for (var i = 0; i < this._postProcesses.length; i++) {
  113525. if (!this._postProcesses[i].isReady()) {
  113526. return;
  113527. }
  113528. }
  113529. var engine = this._scene.getEngine();
  113530. this.onBeforeComposeObservable.notifyObservers(this);
  113531. // Render
  113532. engine.enableEffect(currentEffect);
  113533. engine.setState(false);
  113534. // VBOs
  113535. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  113536. // Cache
  113537. var previousAlphaMode = engine.getAlphaMode();
  113538. // Go Blend.
  113539. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  113540. // Blends the map on the main canvas.
  113541. this._internalRender(currentEffect);
  113542. // Restore Alpha
  113543. engine.setAlphaMode(previousAlphaMode);
  113544. this.onAfterComposeObservable.notifyObservers(this);
  113545. // Handle size changes.
  113546. var size = this._mainTexture.getSize();
  113547. this._setMainTextureSize();
  113548. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  113549. // Recreate RTT and post processes on size change.
  113550. this.onSizeChangedObservable.notifyObservers(this);
  113551. this._disposeTextureAndPostProcesses();
  113552. this._createMainTexture();
  113553. this._createTextureAndPostProcesses();
  113554. }
  113555. };
  113556. /**
  113557. * Determine if a given mesh will be used in the current effect.
  113558. * @param mesh mesh to test
  113559. * @returns true if the mesh will be used
  113560. */
  113561. EffectLayer.prototype.hasMesh = function (mesh) {
  113562. if (this.renderingGroupId === -1 || mesh.renderingGroupId === this.renderingGroupId) {
  113563. return true;
  113564. }
  113565. return false;
  113566. };
  113567. /**
  113568. * Returns true if the layer contains information to display, otherwise false.
  113569. * @returns true if the glow layer should be rendered
  113570. */
  113571. EffectLayer.prototype.shouldRender = function () {
  113572. return this.isEnabled && this._shouldRender;
  113573. };
  113574. /**
  113575. * Returns true if the mesh should render, otherwise false.
  113576. * @param mesh The mesh to render
  113577. * @returns true if it should render otherwise false
  113578. */
  113579. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  113580. return true;
  113581. };
  113582. /**
  113583. * Returns true if the mesh should render, otherwise false.
  113584. * @param mesh The mesh to render
  113585. * @returns true if it should render otherwise false
  113586. */
  113587. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  113588. return true;
  113589. };
  113590. /**
  113591. * Renders the submesh passed in parameter to the generation map.
  113592. */
  113593. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  113594. var _this = this;
  113595. if (!this.shouldRender()) {
  113596. return;
  113597. }
  113598. var material = subMesh.getMaterial();
  113599. var mesh = subMesh.getRenderingMesh();
  113600. var scene = this._scene;
  113601. var engine = scene.getEngine();
  113602. if (!material) {
  113603. return;
  113604. }
  113605. // Do not block in blend mode.
  113606. if (material.needAlphaBlendingForMesh(mesh)) {
  113607. return;
  113608. }
  113609. // Culling
  113610. engine.setState(material.backFaceCulling);
  113611. // Managing instances
  113612. var batch = mesh._getInstancesRenderList(subMesh._id);
  113613. if (batch.mustReturn) {
  113614. return;
  113615. }
  113616. // Early Exit per mesh
  113617. if (!this._shouldRenderMesh(mesh)) {
  113618. return;
  113619. }
  113620. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  113621. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  113622. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  113623. engine.enableEffect(this._effectLayerMapGenerationEffect);
  113624. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  113625. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  113626. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  113627. // Alpha test
  113628. if (material && material.needAlphaTesting()) {
  113629. var alphaTexture = material.getAlphaTestTexture();
  113630. if (alphaTexture) {
  113631. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  113632. var textureMatrix = alphaTexture.getTextureMatrix();
  113633. if (textureMatrix) {
  113634. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  113635. }
  113636. }
  113637. }
  113638. // Glow emissive only
  113639. if (this._emissiveTextureAndColor.texture) {
  113640. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  113641. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  113642. }
  113643. // Bones
  113644. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  113645. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  113646. }
  113647. // Morph targets
  113648. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  113649. // Draw
  113650. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  113651. }
  113652. else {
  113653. // Need to reset refresh rate of the main map
  113654. this._mainTexture.resetRefreshCounter();
  113655. }
  113656. };
  113657. /**
  113658. * Rebuild the required buffers.
  113659. * @hidden Internal use only.
  113660. */
  113661. EffectLayer.prototype._rebuild = function () {
  113662. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  113663. if (vb) {
  113664. vb._rebuild();
  113665. }
  113666. this._generateIndexBuffer();
  113667. };
  113668. /**
  113669. * Dispose only the render target textures and post process.
  113670. */
  113671. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  113672. this._mainTexture.dispose();
  113673. for (var i = 0; i < this._postProcesses.length; i++) {
  113674. if (this._postProcesses[i]) {
  113675. this._postProcesses[i].dispose();
  113676. }
  113677. }
  113678. this._postProcesses = [];
  113679. for (var i = 0; i < this._textures.length; i++) {
  113680. if (this._textures[i]) {
  113681. this._textures[i].dispose();
  113682. }
  113683. }
  113684. this._textures = [];
  113685. };
  113686. /**
  113687. * Dispose the highlight layer and free resources.
  113688. */
  113689. EffectLayer.prototype.dispose = function () {
  113690. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  113691. if (vertexBuffer) {
  113692. vertexBuffer.dispose();
  113693. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  113694. }
  113695. if (this._indexBuffer) {
  113696. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  113697. this._indexBuffer = null;
  113698. }
  113699. // Clean textures and post processes
  113700. this._disposeTextureAndPostProcesses();
  113701. // Remove from scene
  113702. var index = this._scene.effectLayers.indexOf(this, 0);
  113703. if (index > -1) {
  113704. this._scene.effectLayers.splice(index, 1);
  113705. }
  113706. // Callback
  113707. this.onDisposeObservable.notifyObservers(this);
  113708. this.onDisposeObservable.clear();
  113709. this.onBeforeRenderMainTextureObservable.clear();
  113710. this.onBeforeComposeObservable.clear();
  113711. this.onAfterComposeObservable.clear();
  113712. this.onSizeChangedObservable.clear();
  113713. };
  113714. /**
  113715. * Gets the class name of the effect layer
  113716. * @returns the string with the class name of the effect layer
  113717. */
  113718. EffectLayer.prototype.getClassName = function () {
  113719. return "EffectLayer";
  113720. };
  113721. /**
  113722. * Creates an effect layer from parsed effect layer data
  113723. * @param parsedEffectLayer defines effect layer data
  113724. * @param scene defines the current scene
  113725. * @param rootUrl defines the root URL containing the effect layer information
  113726. * @returns a parsed effect Layer
  113727. */
  113728. EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
  113729. var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);
  113730. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  113731. };
  113732. __decorate([
  113733. BABYLON.serialize()
  113734. ], EffectLayer.prototype, "name", void 0);
  113735. __decorate([
  113736. BABYLON.serializeAsColor4()
  113737. ], EffectLayer.prototype, "neutralColor", void 0);
  113738. __decorate([
  113739. BABYLON.serialize()
  113740. ], EffectLayer.prototype, "isEnabled", void 0);
  113741. __decorate([
  113742. BABYLON.serializeAsCameraReference()
  113743. ], EffectLayer.prototype, "camera", null);
  113744. __decorate([
  113745. BABYLON.serialize()
  113746. ], EffectLayer.prototype, "renderingGroupId", null);
  113747. return EffectLayer;
  113748. }());
  113749. BABYLON.EffectLayer = EffectLayer;
  113750. })(BABYLON || (BABYLON = {}));
  113751. //# sourceMappingURL=babylon.effectLayer.js.map
  113752. var BABYLON;
  113753. (function (BABYLON) {
  113754. BABYLON.AbstractScene.prototype.getHighlightLayerByName = function (name) {
  113755. for (var index = 0; index < this.effectLayers.length; index++) {
  113756. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === HighlightLayer.EffectName) {
  113757. return this.effectLayers[index];
  113758. }
  113759. }
  113760. return null;
  113761. };
  113762. /**
  113763. * Special Glow Blur post process only blurring the alpha channel
  113764. * It enforces keeping the most luminous color in the color channel.
  113765. */
  113766. var GlowBlurPostProcess = /** @class */ (function (_super) {
  113767. __extends(GlowBlurPostProcess, _super);
  113768. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  113769. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  113770. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  113771. _this.direction = direction;
  113772. _this.kernel = kernel;
  113773. _this.onApplyObservable.add(function (effect) {
  113774. effect.setFloat2("screenSize", _this.width, _this.height);
  113775. effect.setVector2("direction", _this.direction);
  113776. effect.setFloat("blurWidth", _this.kernel);
  113777. });
  113778. return _this;
  113779. }
  113780. return GlowBlurPostProcess;
  113781. }(BABYLON.PostProcess));
  113782. /**
  113783. * The highlight layer Helps adding a glow effect around a mesh.
  113784. *
  113785. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  113786. * glowy meshes to your scene.
  113787. *
  113788. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  113789. */
  113790. var HighlightLayer = /** @class */ (function (_super) {
  113791. __extends(HighlightLayer, _super);
  113792. /**
  113793. * Instantiates a new highlight Layer and references it to the scene..
  113794. * @param name The name of the layer
  113795. * @param scene The scene to use the layer in
  113796. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  113797. */
  113798. function HighlightLayer(name, scene, options) {
  113799. var _this = _super.call(this, name, scene) || this;
  113800. _this.name = name;
  113801. /**
  113802. * Specifies whether or not the inner glow is ACTIVE in the layer.
  113803. */
  113804. _this.innerGlow = true;
  113805. /**
  113806. * Specifies whether or not the outer glow is ACTIVE in the layer.
  113807. */
  113808. _this.outerGlow = true;
  113809. /**
  113810. * An event triggered when the highlight layer is being blurred.
  113811. */
  113812. _this.onBeforeBlurObservable = new BABYLON.Observable();
  113813. /**
  113814. * An event triggered when the highlight layer has been blurred.
  113815. */
  113816. _this.onAfterBlurObservable = new BABYLON.Observable();
  113817. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  113818. _this._meshes = {};
  113819. _this._excludedMeshes = {};
  113820. _this.neutralColor = HighlightLayer.NeutralColor;
  113821. // Warn on stencil
  113822. if (!_this._engine.isStencilEnable) {
  113823. 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 }");
  113824. }
  113825. // Adapt options
  113826. _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);
  113827. // Initialize the layer
  113828. _this._init({
  113829. alphaBlendingMode: _this._options.alphaBlendingMode,
  113830. camera: _this._options.camera,
  113831. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  113832. mainTextureRatio: _this._options.mainTextureRatio,
  113833. renderingGroupId: _this._options.renderingGroupId
  113834. });
  113835. // Do not render as long as no meshes have been added
  113836. _this._shouldRender = false;
  113837. return _this;
  113838. }
  113839. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  113840. /**
  113841. * Gets the horizontal size of the blur.
  113842. */
  113843. get: function () {
  113844. return this._horizontalBlurPostprocess.kernel;
  113845. },
  113846. /**
  113847. * Specifies the horizontal size of the blur.
  113848. */
  113849. set: function (value) {
  113850. this._horizontalBlurPostprocess.kernel = value;
  113851. },
  113852. enumerable: true,
  113853. configurable: true
  113854. });
  113855. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  113856. /**
  113857. * Gets the vertical size of the blur.
  113858. */
  113859. get: function () {
  113860. return this._verticalBlurPostprocess.kernel;
  113861. },
  113862. /**
  113863. * Specifies the vertical size of the blur.
  113864. */
  113865. set: function (value) {
  113866. this._verticalBlurPostprocess.kernel = value;
  113867. },
  113868. enumerable: true,
  113869. configurable: true
  113870. });
  113871. /**
  113872. * Get the effect name of the layer.
  113873. * @return The effect name
  113874. */
  113875. HighlightLayer.prototype.getEffectName = function () {
  113876. return HighlightLayer.EffectName;
  113877. };
  113878. /**
  113879. * Create the merge effect. This is the shader use to blit the information back
  113880. * to the main canvas at the end of the scene rendering.
  113881. */
  113882. HighlightLayer.prototype._createMergeEffect = function () {
  113883. // Effect
  113884. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  113885. };
  113886. /**
  113887. * Creates the render target textures and post processes used in the highlight layer.
  113888. */
  113889. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  113890. var _this = this;
  113891. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  113892. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  113893. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  113894. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  113895. var textureType = 0;
  113896. if (this._engine.getCaps().textureHalfFloatRender) {
  113897. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  113898. }
  113899. else {
  113900. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  113901. }
  113902. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  113903. width: blurTextureWidth,
  113904. height: blurTextureHeight
  113905. }, this._scene, false, true, textureType);
  113906. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  113907. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  113908. this._blurTexture.anisotropicFilteringLevel = 16;
  113909. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  113910. this._blurTexture.renderParticles = false;
  113911. this._blurTexture.ignoreCameraViewport = true;
  113912. this._textures = [this._blurTexture];
  113913. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  113914. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  113915. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  113916. effect.setTexture("textureSampler", _this._mainTexture);
  113917. });
  113918. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  113919. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  113920. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  113921. });
  113922. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  113923. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  113924. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  113925. });
  113926. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  113927. }
  113928. else {
  113929. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  113930. width: blurTextureWidth,
  113931. height: blurTextureHeight
  113932. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  113933. this._horizontalBlurPostprocess.width = blurTextureWidth;
  113934. this._horizontalBlurPostprocess.height = blurTextureHeight;
  113935. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  113936. effect.setTexture("textureSampler", _this._mainTexture);
  113937. });
  113938. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  113939. width: blurTextureWidth,
  113940. height: blurTextureHeight
  113941. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  113942. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  113943. }
  113944. this._mainTexture.onAfterUnbindObservable.add(function () {
  113945. _this.onBeforeBlurObservable.notifyObservers(_this);
  113946. var internalTexture = _this._blurTexture.getInternalTexture();
  113947. if (internalTexture) {
  113948. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  113949. }
  113950. _this.onAfterBlurObservable.notifyObservers(_this);
  113951. });
  113952. // Prevent autoClear.
  113953. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  113954. };
  113955. /**
  113956. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  113957. */
  113958. HighlightLayer.prototype.needStencil = function () {
  113959. return true;
  113960. };
  113961. /**
  113962. * Checks for the readiness of the element composing the layer.
  113963. * @param subMesh the mesh to check for
  113964. * @param useInstances specify wether or not to use instances to render the mesh
  113965. * @param emissiveTexture the associated emissive texture used to generate the glow
  113966. * @return true if ready otherwise, false
  113967. */
  113968. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  113969. var material = subMesh.getMaterial();
  113970. var mesh = subMesh.getRenderingMesh();
  113971. if (!material || !mesh || !this._meshes) {
  113972. return false;
  113973. }
  113974. var emissiveTexture = null;
  113975. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  113976. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  113977. emissiveTexture = material.emissiveTexture;
  113978. }
  113979. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  113980. };
  113981. /**
  113982. * Implementation specific of rendering the generating effect on the main canvas.
  113983. * @param effect The effect used to render through
  113984. */
  113985. HighlightLayer.prototype._internalRender = function (effect) {
  113986. // Texture
  113987. effect.setTexture("textureSampler", this._blurTexture);
  113988. // Cache
  113989. var engine = this._engine;
  113990. var previousStencilBuffer = engine.getStencilBuffer();
  113991. var previousStencilFunction = engine.getStencilFunction();
  113992. var previousStencilMask = engine.getStencilMask();
  113993. var previousStencilOperationPass = engine.getStencilOperationPass();
  113994. var previousStencilOperationFail = engine.getStencilOperationFail();
  113995. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  113996. var previousStencilReference = engine.getStencilFunctionReference();
  113997. // Stencil operations
  113998. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  113999. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  114000. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  114001. // Draw order
  114002. engine.setStencilMask(0x00);
  114003. engine.setStencilBuffer(true);
  114004. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  114005. // 2 passes inner outer
  114006. if (this.outerGlow) {
  114007. effect.setFloat("offset", 0);
  114008. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  114009. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  114010. }
  114011. if (this.innerGlow) {
  114012. effect.setFloat("offset", 1);
  114013. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  114014. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  114015. }
  114016. // Restore Cache
  114017. engine.setStencilFunction(previousStencilFunction);
  114018. engine.setStencilMask(previousStencilMask);
  114019. engine.setStencilBuffer(previousStencilBuffer);
  114020. engine.setStencilOperationPass(previousStencilOperationPass);
  114021. engine.setStencilOperationFail(previousStencilOperationFail);
  114022. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  114023. engine.setStencilFunctionReference(previousStencilReference);
  114024. };
  114025. /**
  114026. * Returns true if the layer contains information to display, otherwise false.
  114027. */
  114028. HighlightLayer.prototype.shouldRender = function () {
  114029. if (_super.prototype.shouldRender.call(this)) {
  114030. return this._meshes ? true : false;
  114031. }
  114032. return false;
  114033. };
  114034. /**
  114035. * Returns true if the mesh should render, otherwise false.
  114036. * @param mesh The mesh to render
  114037. * @returns true if it should render otherwise false
  114038. */
  114039. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  114040. // Excluded Mesh
  114041. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  114042. return false;
  114043. }
  114044. if (!_super.prototype.hasMesh.call(this, mesh)) {
  114045. return false;
  114046. }
  114047. return true;
  114048. };
  114049. /**
  114050. * Sets the required values for both the emissive texture and and the main color.
  114051. */
  114052. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  114053. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  114054. if (highlightLayerMesh) {
  114055. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  114056. }
  114057. else {
  114058. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  114059. }
  114060. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  114061. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  114062. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  114063. }
  114064. else {
  114065. this._emissiveTextureAndColor.texture = null;
  114066. }
  114067. };
  114068. /**
  114069. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  114070. * @param mesh The mesh to exclude from the highlight layer
  114071. */
  114072. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  114073. if (!this._excludedMeshes) {
  114074. return;
  114075. }
  114076. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  114077. if (!meshExcluded) {
  114078. this._excludedMeshes[mesh.uniqueId] = {
  114079. mesh: mesh,
  114080. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  114081. mesh.getEngine().setStencilBuffer(false);
  114082. }),
  114083. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  114084. mesh.getEngine().setStencilBuffer(true);
  114085. }),
  114086. };
  114087. }
  114088. };
  114089. /**
  114090. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  114091. * @param mesh The mesh to highlight
  114092. */
  114093. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  114094. if (!this._excludedMeshes) {
  114095. return;
  114096. }
  114097. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  114098. if (meshExcluded) {
  114099. if (meshExcluded.beforeRender) {
  114100. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  114101. }
  114102. if (meshExcluded.afterRender) {
  114103. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  114104. }
  114105. }
  114106. this._excludedMeshes[mesh.uniqueId] = null;
  114107. };
  114108. /**
  114109. * Determine if a given mesh will be highlighted by the current HighlightLayer
  114110. * @param mesh mesh to test
  114111. * @returns true if the mesh will be highlighted by the current HighlightLayer
  114112. */
  114113. HighlightLayer.prototype.hasMesh = function (mesh) {
  114114. if (!this._meshes) {
  114115. return false;
  114116. }
  114117. if (!_super.prototype.hasMesh.call(this, mesh)) {
  114118. return false;
  114119. }
  114120. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  114121. };
  114122. /**
  114123. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  114124. * @param mesh The mesh to highlight
  114125. * @param color The color of the highlight
  114126. * @param glowEmissiveOnly Extract the glow from the emissive texture
  114127. */
  114128. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  114129. var _this = this;
  114130. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  114131. if (!this._meshes) {
  114132. return;
  114133. }
  114134. var meshHighlight = this._meshes[mesh.uniqueId];
  114135. if (meshHighlight) {
  114136. meshHighlight.color = color;
  114137. }
  114138. else {
  114139. this._meshes[mesh.uniqueId] = {
  114140. mesh: mesh,
  114141. color: color,
  114142. // Lambda required for capture due to Observable this context
  114143. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  114144. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  114145. _this._defaultStencilReference(mesh);
  114146. }
  114147. else {
  114148. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  114149. }
  114150. }),
  114151. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  114152. glowEmissiveOnly: glowEmissiveOnly
  114153. };
  114154. mesh.onDisposeObservable.add(function () {
  114155. _this._disposeMesh(mesh);
  114156. });
  114157. }
  114158. this._shouldRender = true;
  114159. };
  114160. /**
  114161. * Remove a mesh from the highlight layer in order to make it stop glowing.
  114162. * @param mesh The mesh to highlight
  114163. */
  114164. HighlightLayer.prototype.removeMesh = function (mesh) {
  114165. if (!this._meshes) {
  114166. return;
  114167. }
  114168. var meshHighlight = this._meshes[mesh.uniqueId];
  114169. if (meshHighlight) {
  114170. if (meshHighlight.observerHighlight) {
  114171. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  114172. }
  114173. if (meshHighlight.observerDefault) {
  114174. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  114175. }
  114176. delete this._meshes[mesh.uniqueId];
  114177. }
  114178. this._shouldRender = false;
  114179. for (var meshHighlightToCheck in this._meshes) {
  114180. if (this._meshes[meshHighlightToCheck]) {
  114181. this._shouldRender = true;
  114182. break;
  114183. }
  114184. }
  114185. };
  114186. /**
  114187. * Force the stencil to the normal expected value for none glowing parts
  114188. */
  114189. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  114190. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  114191. };
  114192. /**
  114193. * Free any resources and references associated to a mesh.
  114194. * Internal use
  114195. * @param mesh The mesh to free.
  114196. * @hidden
  114197. */
  114198. HighlightLayer.prototype._disposeMesh = function (mesh) {
  114199. this.removeMesh(mesh);
  114200. this.removeExcludedMesh(mesh);
  114201. };
  114202. /**
  114203. * Dispose the highlight layer and free resources.
  114204. */
  114205. HighlightLayer.prototype.dispose = function () {
  114206. if (this._meshes) {
  114207. // Clean mesh references
  114208. for (var id in this._meshes) {
  114209. var meshHighlight = this._meshes[id];
  114210. if (meshHighlight && meshHighlight.mesh) {
  114211. if (meshHighlight.observerHighlight) {
  114212. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  114213. }
  114214. if (meshHighlight.observerDefault) {
  114215. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  114216. }
  114217. }
  114218. }
  114219. this._meshes = null;
  114220. }
  114221. if (this._excludedMeshes) {
  114222. for (var id in this._excludedMeshes) {
  114223. var meshHighlight = this._excludedMeshes[id];
  114224. if (meshHighlight) {
  114225. if (meshHighlight.beforeRender) {
  114226. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  114227. }
  114228. if (meshHighlight.afterRender) {
  114229. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  114230. }
  114231. }
  114232. }
  114233. this._excludedMeshes = null;
  114234. }
  114235. _super.prototype.dispose.call(this);
  114236. };
  114237. /**
  114238. * Gets the class name of the effect layer
  114239. * @returns the string with the class name of the effect layer
  114240. */
  114241. HighlightLayer.prototype.getClassName = function () {
  114242. return "HighlightLayer";
  114243. };
  114244. /**
  114245. * Serializes this Highlight layer
  114246. * @returns a serialized Highlight layer object
  114247. */
  114248. HighlightLayer.prototype.serialize = function () {
  114249. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  114250. serializationObject.customType = "BABYLON.HighlightLayer";
  114251. // Highlighted meshes
  114252. serializationObject.meshes = [];
  114253. if (this._meshes) {
  114254. for (var m in this._meshes) {
  114255. var mesh = this._meshes[m];
  114256. if (mesh) {
  114257. serializationObject.meshes.push({
  114258. glowEmissiveOnly: mesh.glowEmissiveOnly,
  114259. color: mesh.color.asArray(),
  114260. meshId: mesh.mesh.id
  114261. });
  114262. }
  114263. }
  114264. }
  114265. // Excluded meshes
  114266. serializationObject.excludedMeshes = [];
  114267. if (this._excludedMeshes) {
  114268. for (var e in this._excludedMeshes) {
  114269. var excludedMesh = this._excludedMeshes[e];
  114270. if (excludedMesh) {
  114271. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  114272. }
  114273. }
  114274. }
  114275. return serializationObject;
  114276. };
  114277. /**
  114278. * Creates a Highlight layer from parsed Highlight layer data
  114279. * @param parsedHightlightLayer defines the Highlight layer data
  114280. * @param scene defines the current scene
  114281. * @param rootUrl defines the root URL containing the Highlight layer information
  114282. * @returns a parsed Highlight layer
  114283. */
  114284. HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
  114285. var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
  114286. var index;
  114287. // Excluded meshes
  114288. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  114289. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  114290. if (mesh) {
  114291. hl.addExcludedMesh(mesh);
  114292. }
  114293. }
  114294. // Included meshes
  114295. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  114296. var highlightedMesh = parsedHightlightLayer.meshes[index];
  114297. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  114298. if (mesh) {
  114299. hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  114300. }
  114301. }
  114302. return hl;
  114303. };
  114304. /**
  114305. * Effect Name of the highlight layer.
  114306. */
  114307. HighlightLayer.EffectName = "HighlightLayer";
  114308. /**
  114309. * The neutral color used during the preparation of the glow effect.
  114310. * This is black by default as the blend operation is a blend operation.
  114311. */
  114312. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  114313. /**
  114314. * Stencil value used for glowing meshes.
  114315. */
  114316. HighlightLayer.GlowingMeshStencilReference = 0x02;
  114317. /**
  114318. * Stencil value used for the other meshes in the scene.
  114319. */
  114320. HighlightLayer.NormalMeshStencilReference = 0x01;
  114321. __decorate([
  114322. BABYLON.serialize()
  114323. ], HighlightLayer.prototype, "innerGlow", void 0);
  114324. __decorate([
  114325. BABYLON.serialize()
  114326. ], HighlightLayer.prototype, "outerGlow", void 0);
  114327. __decorate([
  114328. BABYLON.serialize()
  114329. ], HighlightLayer.prototype, "blurHorizontalSize", null);
  114330. __decorate([
  114331. BABYLON.serialize()
  114332. ], HighlightLayer.prototype, "blurVerticalSize", null);
  114333. __decorate([
  114334. BABYLON.serialize("options")
  114335. ], HighlightLayer.prototype, "_options", void 0);
  114336. return HighlightLayer;
  114337. }(BABYLON.EffectLayer));
  114338. BABYLON.HighlightLayer = HighlightLayer;
  114339. })(BABYLON || (BABYLON = {}));
  114340. //# sourceMappingURL=babylon.highlightLayer.js.map
  114341. var BABYLON;
  114342. (function (BABYLON) {
  114343. BABYLON.AbstractScene.prototype.getGlowLayerByName = function (name) {
  114344. for (var index = 0; index < this.effectLayers.length; index++) {
  114345. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === GlowLayer.EffectName) {
  114346. return this.effectLayers[index];
  114347. }
  114348. }
  114349. return null;
  114350. };
  114351. /**
  114352. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  114353. *
  114354. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  114355. * glowy meshes to your scene.
  114356. *
  114357. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  114358. */
  114359. var GlowLayer = /** @class */ (function (_super) {
  114360. __extends(GlowLayer, _super);
  114361. /**
  114362. * Instantiates a new glow Layer and references it to the scene.
  114363. * @param name The name of the layer
  114364. * @param scene The scene to use the layer in
  114365. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  114366. */
  114367. function GlowLayer(name, scene, options) {
  114368. var _this = _super.call(this, name, scene) || this;
  114369. _this._intensity = 1.0;
  114370. _this._includedOnlyMeshes = [];
  114371. _this._excludedMeshes = [];
  114372. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  114373. // Adapt options
  114374. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1, renderingGroupId: -1 }, options);
  114375. // Initialize the layer
  114376. _this._init({
  114377. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  114378. camera: _this._options.camera,
  114379. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  114380. mainTextureRatio: _this._options.mainTextureRatio,
  114381. renderingGroupId: _this._options.renderingGroupId
  114382. });
  114383. return _this;
  114384. }
  114385. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  114386. /**
  114387. * Gets the kernel size of the blur.
  114388. */
  114389. get: function () {
  114390. return this._horizontalBlurPostprocess1.kernel;
  114391. },
  114392. /**
  114393. * Sets the kernel size of the blur.
  114394. */
  114395. set: function (value) {
  114396. this._horizontalBlurPostprocess1.kernel = value;
  114397. this._verticalBlurPostprocess1.kernel = value;
  114398. this._horizontalBlurPostprocess2.kernel = value;
  114399. this._verticalBlurPostprocess2.kernel = value;
  114400. },
  114401. enumerable: true,
  114402. configurable: true
  114403. });
  114404. Object.defineProperty(GlowLayer.prototype, "intensity", {
  114405. /**
  114406. * Gets the glow intensity.
  114407. */
  114408. get: function () {
  114409. return this._intensity;
  114410. },
  114411. /**
  114412. * Sets the glow intensity.
  114413. */
  114414. set: function (value) {
  114415. this._intensity = value;
  114416. },
  114417. enumerable: true,
  114418. configurable: true
  114419. });
  114420. /**
  114421. * Get the effect name of the layer.
  114422. * @return The effect name
  114423. */
  114424. GlowLayer.prototype.getEffectName = function () {
  114425. return GlowLayer.EffectName;
  114426. };
  114427. /**
  114428. * Create the merge effect. This is the shader use to blit the information back
  114429. * to the main canvas at the end of the scene rendering.
  114430. */
  114431. GlowLayer.prototype._createMergeEffect = function () {
  114432. // Effect
  114433. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  114434. };
  114435. /**
  114436. * Creates the render target textures and post processes used in the glow layer.
  114437. */
  114438. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  114439. var _this = this;
  114440. var blurTextureWidth = this._mainTextureDesiredSize.width;
  114441. var blurTextureHeight = this._mainTextureDesiredSize.height;
  114442. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  114443. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  114444. var textureType = 0;
  114445. if (this._engine.getCaps().textureHalfFloatRender) {
  114446. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  114447. }
  114448. else {
  114449. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  114450. }
  114451. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  114452. width: blurTextureWidth,
  114453. height: blurTextureHeight
  114454. }, this._scene, false, true, textureType);
  114455. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  114456. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  114457. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  114458. this._blurTexture1.renderParticles = false;
  114459. this._blurTexture1.ignoreCameraViewport = true;
  114460. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  114461. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  114462. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  114463. width: blurTextureWidth2,
  114464. height: blurTextureHeight2
  114465. }, this._scene, false, true, textureType);
  114466. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  114467. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  114468. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  114469. this._blurTexture2.renderParticles = false;
  114470. this._blurTexture2.ignoreCameraViewport = true;
  114471. this._textures = [this._blurTexture1, this._blurTexture2];
  114472. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  114473. width: blurTextureWidth,
  114474. height: blurTextureHeight
  114475. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  114476. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  114477. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  114478. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  114479. effect.setTexture("textureSampler", _this._mainTexture);
  114480. });
  114481. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  114482. width: blurTextureWidth,
  114483. height: blurTextureHeight
  114484. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  114485. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  114486. width: blurTextureWidth2,
  114487. height: blurTextureHeight2
  114488. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  114489. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  114490. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  114491. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  114492. effect.setTexture("textureSampler", _this._blurTexture1);
  114493. });
  114494. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  114495. width: blurTextureWidth2,
  114496. height: blurTextureHeight2
  114497. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  114498. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  114499. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  114500. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  114501. this._mainTexture.samples = this._options.mainTextureSamples;
  114502. this._mainTexture.onAfterUnbindObservable.add(function () {
  114503. var internalTexture = _this._blurTexture1.getInternalTexture();
  114504. if (internalTexture) {
  114505. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  114506. internalTexture = _this._blurTexture2.getInternalTexture();
  114507. if (internalTexture) {
  114508. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  114509. }
  114510. }
  114511. });
  114512. // Prevent autoClear.
  114513. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  114514. };
  114515. /**
  114516. * Checks for the readiness of the element composing the layer.
  114517. * @param subMesh the mesh to check for
  114518. * @param useInstances specify wether or not to use instances to render the mesh
  114519. * @param emissiveTexture the associated emissive texture used to generate the glow
  114520. * @return true if ready otherwise, false
  114521. */
  114522. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  114523. var material = subMesh.getMaterial();
  114524. var mesh = subMesh.getRenderingMesh();
  114525. if (!material || !mesh) {
  114526. return false;
  114527. }
  114528. var emissiveTexture = material.emissiveTexture;
  114529. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  114530. };
  114531. /**
  114532. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  114533. */
  114534. GlowLayer.prototype.needStencil = function () {
  114535. return false;
  114536. };
  114537. /**
  114538. * Implementation specific of rendering the generating effect on the main canvas.
  114539. * @param effect The effect used to render through
  114540. */
  114541. GlowLayer.prototype._internalRender = function (effect) {
  114542. // Texture
  114543. effect.setTexture("textureSampler", this._blurTexture1);
  114544. effect.setTexture("textureSampler2", this._blurTexture2);
  114545. effect.setFloat("offset", this._intensity);
  114546. // Cache
  114547. var engine = this._engine;
  114548. var previousStencilBuffer = engine.getStencilBuffer();
  114549. // Draw order
  114550. engine.setStencilBuffer(false);
  114551. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  114552. // Draw order
  114553. engine.setStencilBuffer(previousStencilBuffer);
  114554. };
  114555. /**
  114556. * Sets the required values for both the emissive texture and and the main color.
  114557. */
  114558. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  114559. var textureLevel = 1.0;
  114560. if (this.customEmissiveTextureSelector) {
  114561. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  114562. }
  114563. else {
  114564. if (material) {
  114565. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  114566. if (this._emissiveTextureAndColor.texture) {
  114567. textureLevel = this._emissiveTextureAndColor.texture.level;
  114568. }
  114569. }
  114570. else {
  114571. this._emissiveTextureAndColor.texture = null;
  114572. }
  114573. }
  114574. if (this.customEmissiveColorSelector) {
  114575. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  114576. }
  114577. else {
  114578. if (material.emissiveColor) {
  114579. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  114580. }
  114581. else {
  114582. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  114583. }
  114584. }
  114585. };
  114586. /**
  114587. * Returns true if the mesh should render, otherwise false.
  114588. * @param mesh The mesh to render
  114589. * @returns true if it should render otherwise false
  114590. */
  114591. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  114592. return this.hasMesh(mesh);
  114593. };
  114594. /**
  114595. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  114596. * @param mesh The mesh to exclude from the glow layer
  114597. */
  114598. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  114599. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  114600. this._excludedMeshes.push(mesh.uniqueId);
  114601. }
  114602. };
  114603. /**
  114604. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  114605. * @param mesh The mesh to remove
  114606. */
  114607. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  114608. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  114609. if (index !== -1) {
  114610. this._excludedMeshes.splice(index, 1);
  114611. }
  114612. };
  114613. /**
  114614. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  114615. * @param mesh The mesh to include in the glow layer
  114616. */
  114617. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  114618. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  114619. this._includedOnlyMeshes.push(mesh.uniqueId);
  114620. }
  114621. };
  114622. /**
  114623. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  114624. * @param mesh The mesh to remove
  114625. */
  114626. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  114627. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  114628. if (index !== -1) {
  114629. this._includedOnlyMeshes.splice(index, 1);
  114630. }
  114631. };
  114632. /**
  114633. * Determine if a given mesh will be used in the glow layer
  114634. * @param mesh The mesh to test
  114635. * @returns true if the mesh will be highlighted by the current glow layer
  114636. */
  114637. GlowLayer.prototype.hasMesh = function (mesh) {
  114638. if (!_super.prototype.hasMesh.call(this, mesh)) {
  114639. return false;
  114640. }
  114641. // Included Mesh
  114642. if (this._includedOnlyMeshes.length) {
  114643. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  114644. }
  114645. // Excluded Mesh
  114646. if (this._excludedMeshes.length) {
  114647. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  114648. }
  114649. return true;
  114650. };
  114651. /**
  114652. * Free any resources and references associated to a mesh.
  114653. * Internal use
  114654. * @param mesh The mesh to free.
  114655. * @hidden
  114656. */
  114657. GlowLayer.prototype._disposeMesh = function (mesh) {
  114658. this.removeIncludedOnlyMesh(mesh);
  114659. this.removeExcludedMesh(mesh);
  114660. };
  114661. /**
  114662. * Gets the class name of the effect layer
  114663. * @returns the string with the class name of the effect layer
  114664. */
  114665. GlowLayer.prototype.getClassName = function () {
  114666. return "GlowLayer";
  114667. };
  114668. /**
  114669. * Serializes this glow layer
  114670. * @returns a serialized glow layer object
  114671. */
  114672. GlowLayer.prototype.serialize = function () {
  114673. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  114674. serializationObject.customType = "BABYLON.GlowLayer";
  114675. var index;
  114676. // Included meshes
  114677. serializationObject.includedMeshes = [];
  114678. if (this._includedOnlyMeshes.length) {
  114679. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  114680. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  114681. if (mesh) {
  114682. serializationObject.includedMeshes.push(mesh.id);
  114683. }
  114684. }
  114685. }
  114686. // Excluded meshes
  114687. serializationObject.excludedMeshes = [];
  114688. if (this._excludedMeshes.length) {
  114689. for (index = 0; index < this._excludedMeshes.length; index++) {
  114690. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  114691. if (mesh) {
  114692. serializationObject.excludedMeshes.push(mesh.id);
  114693. }
  114694. }
  114695. }
  114696. return serializationObject;
  114697. };
  114698. /**
  114699. * Creates a Glow Layer from parsed glow layer data
  114700. * @param parsedGlowLayer defines glow layer data
  114701. * @param scene defines the current scene
  114702. * @param rootUrl defines the root URL containing the glow layer information
  114703. * @returns a parsed Glow Layer
  114704. */
  114705. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  114706. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  114707. var index;
  114708. // Excluded meshes
  114709. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  114710. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  114711. if (mesh) {
  114712. gl.addExcludedMesh(mesh);
  114713. }
  114714. }
  114715. // Included meshes
  114716. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  114717. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  114718. if (mesh) {
  114719. gl.addIncludedOnlyMesh(mesh);
  114720. }
  114721. }
  114722. return gl;
  114723. };
  114724. /**
  114725. * Effect Name of the layer.
  114726. */
  114727. GlowLayer.EffectName = "GlowLayer";
  114728. /**
  114729. * The default blur kernel size used for the glow.
  114730. */
  114731. GlowLayer.DefaultBlurKernelSize = 32;
  114732. /**
  114733. * The default texture size ratio used for the glow.
  114734. */
  114735. GlowLayer.DefaultTextureRatio = 0.5;
  114736. __decorate([
  114737. BABYLON.serialize()
  114738. ], GlowLayer.prototype, "blurKernelSize", null);
  114739. __decorate([
  114740. BABYLON.serialize()
  114741. ], GlowLayer.prototype, "intensity", null);
  114742. __decorate([
  114743. BABYLON.serialize("options")
  114744. ], GlowLayer.prototype, "_options", void 0);
  114745. return GlowLayer;
  114746. }(BABYLON.EffectLayer));
  114747. BABYLON.GlowLayer = GlowLayer;
  114748. })(BABYLON || (BABYLON = {}));
  114749. //# sourceMappingURL=babylon.glowLayer.js.map
  114750. var BABYLON;
  114751. (function (BABYLON) {
  114752. /**
  114753. * Defines the list of states available for a task inside a AssetsManager
  114754. */
  114755. var AssetTaskState;
  114756. (function (AssetTaskState) {
  114757. /**
  114758. * Initialization
  114759. */
  114760. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  114761. /**
  114762. * Running
  114763. */
  114764. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  114765. /**
  114766. * Done
  114767. */
  114768. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  114769. /**
  114770. * Error
  114771. */
  114772. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  114773. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  114774. /**
  114775. * Define an abstract asset task used with a AssetsManager class to load assets into a scene
  114776. */
  114777. var AbstractAssetTask = /** @class */ (function () {
  114778. /**
  114779. * Creates a new AssetsManager
  114780. * @param name defines the name of the task
  114781. */
  114782. function AbstractAssetTask(
  114783. /**
  114784. * Task name
  114785. */ name) {
  114786. this.name = name;
  114787. this._isCompleted = false;
  114788. this._taskState = AssetTaskState.INIT;
  114789. }
  114790. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  114791. /**
  114792. * Get if the task is completed
  114793. */
  114794. get: function () {
  114795. return this._isCompleted;
  114796. },
  114797. enumerable: true,
  114798. configurable: true
  114799. });
  114800. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  114801. /**
  114802. * Gets the current state of the task
  114803. */
  114804. get: function () {
  114805. return this._taskState;
  114806. },
  114807. enumerable: true,
  114808. configurable: true
  114809. });
  114810. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  114811. /**
  114812. * Gets the current error object (if task is in error)
  114813. */
  114814. get: function () {
  114815. return this._errorObject;
  114816. },
  114817. enumerable: true,
  114818. configurable: true
  114819. });
  114820. /**
  114821. * Internal only
  114822. * @hidden
  114823. */
  114824. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  114825. if (this._errorObject) {
  114826. return;
  114827. }
  114828. this._errorObject = {
  114829. message: message,
  114830. exception: exception
  114831. };
  114832. };
  114833. /**
  114834. * Execute the current task
  114835. * @param scene defines the scene where you want your assets to be loaded
  114836. * @param onSuccess is a callback called when the task is successfully executed
  114837. * @param onError is a callback called if an error occurs
  114838. */
  114839. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  114840. var _this = this;
  114841. this._taskState = AssetTaskState.RUNNING;
  114842. this.runTask(scene, function () {
  114843. _this.onDoneCallback(onSuccess, onError);
  114844. }, function (msg, exception) {
  114845. _this.onErrorCallback(onError, msg, exception);
  114846. });
  114847. };
  114848. /**
  114849. * Execute the current task
  114850. * @param scene defines the scene where you want your assets to be loaded
  114851. * @param onSuccess is a callback called when the task is successfully executed
  114852. * @param onError is a callback called if an error occurs
  114853. */
  114854. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  114855. throw new Error("runTask is not implemented");
  114856. };
  114857. /**
  114858. * Reset will set the task state back to INIT, so the next load call of the assets manager will execute this task again.
  114859. * This can be used with failed tasks that have the reason for failure fixed.
  114860. */
  114861. AbstractAssetTask.prototype.reset = function () {
  114862. this._taskState = AssetTaskState.INIT;
  114863. };
  114864. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  114865. this._taskState = AssetTaskState.ERROR;
  114866. this._errorObject = {
  114867. message: message,
  114868. exception: exception
  114869. };
  114870. if (this.onError) {
  114871. this.onError(this, message, exception);
  114872. }
  114873. onError();
  114874. };
  114875. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  114876. try {
  114877. this._taskState = AssetTaskState.DONE;
  114878. this._isCompleted = true;
  114879. if (this.onSuccess) {
  114880. this.onSuccess(this);
  114881. }
  114882. onSuccess();
  114883. }
  114884. catch (e) {
  114885. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  114886. }
  114887. };
  114888. return AbstractAssetTask;
  114889. }());
  114890. BABYLON.AbstractAssetTask = AbstractAssetTask;
  114891. /**
  114892. * Class used to share progress information about assets loading
  114893. */
  114894. var AssetsProgressEvent = /** @class */ (function () {
  114895. /**
  114896. * Creates a AssetsProgressEvent
  114897. * @param remainingCount defines the number of remaining tasks to process
  114898. * @param totalCount defines the total number of tasks
  114899. * @param task defines the task that was just processed
  114900. */
  114901. function AssetsProgressEvent(remainingCount, totalCount, task) {
  114902. this.remainingCount = remainingCount;
  114903. this.totalCount = totalCount;
  114904. this.task = task;
  114905. }
  114906. return AssetsProgressEvent;
  114907. }());
  114908. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  114909. /**
  114910. * Define a task used by AssetsManager to load meshes
  114911. */
  114912. var MeshAssetTask = /** @class */ (function (_super) {
  114913. __extends(MeshAssetTask, _super);
  114914. /**
  114915. * Creates a new MeshAssetTask
  114916. * @param name defines the name of the task
  114917. * @param meshesNames defines the list of mesh's names you want to load
  114918. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  114919. * @param sceneFilename defines the filename of the scene to load from
  114920. */
  114921. function MeshAssetTask(
  114922. /**
  114923. * Defines the name of the task
  114924. */
  114925. name,
  114926. /**
  114927. * Defines the list of mesh's names you want to load
  114928. */
  114929. meshesNames,
  114930. /**
  114931. * Defines the root url to use as a base to load your meshes and associated resources
  114932. */
  114933. rootUrl,
  114934. /**
  114935. * Defines the filename of the scene to load from
  114936. */
  114937. sceneFilename) {
  114938. var _this = _super.call(this, name) || this;
  114939. _this.name = name;
  114940. _this.meshesNames = meshesNames;
  114941. _this.rootUrl = rootUrl;
  114942. _this.sceneFilename = sceneFilename;
  114943. return _this;
  114944. }
  114945. /**
  114946. * Execute the current task
  114947. * @param scene defines the scene where you want your assets to be loaded
  114948. * @param onSuccess is a callback called when the task is successfully executed
  114949. * @param onError is a callback called if an error occurs
  114950. */
  114951. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  114952. var _this = this;
  114953. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  114954. _this.loadedMeshes = meshes;
  114955. _this.loadedParticleSystems = particleSystems;
  114956. _this.loadedSkeletons = skeletons;
  114957. onSuccess();
  114958. }, null, function (scene, message, exception) {
  114959. onError(message, exception);
  114960. });
  114961. };
  114962. return MeshAssetTask;
  114963. }(AbstractAssetTask));
  114964. BABYLON.MeshAssetTask = MeshAssetTask;
  114965. /**
  114966. * Define a task used by AssetsManager to load text content
  114967. */
  114968. var TextFileAssetTask = /** @class */ (function (_super) {
  114969. __extends(TextFileAssetTask, _super);
  114970. /**
  114971. * Creates a new TextFileAssetTask object
  114972. * @param name defines the name of the task
  114973. * @param url defines the location of the file to load
  114974. */
  114975. function TextFileAssetTask(
  114976. /**
  114977. * Defines the name of the task
  114978. */
  114979. name,
  114980. /**
  114981. * Defines the location of the file to load
  114982. */
  114983. url) {
  114984. var _this = _super.call(this, name) || this;
  114985. _this.name = name;
  114986. _this.url = url;
  114987. return _this;
  114988. }
  114989. /**
  114990. * Execute the current task
  114991. * @param scene defines the scene where you want your assets to be loaded
  114992. * @param onSuccess is a callback called when the task is successfully executed
  114993. * @param onError is a callback called if an error occurs
  114994. */
  114995. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  114996. var _this = this;
  114997. scene._loadFile(this.url, function (data) {
  114998. _this.text = data;
  114999. onSuccess();
  115000. }, undefined, false, false, function (request, exception) {
  115001. if (request) {
  115002. onError(request.status + " " + request.statusText, exception);
  115003. }
  115004. });
  115005. };
  115006. return TextFileAssetTask;
  115007. }(AbstractAssetTask));
  115008. BABYLON.TextFileAssetTask = TextFileAssetTask;
  115009. /**
  115010. * Define a task used by AssetsManager to load binary data
  115011. */
  115012. var BinaryFileAssetTask = /** @class */ (function (_super) {
  115013. __extends(BinaryFileAssetTask, _super);
  115014. /**
  115015. * Creates a new BinaryFileAssetTask object
  115016. * @param name defines the name of the new task
  115017. * @param url defines the location of the file to load
  115018. */
  115019. function BinaryFileAssetTask(
  115020. /**
  115021. * Defines the name of the task
  115022. */
  115023. name,
  115024. /**
  115025. * Defines the location of the file to load
  115026. */
  115027. url) {
  115028. var _this = _super.call(this, name) || this;
  115029. _this.name = name;
  115030. _this.url = url;
  115031. return _this;
  115032. }
  115033. /**
  115034. * Execute the current task
  115035. * @param scene defines the scene where you want your assets to be loaded
  115036. * @param onSuccess is a callback called when the task is successfully executed
  115037. * @param onError is a callback called if an error occurs
  115038. */
  115039. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  115040. var _this = this;
  115041. scene._loadFile(this.url, function (data) {
  115042. _this.data = data;
  115043. onSuccess();
  115044. }, undefined, true, true, function (request, exception) {
  115045. if (request) {
  115046. onError(request.status + " " + request.statusText, exception);
  115047. }
  115048. });
  115049. };
  115050. return BinaryFileAssetTask;
  115051. }(AbstractAssetTask));
  115052. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  115053. /**
  115054. * Define a task used by AssetsManager to load images
  115055. */
  115056. var ImageAssetTask = /** @class */ (function (_super) {
  115057. __extends(ImageAssetTask, _super);
  115058. /**
  115059. * Creates a new ImageAssetTask
  115060. * @param name defines the name of the task
  115061. * @param url defines the location of the image to load
  115062. */
  115063. function ImageAssetTask(
  115064. /**
  115065. * Defines the name of the task
  115066. */
  115067. name,
  115068. /**
  115069. * Defines the location of the image to load
  115070. */
  115071. url) {
  115072. var _this = _super.call(this, name) || this;
  115073. _this.name = name;
  115074. _this.url = url;
  115075. return _this;
  115076. }
  115077. /**
  115078. * Execute the current task
  115079. * @param scene defines the scene where you want your assets to be loaded
  115080. * @param onSuccess is a callback called when the task is successfully executed
  115081. * @param onError is a callback called if an error occurs
  115082. */
  115083. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  115084. var _this = this;
  115085. var img = new Image();
  115086. BABYLON.Tools.SetCorsBehavior(this.url, img);
  115087. img.onload = function () {
  115088. _this.image = img;
  115089. onSuccess();
  115090. };
  115091. img.onerror = function (err) {
  115092. onError("Error loading image", err);
  115093. };
  115094. img.src = this.url;
  115095. };
  115096. return ImageAssetTask;
  115097. }(AbstractAssetTask));
  115098. BABYLON.ImageAssetTask = ImageAssetTask;
  115099. /**
  115100. * Define a task used by AssetsManager to load 2D textures
  115101. */
  115102. var TextureAssetTask = /** @class */ (function (_super) {
  115103. __extends(TextureAssetTask, _super);
  115104. /**
  115105. * Creates a new TextureAssetTask object
  115106. * @param name defines the name of the task
  115107. * @param url defines the location of the file to load
  115108. * @param noMipmap defines if mipmap should not be generated (default is false)
  115109. * @param invertY defines if texture must be inverted on Y axis (default is false)
  115110. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  115111. */
  115112. function TextureAssetTask(
  115113. /**
  115114. * Defines the name of the task
  115115. */
  115116. name,
  115117. /**
  115118. * Defines the location of the file to load
  115119. */
  115120. url,
  115121. /**
  115122. * Defines if mipmap should not be generated (default is false)
  115123. */
  115124. noMipmap,
  115125. /**
  115126. * Defines if texture must be inverted on Y axis (default is false)
  115127. */
  115128. invertY,
  115129. /**
  115130. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  115131. */
  115132. samplingMode) {
  115133. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  115134. var _this = _super.call(this, name) || this;
  115135. _this.name = name;
  115136. _this.url = url;
  115137. _this.noMipmap = noMipmap;
  115138. _this.invertY = invertY;
  115139. _this.samplingMode = samplingMode;
  115140. return _this;
  115141. }
  115142. /**
  115143. * Execute the current task
  115144. * @param scene defines the scene where you want your assets to be loaded
  115145. * @param onSuccess is a callback called when the task is successfully executed
  115146. * @param onError is a callback called if an error occurs
  115147. */
  115148. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  115149. var onload = function () {
  115150. onSuccess();
  115151. };
  115152. var onerror = function (message, exception) {
  115153. onError(message, exception);
  115154. };
  115155. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  115156. };
  115157. return TextureAssetTask;
  115158. }(AbstractAssetTask));
  115159. BABYLON.TextureAssetTask = TextureAssetTask;
  115160. /**
  115161. * Define a task used by AssetsManager to load cube textures
  115162. */
  115163. var CubeTextureAssetTask = /** @class */ (function (_super) {
  115164. __extends(CubeTextureAssetTask, _super);
  115165. /**
  115166. * Creates a new CubeTextureAssetTask
  115167. * @param name defines the name of the task
  115168. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  115169. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  115170. * @param noMipmap defines if mipmaps should not be generated (default is false)
  115171. * @param files defines the explicit list of files (undefined by default)
  115172. */
  115173. function CubeTextureAssetTask(
  115174. /**
  115175. * Defines the name of the task
  115176. */
  115177. name,
  115178. /**
  115179. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  115180. */
  115181. url,
  115182. /**
  115183. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  115184. */
  115185. extensions,
  115186. /**
  115187. * Defines if mipmaps should not be generated (default is false)
  115188. */
  115189. noMipmap,
  115190. /**
  115191. * Defines the explicit list of files (undefined by default)
  115192. */
  115193. files) {
  115194. var _this = _super.call(this, name) || this;
  115195. _this.name = name;
  115196. _this.url = url;
  115197. _this.extensions = extensions;
  115198. _this.noMipmap = noMipmap;
  115199. _this.files = files;
  115200. return _this;
  115201. }
  115202. /**
  115203. * Execute the current task
  115204. * @param scene defines the scene where you want your assets to be loaded
  115205. * @param onSuccess is a callback called when the task is successfully executed
  115206. * @param onError is a callback called if an error occurs
  115207. */
  115208. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  115209. var onload = function () {
  115210. onSuccess();
  115211. };
  115212. var onerror = function (message, exception) {
  115213. onError(message, exception);
  115214. };
  115215. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  115216. };
  115217. return CubeTextureAssetTask;
  115218. }(AbstractAssetTask));
  115219. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  115220. /**
  115221. * Define a task used by AssetsManager to load HDR cube textures
  115222. */
  115223. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  115224. __extends(HDRCubeTextureAssetTask, _super);
  115225. /**
  115226. * Creates a new HDRCubeTextureAssetTask object
  115227. * @param name defines the name of the task
  115228. * @param url defines the location of the file to load
  115229. * @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.
  115230. * @param noMipmap defines if mipmaps should not be generated (default is false)
  115231. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  115232. * @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)
  115233. * @param reserved Internal use only
  115234. */
  115235. function HDRCubeTextureAssetTask(
  115236. /**
  115237. * Defines the name of the task
  115238. */
  115239. name,
  115240. /**
  115241. * Defines the location of the file to load
  115242. */
  115243. url,
  115244. /**
  115245. * Defines the desired size (the more it increases the longer the generation will be)
  115246. */
  115247. size,
  115248. /**
  115249. * Defines if mipmaps should not be generated (default is false)
  115250. */
  115251. noMipmap,
  115252. /**
  115253. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  115254. */
  115255. generateHarmonics,
  115256. /**
  115257. * 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)
  115258. */
  115259. gammaSpace,
  115260. /**
  115261. * Internal Use Only
  115262. */
  115263. reserved) {
  115264. if (noMipmap === void 0) { noMipmap = false; }
  115265. if (generateHarmonics === void 0) { generateHarmonics = true; }
  115266. if (gammaSpace === void 0) { gammaSpace = false; }
  115267. if (reserved === void 0) { reserved = false; }
  115268. var _this = _super.call(this, name) || this;
  115269. _this.name = name;
  115270. _this.url = url;
  115271. _this.size = size;
  115272. _this.noMipmap = noMipmap;
  115273. _this.generateHarmonics = generateHarmonics;
  115274. _this.gammaSpace = gammaSpace;
  115275. _this.reserved = reserved;
  115276. return _this;
  115277. }
  115278. /**
  115279. * Execute the current task
  115280. * @param scene defines the scene where you want your assets to be loaded
  115281. * @param onSuccess is a callback called when the task is successfully executed
  115282. * @param onError is a callback called if an error occurs
  115283. */
  115284. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  115285. var onload = function () {
  115286. onSuccess();
  115287. };
  115288. var onerror = function (message, exception) {
  115289. onError(message, exception);
  115290. };
  115291. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.gammaSpace, this.reserved, onload, onerror);
  115292. };
  115293. return HDRCubeTextureAssetTask;
  115294. }(AbstractAssetTask));
  115295. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  115296. /**
  115297. * This class can be used to easily import assets into a scene
  115298. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  115299. */
  115300. var AssetsManager = /** @class */ (function () {
  115301. /**
  115302. * Creates a new AssetsManager
  115303. * @param scene defines the scene to work on
  115304. */
  115305. function AssetsManager(scene) {
  115306. this._isLoading = false;
  115307. this._tasks = new Array();
  115308. this._waitingTasksCount = 0;
  115309. this._totalTasksCount = 0;
  115310. /**
  115311. * Observable called when all tasks are processed
  115312. */
  115313. this.onTaskSuccessObservable = new BABYLON.Observable();
  115314. /**
  115315. * Observable called when a task had an error
  115316. */
  115317. this.onTaskErrorObservable = new BABYLON.Observable();
  115318. /**
  115319. * Observable called when a task is successful
  115320. */
  115321. this.onTasksDoneObservable = new BABYLON.Observable();
  115322. /**
  115323. * Observable called when a task is done (whatever the result is)
  115324. */
  115325. this.onProgressObservable = new BABYLON.Observable();
  115326. /**
  115327. * Gets or sets a boolean defining if the AssetsManager should use the default loading screen
  115328. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  115329. */
  115330. this.useDefaultLoadingScreen = true;
  115331. this._scene = scene;
  115332. }
  115333. /**
  115334. * Add a MeshAssetTask to the list of active tasks
  115335. * @param taskName defines the name of the new task
  115336. * @param meshesNames defines the name of meshes to load
  115337. * @param rootUrl defines the root url to use to locate files
  115338. * @param sceneFilename defines the filename of the scene file
  115339. * @returns a new MeshAssetTask object
  115340. */
  115341. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  115342. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  115343. this._tasks.push(task);
  115344. return task;
  115345. };
  115346. /**
  115347. * Add a TextFileAssetTask to the list of active tasks
  115348. * @param taskName defines the name of the new task
  115349. * @param url defines the url of the file to load
  115350. * @returns a new TextFileAssetTask object
  115351. */
  115352. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  115353. var task = new TextFileAssetTask(taskName, url);
  115354. this._tasks.push(task);
  115355. return task;
  115356. };
  115357. /**
  115358. * Add a BinaryFileAssetTask to the list of active tasks
  115359. * @param taskName defines the name of the new task
  115360. * @param url defines the url of the file to load
  115361. * @returns a new BinaryFileAssetTask object
  115362. */
  115363. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  115364. var task = new BinaryFileAssetTask(taskName, url);
  115365. this._tasks.push(task);
  115366. return task;
  115367. };
  115368. /**
  115369. * Add a ImageAssetTask to the list of active tasks
  115370. * @param taskName defines the name of the new task
  115371. * @param url defines the url of the file to load
  115372. * @returns a new ImageAssetTask object
  115373. */
  115374. AssetsManager.prototype.addImageTask = function (taskName, url) {
  115375. var task = new ImageAssetTask(taskName, url);
  115376. this._tasks.push(task);
  115377. return task;
  115378. };
  115379. /**
  115380. * Add a TextureAssetTask to the list of active tasks
  115381. * @param taskName defines the name of the new task
  115382. * @param url defines the url of the file to load
  115383. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  115384. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  115385. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  115386. * @returns a new TextureAssetTask object
  115387. */
  115388. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  115389. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  115390. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  115391. this._tasks.push(task);
  115392. return task;
  115393. };
  115394. /**
  115395. * Add a CubeTextureAssetTask to the list of active tasks
  115396. * @param taskName defines the name of the new task
  115397. * @param url defines the url of the file to load
  115398. * @param extensions defines the extension to use to load the cube map (can be null)
  115399. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  115400. * @param files defines the list of files to load (can be null)
  115401. * @returns a new CubeTextureAssetTask object
  115402. */
  115403. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  115404. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  115405. this._tasks.push(task);
  115406. return task;
  115407. };
  115408. /**
  115409. *
  115410. * Add a HDRCubeTextureAssetTask to the list of active tasks
  115411. * @param taskName defines the name of the new task
  115412. * @param url defines the url of the file to load
  115413. * @param size defines the size you want for the cubemap (can be null)
  115414. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  115415. * @param generateHarmonics defines if you want to automatically generate (true by default)
  115416. * @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)
  115417. * @param reserved Internal use only
  115418. * @returns a new HDRCubeTextureAssetTask object
  115419. */
  115420. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved) {
  115421. if (noMipmap === void 0) { noMipmap = false; }
  115422. if (generateHarmonics === void 0) { generateHarmonics = true; }
  115423. if (gammaSpace === void 0) { gammaSpace = false; }
  115424. if (reserved === void 0) { reserved = false; }
  115425. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved);
  115426. this._tasks.push(task);
  115427. return task;
  115428. };
  115429. /**
  115430. * Remove a task from the assets manager.
  115431. * @param task the task to remove
  115432. */
  115433. AssetsManager.prototype.removeTask = function (task) {
  115434. var index = this._tasks.indexOf(task);
  115435. if (index > -1) {
  115436. this._tasks.splice(index, 1);
  115437. }
  115438. };
  115439. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  115440. this._waitingTasksCount--;
  115441. try {
  115442. if (this.onProgress) {
  115443. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  115444. }
  115445. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  115446. }
  115447. catch (e) {
  115448. BABYLON.Tools.Error("Error running progress callbacks.");
  115449. console.log(e);
  115450. }
  115451. if (this._waitingTasksCount === 0) {
  115452. try {
  115453. if (this.onFinish) {
  115454. this.onFinish(this._tasks);
  115455. }
  115456. // Let's remove successfull tasks
  115457. var currentTasks = this._tasks.slice();
  115458. for (var _i = 0, currentTasks_1 = currentTasks; _i < currentTasks_1.length; _i++) {
  115459. var task = currentTasks_1[_i];
  115460. if (task.taskState === AssetTaskState.DONE) {
  115461. var index = this._tasks.indexOf(task);
  115462. if (index > -1) {
  115463. this._tasks.splice(index, 1);
  115464. }
  115465. }
  115466. }
  115467. this.onTasksDoneObservable.notifyObservers(this._tasks);
  115468. }
  115469. catch (e) {
  115470. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  115471. console.log(e);
  115472. }
  115473. this._isLoading = false;
  115474. this._scene.getEngine().hideLoadingUI();
  115475. }
  115476. };
  115477. AssetsManager.prototype._runTask = function (task) {
  115478. var _this = this;
  115479. var done = function () {
  115480. try {
  115481. if (_this.onTaskSuccess) {
  115482. _this.onTaskSuccess(task);
  115483. }
  115484. _this.onTaskSuccessObservable.notifyObservers(task);
  115485. _this._decreaseWaitingTasksCount(task);
  115486. }
  115487. catch (e) {
  115488. error("Error executing task success callbacks", e);
  115489. }
  115490. };
  115491. var error = function (message, exception) {
  115492. task._setErrorObject(message, exception);
  115493. if (_this.onTaskError) {
  115494. _this.onTaskError(task);
  115495. }
  115496. _this.onTaskErrorObservable.notifyObservers(task);
  115497. _this._decreaseWaitingTasksCount(task);
  115498. };
  115499. task.run(this._scene, done, error);
  115500. };
  115501. /**
  115502. * Reset the AssetsManager and remove all tasks
  115503. * @return the current instance of the AssetsManager
  115504. */
  115505. AssetsManager.prototype.reset = function () {
  115506. this._isLoading = false;
  115507. this._tasks = new Array();
  115508. return this;
  115509. };
  115510. /**
  115511. * Start the loading process
  115512. * @return the current instance of the AssetsManager
  115513. */
  115514. AssetsManager.prototype.load = function () {
  115515. if (this._isLoading) {
  115516. return this;
  115517. }
  115518. this._isLoading = true;
  115519. this._waitingTasksCount = this._tasks.length;
  115520. this._totalTasksCount = this._tasks.length;
  115521. if (this._waitingTasksCount === 0) {
  115522. this._isLoading = false;
  115523. if (this.onFinish) {
  115524. this.onFinish(this._tasks);
  115525. }
  115526. this.onTasksDoneObservable.notifyObservers(this._tasks);
  115527. return this;
  115528. }
  115529. if (this.useDefaultLoadingScreen) {
  115530. this._scene.getEngine().displayLoadingUI();
  115531. }
  115532. for (var index = 0; index < this._tasks.length; index++) {
  115533. var task = this._tasks[index];
  115534. if (task.taskState === AssetTaskState.INIT) {
  115535. this._runTask(task);
  115536. }
  115537. }
  115538. return this;
  115539. };
  115540. return AssetsManager;
  115541. }());
  115542. BABYLON.AssetsManager = AssetsManager;
  115543. })(BABYLON || (BABYLON = {}));
  115544. //# sourceMappingURL=babylon.assetsManager.js.map
  115545. var BABYLON;
  115546. (function (BABYLON) {
  115547. var serializedGeometries = [];
  115548. var serializeGeometry = function (geometry, serializationGeometries) {
  115549. if (serializedGeometries[geometry.id]) {
  115550. return;
  115551. }
  115552. if (geometry.doNotSerialize) {
  115553. return;
  115554. }
  115555. if (geometry instanceof BABYLON.BoxGeometry) {
  115556. serializationGeometries.boxes.push(geometry.serialize());
  115557. }
  115558. else if (geometry instanceof BABYLON.SphereGeometry) {
  115559. serializationGeometries.spheres.push(geometry.serialize());
  115560. }
  115561. else if (geometry instanceof BABYLON.CylinderGeometry) {
  115562. serializationGeometries.cylinders.push(geometry.serialize());
  115563. }
  115564. else if (geometry instanceof BABYLON.TorusGeometry) {
  115565. serializationGeometries.toruses.push(geometry.serialize());
  115566. }
  115567. else if (geometry instanceof BABYLON.GroundGeometry) {
  115568. serializationGeometries.grounds.push(geometry.serialize());
  115569. }
  115570. else if (geometry instanceof BABYLON.Plane) {
  115571. serializationGeometries.planes.push(geometry.serialize());
  115572. }
  115573. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  115574. serializationGeometries.torusKnots.push(geometry.serialize());
  115575. }
  115576. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  115577. throw new Error("Unknown primitive type");
  115578. }
  115579. else {
  115580. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  115581. }
  115582. serializedGeometries[geometry.id] = true;
  115583. };
  115584. var serializeMesh = function (mesh, serializationScene) {
  115585. var serializationObject = {};
  115586. // Geometry
  115587. var geometry = mesh._geometry;
  115588. if (geometry) {
  115589. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  115590. // 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
  115591. serializeGeometry(geometry, serializationScene.geometries);
  115592. }
  115593. }
  115594. // Custom
  115595. if (mesh.serialize) {
  115596. mesh.serialize(serializationObject);
  115597. }
  115598. return serializationObject;
  115599. };
  115600. var finalizeSingleMesh = function (mesh, serializationObject) {
  115601. //only works if the mesh is already loaded
  115602. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  115603. //serialize material
  115604. if (mesh.material) {
  115605. if (mesh.material instanceof BABYLON.MultiMaterial) {
  115606. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  115607. serializationObject.materials = serializationObject.materials || [];
  115608. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  115609. serializationObject.multiMaterials.push(mesh.material.serialize());
  115610. var _loop_1 = function (submaterial) {
  115611. if (submaterial) {
  115612. if (!serializationObject.materials.some(function (mat) { return (mat.id === submaterial.id); })) {
  115613. serializationObject.materials.push(submaterial.serialize());
  115614. }
  115615. }
  115616. };
  115617. for (var _i = 0, _a = mesh.material.subMaterials; _i < _a.length; _i++) {
  115618. var submaterial = _a[_i];
  115619. _loop_1(submaterial);
  115620. }
  115621. }
  115622. }
  115623. else {
  115624. serializationObject.materials = serializationObject.materials || [];
  115625. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  115626. serializationObject.materials.push(mesh.material.serialize());
  115627. }
  115628. }
  115629. }
  115630. //serialize geometry
  115631. var geometry = mesh._geometry;
  115632. if (geometry) {
  115633. if (!serializationObject.geometries) {
  115634. serializationObject.geometries = {};
  115635. serializationObject.geometries.boxes = [];
  115636. serializationObject.geometries.spheres = [];
  115637. serializationObject.geometries.cylinders = [];
  115638. serializationObject.geometries.toruses = [];
  115639. serializationObject.geometries.grounds = [];
  115640. serializationObject.geometries.planes = [];
  115641. serializationObject.geometries.torusKnots = [];
  115642. serializationObject.geometries.vertexData = [];
  115643. }
  115644. serializeGeometry(geometry, serializationObject.geometries);
  115645. }
  115646. // Skeletons
  115647. if (mesh.skeleton) {
  115648. serializationObject.skeletons = serializationObject.skeletons || [];
  115649. serializationObject.skeletons.push(mesh.skeleton.serialize());
  115650. }
  115651. //serialize the actual mesh
  115652. serializationObject.meshes = serializationObject.meshes || [];
  115653. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  115654. }
  115655. };
  115656. /**
  115657. * Class used to serialize a scene into a string
  115658. */
  115659. var SceneSerializer = /** @class */ (function () {
  115660. function SceneSerializer() {
  115661. }
  115662. /**
  115663. * Clear cache used by a previous serialization
  115664. */
  115665. SceneSerializer.ClearCache = function () {
  115666. serializedGeometries = [];
  115667. };
  115668. /**
  115669. * Serialize a scene into a JSON compatible object
  115670. * @param scene defines the scene to serialize
  115671. * @returns a JSON compatible object
  115672. */
  115673. SceneSerializer.Serialize = function (scene) {
  115674. var serializationObject = {};
  115675. SceneSerializer.ClearCache();
  115676. // Scene
  115677. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  115678. serializationObject.autoClear = scene.autoClear;
  115679. serializationObject.clearColor = scene.clearColor.asArray();
  115680. serializationObject.ambientColor = scene.ambientColor.asArray();
  115681. serializationObject.gravity = scene.gravity.asArray();
  115682. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  115683. serializationObject.workerCollisions = scene.workerCollisions;
  115684. // Fog
  115685. if (scene.fogMode && scene.fogMode !== 0) {
  115686. serializationObject.fogMode = scene.fogMode;
  115687. serializationObject.fogColor = scene.fogColor.asArray();
  115688. serializationObject.fogStart = scene.fogStart;
  115689. serializationObject.fogEnd = scene.fogEnd;
  115690. serializationObject.fogDensity = scene.fogDensity;
  115691. }
  115692. //Physics
  115693. if (scene.isPhysicsEnabled()) {
  115694. var physicEngine = scene.getPhysicsEngine();
  115695. if (physicEngine) {
  115696. serializationObject.physicsEnabled = true;
  115697. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  115698. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  115699. }
  115700. }
  115701. // Metadata
  115702. if (scene.metadata) {
  115703. serializationObject.metadata = scene.metadata;
  115704. }
  115705. // Morph targets
  115706. serializationObject.morphTargetManagers = [];
  115707. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  115708. var abstractMesh = _a[_i];
  115709. var manager = abstractMesh.morphTargetManager;
  115710. if (manager) {
  115711. serializationObject.morphTargetManagers.push(manager.serialize());
  115712. }
  115713. }
  115714. // Lights
  115715. serializationObject.lights = [];
  115716. var index;
  115717. var light;
  115718. for (index = 0; index < scene.lights.length; index++) {
  115719. light = scene.lights[index];
  115720. if (!light.doNotSerialize) {
  115721. serializationObject.lights.push(light.serialize());
  115722. }
  115723. }
  115724. // Cameras
  115725. serializationObject.cameras = [];
  115726. for (index = 0; index < scene.cameras.length; index++) {
  115727. var camera = scene.cameras[index];
  115728. if (!camera.doNotSerialize) {
  115729. serializationObject.cameras.push(camera.serialize());
  115730. }
  115731. }
  115732. if (scene.activeCamera) {
  115733. serializationObject.activeCameraID = scene.activeCamera.id;
  115734. }
  115735. // Animations
  115736. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  115737. // Reflection probes
  115738. if (scene.reflectionProbes && scene.reflectionProbes.length > 0) {
  115739. serializationObject.reflectionProbes = [];
  115740. for (index = 0; index < scene.reflectionProbes.length; index++) {
  115741. var reflectionProbe = scene.reflectionProbes[index];
  115742. serializationObject.reflectionProbes.push(reflectionProbe.serialize());
  115743. }
  115744. }
  115745. // Materials
  115746. serializationObject.materials = [];
  115747. serializationObject.multiMaterials = [];
  115748. var material;
  115749. for (index = 0; index < scene.materials.length; index++) {
  115750. material = scene.materials[index];
  115751. if (!material.doNotSerialize) {
  115752. serializationObject.materials.push(material.serialize());
  115753. }
  115754. }
  115755. // MultiMaterials
  115756. serializationObject.multiMaterials = [];
  115757. for (index = 0; index < scene.multiMaterials.length; index++) {
  115758. var multiMaterial = scene.multiMaterials[index];
  115759. serializationObject.multiMaterials.push(multiMaterial.serialize());
  115760. }
  115761. // Environment texture
  115762. if (scene.environmentTexture) {
  115763. serializationObject.environmentTexture = scene.environmentTexture.name;
  115764. }
  115765. // Skeletons
  115766. serializationObject.skeletons = [];
  115767. for (index = 0; index < scene.skeletons.length; index++) {
  115768. var skeleton = scene.skeletons[index];
  115769. if (!skeleton.doNotSerialize) {
  115770. serializationObject.skeletons.push(skeleton.serialize());
  115771. }
  115772. }
  115773. // Transform nodes
  115774. serializationObject.transformNodes = [];
  115775. for (index = 0; index < scene.transformNodes.length; index++) {
  115776. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  115777. }
  115778. // Geometries
  115779. serializationObject.geometries = {};
  115780. serializationObject.geometries.boxes = [];
  115781. serializationObject.geometries.spheres = [];
  115782. serializationObject.geometries.cylinders = [];
  115783. serializationObject.geometries.toruses = [];
  115784. serializationObject.geometries.grounds = [];
  115785. serializationObject.geometries.planes = [];
  115786. serializationObject.geometries.torusKnots = [];
  115787. serializationObject.geometries.vertexData = [];
  115788. serializedGeometries = [];
  115789. var geometries = scene.getGeometries();
  115790. for (index = 0; index < geometries.length; index++) {
  115791. var geometry = geometries[index];
  115792. if (geometry.isReady()) {
  115793. serializeGeometry(geometry, serializationObject.geometries);
  115794. }
  115795. }
  115796. // Meshes
  115797. serializationObject.meshes = [];
  115798. for (index = 0; index < scene.meshes.length; index++) {
  115799. var abstractMesh = scene.meshes[index];
  115800. if (abstractMesh instanceof BABYLON.Mesh) {
  115801. var mesh = abstractMesh;
  115802. if (!mesh.doNotSerialize) {
  115803. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  115804. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  115805. }
  115806. }
  115807. }
  115808. }
  115809. // Particles Systems
  115810. serializationObject.particleSystems = [];
  115811. for (index = 0; index < scene.particleSystems.length; index++) {
  115812. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  115813. }
  115814. // Action Manager
  115815. if (scene.actionManager) {
  115816. serializationObject.actions = scene.actionManager.serialize("scene");
  115817. }
  115818. // Components
  115819. for (var _b = 0, _c = scene._serializableComponents; _b < _c.length; _b++) {
  115820. var component = _c[_b];
  115821. component.serialize(serializationObject);
  115822. }
  115823. return serializationObject;
  115824. };
  115825. /**
  115826. * Serialize a mesh into a JSON compatible object
  115827. * @param toSerialize defines the mesh to serialize
  115828. * @param withParents defines if parents must be serialized as well
  115829. * @param withChildren defines if children must be serialized as well
  115830. * @returns a JSON compatible object
  115831. */
  115832. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  115833. if (withParents === void 0) { withParents = false; }
  115834. if (withChildren === void 0) { withChildren = false; }
  115835. var serializationObject = {};
  115836. SceneSerializer.ClearCache();
  115837. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  115838. if (withParents || withChildren) {
  115839. //deliberate for loop! not for each, appended should be processed as well.
  115840. for (var i = 0; i < toSerialize.length; ++i) {
  115841. if (withChildren) {
  115842. toSerialize[i].getDescendants().forEach(function (node) {
  115843. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  115844. toSerialize.push(node);
  115845. }
  115846. });
  115847. }
  115848. //make sure the array doesn't contain the object already
  115849. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  115850. toSerialize.push(toSerialize[i].parent);
  115851. }
  115852. }
  115853. }
  115854. toSerialize.forEach(function (mesh) {
  115855. finalizeSingleMesh(mesh, serializationObject);
  115856. });
  115857. return serializationObject;
  115858. };
  115859. return SceneSerializer;
  115860. }());
  115861. BABYLON.SceneSerializer = SceneSerializer;
  115862. })(BABYLON || (BABYLON = {}));
  115863. //# sourceMappingURL=babylon.sceneSerializer.js.map
  115864. var BABYLON;
  115865. (function (BABYLON) {
  115866. BABYLON.AbstractScene.prototype.removeReflectionProbe = function (toRemove) {
  115867. if (!this.reflectionProbes) {
  115868. return -1;
  115869. }
  115870. var index = this.reflectionProbes.indexOf(toRemove);
  115871. if (index !== -1) {
  115872. this.reflectionProbes.splice(index, 1);
  115873. }
  115874. return index;
  115875. };
  115876. BABYLON.AbstractScene.prototype.addReflectionProbe = function (newReflectionProbe) {
  115877. if (!this.reflectionProbes) {
  115878. this.reflectionProbes = [];
  115879. }
  115880. this.reflectionProbes.push(newReflectionProbe);
  115881. };
  115882. /**
  115883. * Class used to generate realtime reflection / refraction cube textures
  115884. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  115885. */
  115886. var ReflectionProbe = /** @class */ (function () {
  115887. /**
  115888. * Creates a new reflection probe
  115889. * @param name defines the name of the probe
  115890. * @param size defines the texture resolution (for each face)
  115891. * @param scene defines the hosting scene
  115892. * @param generateMipMaps defines if mip maps should be generated automatically (true by default)
  115893. * @param useFloat defines if HDR data (flaot data) should be used to store colors (false by default)
  115894. */
  115895. function ReflectionProbe(
  115896. /** defines the name of the probe */
  115897. name, size, scene, generateMipMaps, useFloat) {
  115898. if (generateMipMaps === void 0) { generateMipMaps = true; }
  115899. if (useFloat === void 0) { useFloat = false; }
  115900. var _this = this;
  115901. this.name = name;
  115902. this._viewMatrix = BABYLON.Matrix.Identity();
  115903. this._target = BABYLON.Vector3.Zero();
  115904. this._add = BABYLON.Vector3.Zero();
  115905. this._invertYAxis = false;
  115906. /** Gets or sets probe position (center of the cube map) */
  115907. this.position = BABYLON.Vector3.Zero();
  115908. this._scene = scene;
  115909. // Create the scene field if not exist.
  115910. if (!this._scene.reflectionProbes) {
  115911. this._scene.reflectionProbes = new Array();
  115912. }
  115913. this._scene.reflectionProbes.push(this);
  115914. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, useFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  115915. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  115916. switch (faceIndex) {
  115917. case 0:
  115918. _this._add.copyFromFloats(1, 0, 0);
  115919. break;
  115920. case 1:
  115921. _this._add.copyFromFloats(-1, 0, 0);
  115922. break;
  115923. case 2:
  115924. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  115925. break;
  115926. case 3:
  115927. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  115928. break;
  115929. case 4:
  115930. _this._add.copyFromFloats(0, 0, 1);
  115931. break;
  115932. case 5:
  115933. _this._add.copyFromFloats(0, 0, -1);
  115934. break;
  115935. }
  115936. if (_this._attachedMesh) {
  115937. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  115938. }
  115939. _this.position.addToRef(_this._add, _this._target);
  115940. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  115941. if (scene.activeCamera) {
  115942. _this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  115943. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  115944. }
  115945. scene._forcedViewPosition = _this.position;
  115946. });
  115947. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  115948. scene._forcedViewPosition = null;
  115949. scene.updateTransformMatrix(true);
  115950. });
  115951. }
  115952. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  115953. /** Gets or sets the number of samples to use for multi-sampling (0 by default). Required WebGL2 */
  115954. get: function () {
  115955. return this._renderTargetTexture.samples;
  115956. },
  115957. set: function (value) {
  115958. this._renderTargetTexture.samples = value;
  115959. },
  115960. enumerable: true,
  115961. configurable: true
  115962. });
  115963. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  115964. /** Gets or sets the refresh rate to use (on every frame by default) */
  115965. get: function () {
  115966. return this._renderTargetTexture.refreshRate;
  115967. },
  115968. set: function (value) {
  115969. this._renderTargetTexture.refreshRate = value;
  115970. },
  115971. enumerable: true,
  115972. configurable: true
  115973. });
  115974. /**
  115975. * Gets the hosting scene
  115976. * @returns a Scene
  115977. */
  115978. ReflectionProbe.prototype.getScene = function () {
  115979. return this._scene;
  115980. };
  115981. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  115982. /** Gets the internal CubeTexture used to render to */
  115983. get: function () {
  115984. return this._renderTargetTexture;
  115985. },
  115986. enumerable: true,
  115987. configurable: true
  115988. });
  115989. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  115990. /** Gets the list of meshes to render */
  115991. get: function () {
  115992. return this._renderTargetTexture.renderList;
  115993. },
  115994. enumerable: true,
  115995. configurable: true
  115996. });
  115997. /**
  115998. * Attach the probe to a specific mesh (Rendering will be done from attached mesh's position)
  115999. * @param mesh defines the mesh to attach to
  116000. */
  116001. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  116002. this._attachedMesh = mesh;
  116003. };
  116004. /**
  116005. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups
  116006. * @param renderingGroupId The rendering group id corresponding to its index
  116007. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  116008. */
  116009. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  116010. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  116011. };
  116012. /**
  116013. * Clean all associated resources
  116014. */
  116015. ReflectionProbe.prototype.dispose = function () {
  116016. var index = this._scene.reflectionProbes.indexOf(this);
  116017. if (index !== -1) {
  116018. // Remove from the scene if found
  116019. this._scene.reflectionProbes.splice(index, 1);
  116020. }
  116021. if (this._renderTargetTexture) {
  116022. this._renderTargetTexture.dispose();
  116023. this._renderTargetTexture = null;
  116024. }
  116025. };
  116026. /**
  116027. * Converts the reflection probe information to a readable string for debug purpose.
  116028. * @param fullDetails Supports for multiple levels of logging within scene loading
  116029. * @returns the human readable reflection probe info
  116030. */
  116031. ReflectionProbe.prototype.toString = function (fullDetails) {
  116032. var ret = "Name: " + this.name;
  116033. if (fullDetails) {
  116034. ret += ", position: " + this.position.toString();
  116035. if (this._attachedMesh) {
  116036. ret += ", attached mesh: " + this._attachedMesh.name;
  116037. }
  116038. }
  116039. return ret;
  116040. };
  116041. /**
  116042. * Get the class name of the relfection probe.
  116043. * @returns "ReflectionProbe"
  116044. */
  116045. ReflectionProbe.prototype.getClassName = function () {
  116046. return "ReflectionProbe";
  116047. };
  116048. /**
  116049. * Serialize the reflection probe to a JSON representation we can easily use in the resepective Parse function.
  116050. * @returns The JSON representation of the texture
  116051. */
  116052. ReflectionProbe.prototype.serialize = function () {
  116053. var serializationObject = BABYLON.SerializationHelper.Serialize(this, this._renderTargetTexture.serialize());
  116054. serializationObject.isReflectionProbe = true;
  116055. return serializationObject;
  116056. };
  116057. /**
  116058. * Parse the JSON representation of a reflection probe in order to recreate the reflection probe in the given scene.
  116059. * @param parsedReflectionProbe Define the JSON representation of the reflection probe
  116060. * @param scene Define the scene the parsed reflection probe should be instantiated in
  116061. * @param rootUrl Define the root url of the parsing sequence in the case of relative dependencies
  116062. * @returns The parsed reflection probe if successful
  116063. */
  116064. ReflectionProbe.Parse = function (parsedReflectionProbe, scene, rootUrl) {
  116065. var reflectionProbe = null;
  116066. if (scene.reflectionProbes) {
  116067. for (var index = 0; index < scene.reflectionProbes.length; index++) {
  116068. var rp = scene.reflectionProbes[index];
  116069. if (rp.name === parsedReflectionProbe.name) {
  116070. reflectionProbe = rp;
  116071. break;
  116072. }
  116073. }
  116074. }
  116075. reflectionProbe = BABYLON.SerializationHelper.Parse(function () { return reflectionProbe || new ReflectionProbe(parsedReflectionProbe.name, parsedReflectionProbe.renderTargetSize, scene, parsedReflectionProbe._generateMipMaps); }, parsedReflectionProbe, scene, rootUrl);
  116076. reflectionProbe.cubeTexture._waitingRenderList = parsedReflectionProbe.renderList;
  116077. if (parsedReflectionProbe._attachedMesh) {
  116078. reflectionProbe.attachToMesh(scene.getMeshByID(parsedReflectionProbe._attachedMesh));
  116079. }
  116080. return reflectionProbe;
  116081. };
  116082. __decorate([
  116083. BABYLON.serializeAsMeshReference()
  116084. ], ReflectionProbe.prototype, "_attachedMesh", void 0);
  116085. __decorate([
  116086. BABYLON.serializeAsVector3()
  116087. ], ReflectionProbe.prototype, "position", void 0);
  116088. return ReflectionProbe;
  116089. }());
  116090. BABYLON.ReflectionProbe = ReflectionProbe;
  116091. })(BABYLON || (BABYLON = {}));
  116092. //# sourceMappingURL=babylon.reflectionProbe.js.map
  116093. var BABYLON;
  116094. (function (BABYLON) {
  116095. /**
  116096. * Defines the layer scene component responsible to manage any layers
  116097. * in a given scene.
  116098. */
  116099. var LayerSceneComponent = /** @class */ (function () {
  116100. /**
  116101. * Creates a new instance of the component for the given scene
  116102. * @param scene Defines the scene to register the component in
  116103. */
  116104. function LayerSceneComponent(scene) {
  116105. /**
  116106. * The component name helpfull to identify the component in the list of scene components.
  116107. */
  116108. this.name = BABYLON.SceneComponentConstants.NAME_LAYER;
  116109. this.scene = scene;
  116110. this._engine = scene.getEngine();
  116111. scene.layers = new Array();
  116112. }
  116113. /**
  116114. * Registers the component in a given scene
  116115. */
  116116. LayerSceneComponent.prototype.register = function () {
  116117. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER, this, this._drawCameraBackground);
  116118. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER, this, this._drawCameraForeground);
  116119. this.scene._beforeRenderTargetDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORERENDERTARGETDRAW_LAYER, this, this._drawRenderTargetBackground);
  116120. this.scene._afterRenderTargetDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERTARGETDRAW_LAYER, this, this._drawRenderTargetForeground);
  116121. };
  116122. /**
  116123. * Rebuilds the elements related to this component in case of
  116124. * context lost for instance.
  116125. */
  116126. LayerSceneComponent.prototype.rebuild = function () {
  116127. var layers = this.scene.layers;
  116128. for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
  116129. var layer = layers_1[_i];
  116130. layer._rebuild();
  116131. }
  116132. };
  116133. /**
  116134. * Disposes the component and the associated ressources.
  116135. */
  116136. LayerSceneComponent.prototype.dispose = function () {
  116137. var layers = this.scene.layers;
  116138. while (layers.length) {
  116139. layers[0].dispose();
  116140. }
  116141. };
  116142. LayerSceneComponent.prototype._draw = function (predicate) {
  116143. var layers = this.scene.layers;
  116144. if (layers.length) {
  116145. this._engine.setDepthBuffer(false);
  116146. for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
  116147. var layer = layers_2[_i];
  116148. if (predicate(layer)) {
  116149. layer.render();
  116150. }
  116151. }
  116152. this._engine.setDepthBuffer(true);
  116153. }
  116154. };
  116155. LayerSceneComponent.prototype._drawCameraPredicate = function (layer, isBackground, cameraLayerMask) {
  116156. return !layer.renderOnlyInRenderTargetTextures &&
  116157. layer.isBackground === isBackground &&
  116158. ((layer.layerMask & cameraLayerMask) !== 0);
  116159. };
  116160. LayerSceneComponent.prototype._drawCameraBackground = function (camera) {
  116161. var _this = this;
  116162. this._draw(function (layer) {
  116163. return _this._drawCameraPredicate(layer, true, camera.layerMask);
  116164. });
  116165. };
  116166. LayerSceneComponent.prototype._drawCameraForeground = function (camera) {
  116167. var _this = this;
  116168. this._draw(function (layer) {
  116169. return _this._drawCameraPredicate(layer, false, camera.layerMask);
  116170. });
  116171. };
  116172. LayerSceneComponent.prototype._drawRenderTargetPredicate = function (layer, isBackground, cameraLayerMask, renderTargetTexture) {
  116173. return (layer.renderTargetTextures.length > 0) &&
  116174. layer.isBackground === isBackground &&
  116175. (layer.renderTargetTextures.indexOf(renderTargetTexture) > -1) &&
  116176. ((layer.layerMask & cameraLayerMask) !== 0);
  116177. };
  116178. LayerSceneComponent.prototype._drawRenderTargetBackground = function (renderTarget) {
  116179. var _this = this;
  116180. this._draw(function (layer) {
  116181. return _this._drawRenderTargetPredicate(layer, true, _this.scene.activeCamera.layerMask, renderTarget);
  116182. });
  116183. };
  116184. LayerSceneComponent.prototype._drawRenderTargetForeground = function (renderTarget) {
  116185. var _this = this;
  116186. this._draw(function (layer) {
  116187. return _this._drawRenderTargetPredicate(layer, false, _this.scene.activeCamera.layerMask, renderTarget);
  116188. });
  116189. };
  116190. return LayerSceneComponent;
  116191. }());
  116192. BABYLON.LayerSceneComponent = LayerSceneComponent;
  116193. })(BABYLON || (BABYLON = {}));
  116194. //# sourceMappingURL=babylon.layerSceneComponent.js.map
  116195. var BABYLON;
  116196. (function (BABYLON) {
  116197. /**
  116198. * This represents a full screen 2d layer.
  116199. * This can be useful to display a picture in the background of your scene for instance.
  116200. * @see https://www.babylonjs-playground.com/#08A2BS#1
  116201. */
  116202. var Layer = /** @class */ (function () {
  116203. /**
  116204. * Instantiates a new layer.
  116205. * This represents a full screen 2d layer.
  116206. * This can be useful to display a picture in the background of your scene for instance.
  116207. * @see https://www.babylonjs-playground.com/#08A2BS#1
  116208. * @param name Define the name of the layer in the scene
  116209. * @param imgUrl Define the url of the texture to display in the layer
  116210. * @param scene Define the scene the layer belongs to
  116211. * @param isBackground Defines whether the layer is displayed in front or behind the scene
  116212. * @param color Defines a color for the layer
  116213. */
  116214. function Layer(
  116215. /**
  116216. * Define the name of the layer.
  116217. */
  116218. name, imgUrl, scene, isBackground, color) {
  116219. this.name = name;
  116220. /**
  116221. * Define the scale of the layer in order to zoom in out of the texture.
  116222. */
  116223. this.scale = new BABYLON.Vector2(1, 1);
  116224. /**
  116225. * Define an offset for the layer in order to shift the texture.
  116226. */
  116227. this.offset = new BABYLON.Vector2(0, 0);
  116228. /**
  116229. * Define the alpha blending mode used in the layer in case the texture or color has an alpha.
  116230. */
  116231. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  116232. /**
  116233. * Define a mask to restrict the layer to only some of the scene cameras.
  116234. */
  116235. this.layerMask = 0x0FFFFFFF;
  116236. /**
  116237. * Define the list of render target the layer is visible into.
  116238. */
  116239. this.renderTargetTextures = [];
  116240. /**
  116241. * Define if the layer is only used in renderTarget or if it also
  116242. * renders in the main frame buffer of the canvas.
  116243. */
  116244. this.renderOnlyInRenderTargetTextures = false;
  116245. this._vertexBuffers = {};
  116246. /**
  116247. * An event triggered when the layer is disposed.
  116248. */
  116249. this.onDisposeObservable = new BABYLON.Observable();
  116250. /**
  116251. * An event triggered before rendering the scene
  116252. */
  116253. this.onBeforeRenderObservable = new BABYLON.Observable();
  116254. /**
  116255. * An event triggered after rendering the scene
  116256. */
  116257. this.onAfterRenderObservable = new BABYLON.Observable();
  116258. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  116259. this.isBackground = isBackground === undefined ? true : isBackground;
  116260. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  116261. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  116262. var layerComponent = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LAYER);
  116263. if (!layerComponent) {
  116264. layerComponent = new BABYLON.LayerSceneComponent(this._scene);
  116265. this._scene._addComponent(layerComponent);
  116266. }
  116267. this._scene.layers.push(this);
  116268. var engine = this._scene.getEngine();
  116269. // VBO
  116270. var vertices = [];
  116271. vertices.push(1, 1);
  116272. vertices.push(-1, 1);
  116273. vertices.push(-1, -1);
  116274. vertices.push(1, -1);
  116275. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  116276. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  116277. this._createIndexBuffer();
  116278. // Effects
  116279. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  116280. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  116281. }
  116282. Object.defineProperty(Layer.prototype, "onDispose", {
  116283. /**
  116284. * Back compatibility with callback before the onDisposeObservable existed.
  116285. * The set callback will be triggered when the layer has been disposed.
  116286. */
  116287. set: function (callback) {
  116288. if (this._onDisposeObserver) {
  116289. this.onDisposeObservable.remove(this._onDisposeObserver);
  116290. }
  116291. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  116292. },
  116293. enumerable: true,
  116294. configurable: true
  116295. });
  116296. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  116297. /**
  116298. * Back compatibility with callback before the onBeforeRenderObservable existed.
  116299. * The set callback will be triggered just before rendering the layer.
  116300. */
  116301. set: function (callback) {
  116302. if (this._onBeforeRenderObserver) {
  116303. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  116304. }
  116305. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  116306. },
  116307. enumerable: true,
  116308. configurable: true
  116309. });
  116310. Object.defineProperty(Layer.prototype, "onAfterRender", {
  116311. /**
  116312. * Back compatibility with callback before the onAfterRenderObservable existed.
  116313. * The set callback will be triggered just after rendering the layer.
  116314. */
  116315. set: function (callback) {
  116316. if (this._onAfterRenderObserver) {
  116317. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  116318. }
  116319. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  116320. },
  116321. enumerable: true,
  116322. configurable: true
  116323. });
  116324. Layer.prototype._createIndexBuffer = function () {
  116325. var engine = this._scene.getEngine();
  116326. // Indices
  116327. var indices = [];
  116328. indices.push(0);
  116329. indices.push(1);
  116330. indices.push(2);
  116331. indices.push(0);
  116332. indices.push(2);
  116333. indices.push(3);
  116334. this._indexBuffer = engine.createIndexBuffer(indices);
  116335. };
  116336. /** @hidden */
  116337. Layer.prototype._rebuild = function () {
  116338. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  116339. if (vb) {
  116340. vb._rebuild();
  116341. }
  116342. this._createIndexBuffer();
  116343. };
  116344. /**
  116345. * Renders the layer in the scene.
  116346. */
  116347. Layer.prototype.render = function () {
  116348. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  116349. // Check
  116350. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady()) {
  116351. return;
  116352. }
  116353. var engine = this._scene.getEngine();
  116354. this.onBeforeRenderObservable.notifyObservers(this);
  116355. // Render
  116356. engine.enableEffect(currentEffect);
  116357. engine.setState(false);
  116358. // Texture
  116359. currentEffect.setTexture("textureSampler", this.texture);
  116360. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  116361. // Color
  116362. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  116363. // Scale / offset
  116364. currentEffect.setVector2("offset", this.offset);
  116365. currentEffect.setVector2("scale", this.scale);
  116366. // VBOs
  116367. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  116368. // Draw order
  116369. if (!this.alphaTest) {
  116370. engine.setAlphaMode(this.alphaBlendingMode);
  116371. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  116372. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  116373. }
  116374. else {
  116375. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  116376. }
  116377. this.onAfterRenderObservable.notifyObservers(this);
  116378. };
  116379. /**
  116380. * Disposes and releases the associated ressources.
  116381. */
  116382. Layer.prototype.dispose = function () {
  116383. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  116384. if (vertexBuffer) {
  116385. vertexBuffer.dispose();
  116386. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  116387. }
  116388. if (this._indexBuffer) {
  116389. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  116390. this._indexBuffer = null;
  116391. }
  116392. if (this.texture) {
  116393. this.texture.dispose();
  116394. this.texture = null;
  116395. }
  116396. // Clean RTT list
  116397. this.renderTargetTextures = [];
  116398. // Remove from scene
  116399. var index = this._scene.layers.indexOf(this);
  116400. this._scene.layers.splice(index, 1);
  116401. // Callback
  116402. this.onDisposeObservable.notifyObservers(this);
  116403. this.onDisposeObservable.clear();
  116404. this.onAfterRenderObservable.clear();
  116405. this.onBeforeRenderObservable.clear();
  116406. };
  116407. return Layer;
  116408. }());
  116409. BABYLON.Layer = Layer;
  116410. })(BABYLON || (BABYLON = {}));
  116411. //# sourceMappingURL=babylon.layer.js.map
  116412. var BABYLON;
  116413. (function (BABYLON) {
  116414. /**
  116415. * Class used to host texture specific utilities
  116416. */
  116417. var TextureTools = /** @class */ (function () {
  116418. function TextureTools() {
  116419. }
  116420. /**
  116421. * Uses the GPU to create a copy texture rescaled at a given size
  116422. * @param texture Texture to copy from
  116423. * @param width defines the desired width
  116424. * @param height defines the desired height
  116425. * @param useBilinearMode defines if bilinear mode has to be used
  116426. * @return the generated texture
  116427. */
  116428. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  116429. if (useBilinearMode === void 0) { useBilinearMode = true; }
  116430. var scene = texture.getScene();
  116431. var engine = scene.getEngine();
  116432. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture.samplingMode, false);
  116433. rtt.wrapU = texture.wrapU;
  116434. rtt.wrapV = texture.wrapV;
  116435. rtt.uOffset = texture.uOffset;
  116436. rtt.vOffset = texture.vOffset;
  116437. rtt.uScale = texture.uScale;
  116438. rtt.vScale = texture.vScale;
  116439. rtt.uAng = texture.uAng;
  116440. rtt.vAng = texture.vAng;
  116441. rtt.wAng = texture.wAng;
  116442. rtt.coordinatesIndex = texture.coordinatesIndex;
  116443. rtt.level = texture.level;
  116444. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  116445. rtt._texture.isReady = false;
  116446. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  116447. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  116448. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  116449. passPostProcess.getEffect().executeWhenCompiled(function () {
  116450. passPostProcess.onApply = function (effect) {
  116451. effect.setTexture("textureSampler", texture);
  116452. };
  116453. var internalTexture = rtt.getInternalTexture();
  116454. if (internalTexture) {
  116455. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  116456. engine.unBindFramebuffer(internalTexture);
  116457. rtt.disposeFramebufferObjects();
  116458. passPostProcess.dispose();
  116459. internalTexture.isReady = true;
  116460. }
  116461. });
  116462. return rtt;
  116463. };
  116464. /**
  116465. * Gets an environment BRDF texture for a given scene
  116466. * @param scene defines the hosting scene
  116467. * @returns the environment BRDF texture
  116468. */
  116469. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  116470. if (!scene._environmentBRDFTexture) {
  116471. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  116472. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  116473. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  116474. scene._environmentBRDFTexture = texture;
  116475. }
  116476. return scene._environmentBRDFTexture;
  116477. };
  116478. 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=";
  116479. return TextureTools;
  116480. }());
  116481. BABYLON.TextureTools = TextureTools;
  116482. })(BABYLON || (BABYLON = {}));
  116483. //# sourceMappingURL=babylon.textureTools.js.map
  116484. var BABYLON;
  116485. (function (BABYLON) {
  116486. /**
  116487. * 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.
  116488. * @see http://doc.babylonjs.com/how_to/camera_behaviors#framing-behavior
  116489. */
  116490. var FramingBehavior = /** @class */ (function () {
  116491. function FramingBehavior() {
  116492. this._mode = FramingBehavior.FitFrustumSidesMode;
  116493. this._radiusScale = 1.0;
  116494. this._positionScale = 0.5;
  116495. this._defaultElevation = 0.3;
  116496. this._elevationReturnTime = 1500;
  116497. this._elevationReturnWaitTime = 1000;
  116498. this._zoomStopsAnimation = false;
  116499. this._framingTime = 1500;
  116500. /**
  116501. * Define if the behavior should automatically change the configured
  116502. * camera limits and sensibilities.
  116503. */
  116504. this.autoCorrectCameraLimitsAndSensibility = true;
  116505. this._isPointerDown = false;
  116506. this._lastInteractionTime = -Infinity;
  116507. // Framing control
  116508. this._animatables = new Array();
  116509. this._betaIsAnimating = false;
  116510. }
  116511. Object.defineProperty(FramingBehavior.prototype, "name", {
  116512. /**
  116513. * Gets the name of the behavior.
  116514. */
  116515. get: function () {
  116516. return "Framing";
  116517. },
  116518. enumerable: true,
  116519. configurable: true
  116520. });
  116521. Object.defineProperty(FramingBehavior.prototype, "mode", {
  116522. /**
  116523. * Gets current mode used by the behavior.
  116524. */
  116525. get: function () {
  116526. return this._mode;
  116527. },
  116528. /**
  116529. * Sets the current mode used by the behavior
  116530. */
  116531. set: function (mode) {
  116532. this._mode = mode;
  116533. },
  116534. enumerable: true,
  116535. configurable: true
  116536. });
  116537. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  116538. /**
  116539. * Gets the scale applied to the radius
  116540. */
  116541. get: function () {
  116542. return this._radiusScale;
  116543. },
  116544. /**
  116545. * Sets the scale applied to the radius (1 by default)
  116546. */
  116547. set: function (radius) {
  116548. this._radiusScale = radius;
  116549. },
  116550. enumerable: true,
  116551. configurable: true
  116552. });
  116553. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  116554. /**
  116555. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  116556. */
  116557. get: function () {
  116558. return this._positionScale;
  116559. },
  116560. /**
  116561. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  116562. */
  116563. set: function (scale) {
  116564. this._positionScale = scale;
  116565. },
  116566. enumerable: true,
  116567. configurable: true
  116568. });
  116569. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  116570. /**
  116571. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  116572. * behaviour is triggered, in radians.
  116573. */
  116574. get: function () {
  116575. return this._defaultElevation;
  116576. },
  116577. /**
  116578. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  116579. * behaviour is triggered, in radians.
  116580. */
  116581. set: function (elevation) {
  116582. this._defaultElevation = elevation;
  116583. },
  116584. enumerable: true,
  116585. configurable: true
  116586. });
  116587. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  116588. /**
  116589. * Gets the time (in milliseconds) taken to return to the default beta position.
  116590. * Negative value indicates camera should not return to default.
  116591. */
  116592. get: function () {
  116593. return this._elevationReturnTime;
  116594. },
  116595. /**
  116596. * Sets the time (in milliseconds) taken to return to the default beta position.
  116597. * Negative value indicates camera should not return to default.
  116598. */
  116599. set: function (speed) {
  116600. this._elevationReturnTime = speed;
  116601. },
  116602. enumerable: true,
  116603. configurable: true
  116604. });
  116605. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  116606. /**
  116607. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  116608. */
  116609. get: function () {
  116610. return this._elevationReturnWaitTime;
  116611. },
  116612. /**
  116613. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  116614. */
  116615. set: function (time) {
  116616. this._elevationReturnWaitTime = time;
  116617. },
  116618. enumerable: true,
  116619. configurable: true
  116620. });
  116621. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  116622. /**
  116623. * Gets the flag that indicates if user zooming should stop animation.
  116624. */
  116625. get: function () {
  116626. return this._zoomStopsAnimation;
  116627. },
  116628. /**
  116629. * Sets the flag that indicates if user zooming should stop animation.
  116630. */
  116631. set: function (flag) {
  116632. this._zoomStopsAnimation = flag;
  116633. },
  116634. enumerable: true,
  116635. configurable: true
  116636. });
  116637. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  116638. /**
  116639. * Gets the transition time when framing the mesh, in milliseconds
  116640. */
  116641. get: function () {
  116642. return this._framingTime;
  116643. },
  116644. /**
  116645. * Sets the transition time when framing the mesh, in milliseconds
  116646. */
  116647. set: function (time) {
  116648. this._framingTime = time;
  116649. },
  116650. enumerable: true,
  116651. configurable: true
  116652. });
  116653. /**
  116654. * Initializes the behavior.
  116655. */
  116656. FramingBehavior.prototype.init = function () {
  116657. // Do notihng
  116658. };
  116659. /**
  116660. * Attaches the behavior to its arc rotate camera.
  116661. * @param camera Defines the camera to attach the behavior to
  116662. */
  116663. FramingBehavior.prototype.attach = function (camera) {
  116664. var _this = this;
  116665. this._attachedCamera = camera;
  116666. var scene = this._attachedCamera.getScene();
  116667. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  116668. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  116669. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  116670. _this._isPointerDown = true;
  116671. return;
  116672. }
  116673. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  116674. _this._isPointerDown = false;
  116675. }
  116676. });
  116677. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  116678. if (mesh) {
  116679. _this.zoomOnMesh(mesh);
  116680. }
  116681. });
  116682. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  116683. // Stop the animation if there is user interaction and the animation should stop for this interaction
  116684. _this._applyUserInteraction();
  116685. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  116686. // back to the default position after a given timeout
  116687. _this._maintainCameraAboveGround();
  116688. });
  116689. };
  116690. /**
  116691. * Detaches the behavior from its current arc rotate camera.
  116692. */
  116693. FramingBehavior.prototype.detach = function () {
  116694. if (!this._attachedCamera) {
  116695. return;
  116696. }
  116697. var scene = this._attachedCamera.getScene();
  116698. if (this._onPrePointerObservableObserver) {
  116699. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  116700. }
  116701. if (this._onAfterCheckInputsObserver) {
  116702. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  116703. }
  116704. if (this._onMeshTargetChangedObserver) {
  116705. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  116706. }
  116707. this._attachedCamera = null;
  116708. };
  116709. /**
  116710. * Targets the given mesh and updates zoom level accordingly.
  116711. * @param mesh The mesh to target.
  116712. * @param radius Optional. If a cached radius position already exists, overrides default.
  116713. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  116714. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  116715. * @param onAnimationEnd Callback triggered at the end of the framing animation
  116716. */
  116717. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  116718. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  116719. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  116720. mesh.computeWorldMatrix(true);
  116721. var boundingBox = mesh.getBoundingInfo().boundingBox;
  116722. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  116723. };
  116724. /**
  116725. * Targets the given mesh with its children and updates zoom level accordingly.
  116726. * @param mesh The mesh to target.
  116727. * @param radius Optional. If a cached radius position already exists, overrides default.
  116728. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  116729. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  116730. * @param onAnimationEnd Callback triggered at the end of the framing animation
  116731. */
  116732. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  116733. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  116734. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  116735. mesh.computeWorldMatrix(true);
  116736. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  116737. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  116738. };
  116739. /**
  116740. * Targets the given meshes with their children and updates zoom level accordingly.
  116741. * @param meshes The mesh to target.
  116742. * @param radius Optional. If a cached radius position already exists, overrides default.
  116743. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  116744. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  116745. * @param onAnimationEnd Callback triggered at the end of the framing animation
  116746. */
  116747. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  116748. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  116749. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  116750. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  116751. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  116752. for (var i = 0; i < meshes.length; i++) {
  116753. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  116754. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  116755. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  116756. }
  116757. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  116758. };
  116759. /**
  116760. * Targets the bounding box info defined by its extends and updates zoom level accordingly.
  116761. * @param minimumWorld Determines the smaller position of the bounding box extend
  116762. * @param maximumWorld Determines the bigger position of the bounding box extend
  116763. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  116764. * @param onAnimationEnd Callback triggered at the end of the framing animation
  116765. */
  116766. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  116767. var _this = this;
  116768. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  116769. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  116770. var zoomTarget;
  116771. if (!this._attachedCamera) {
  116772. return;
  116773. }
  116774. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  116775. var bottom = minimumWorld.y;
  116776. var top = maximumWorld.y;
  116777. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  116778. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  116779. if (focusOnOriginXZ) {
  116780. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  116781. }
  116782. else {
  116783. var centerWorld = minimumWorld.add(radiusWorld);
  116784. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  116785. }
  116786. if (!this._vectorTransition) {
  116787. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  116788. }
  116789. this._betaIsAnimating = true;
  116790. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  116791. if (animatable) {
  116792. this._animatables.push(animatable);
  116793. }
  116794. // sets the radius and lower radius bounds
  116795. // Small delta ensures camera is not always at lower zoom limit.
  116796. var radius = 0;
  116797. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  116798. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  116799. if (this.autoCorrectCameraLimitsAndSensibility) {
  116800. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  116801. }
  116802. radius = position;
  116803. }
  116804. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  116805. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  116806. if (this.autoCorrectCameraLimitsAndSensibility && this._attachedCamera.lowerRadiusLimit === null) {
  116807. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  116808. }
  116809. }
  116810. // Set sensibilities
  116811. if (this.autoCorrectCameraLimitsAndSensibility) {
  116812. var extend = maximumWorld.subtract(minimumWorld).length();
  116813. this._attachedCamera.panningSensibility = 5000 / extend;
  116814. this._attachedCamera.wheelPrecision = 100 / radius;
  116815. }
  116816. // transition to new radius
  116817. if (!this._radiusTransition) {
  116818. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  116819. }
  116820. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  116821. _this.stopAllAnimations();
  116822. if (onAnimationEnd) {
  116823. onAnimationEnd();
  116824. }
  116825. if (_this._attachedCamera && _this._attachedCamera.useInputToRestoreState) {
  116826. _this._attachedCamera.storeState();
  116827. }
  116828. });
  116829. if (animatable) {
  116830. this._animatables.push(animatable);
  116831. }
  116832. };
  116833. /**
  116834. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  116835. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  116836. * frustum width.
  116837. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  116838. * to fully enclose the mesh in the viewing frustum.
  116839. */
  116840. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  116841. var size = maximumWorld.subtract(minimumWorld);
  116842. var boxVectorGlobalDiagonal = size.length();
  116843. var frustumSlope = this._getFrustumSlope();
  116844. // Formula for setting distance
  116845. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  116846. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  116847. // Horizon distance
  116848. var radius = radiusWithoutFraming * this._radiusScale;
  116849. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  116850. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  116851. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  116852. var camera = this._attachedCamera;
  116853. if (!camera) {
  116854. return 0;
  116855. }
  116856. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  116857. // Don't exceed the requested limit
  116858. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  116859. }
  116860. // Don't exceed the upper radius limit
  116861. if (camera.upperRadiusLimit) {
  116862. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  116863. }
  116864. return distance;
  116865. };
  116866. /**
  116867. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  116868. * is automatically returned to its default position (expected to be above ground plane).
  116869. */
  116870. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  116871. var _this = this;
  116872. if (this._elevationReturnTime < 0) {
  116873. return;
  116874. }
  116875. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  116876. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  116877. var limitBeta = Math.PI * 0.5;
  116878. // Bring the camera back up if below the ground plane
  116879. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  116880. this._betaIsAnimating = true;
  116881. //Transition to new position
  116882. this.stopAllAnimations();
  116883. if (!this._betaTransition) {
  116884. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  116885. }
  116886. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  116887. _this._clearAnimationLocks();
  116888. _this.stopAllAnimations();
  116889. });
  116890. if (animatabe) {
  116891. this._animatables.push(animatabe);
  116892. }
  116893. }
  116894. };
  116895. /**
  116896. * Returns the frustum slope based on the canvas ratio and camera FOV
  116897. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  116898. */
  116899. FramingBehavior.prototype._getFrustumSlope = function () {
  116900. // Calculate the viewport ratio
  116901. // Aspect Ratio is Height/Width.
  116902. var camera = this._attachedCamera;
  116903. if (!camera) {
  116904. return BABYLON.Vector2.Zero();
  116905. }
  116906. var engine = camera.getScene().getEngine();
  116907. var aspectRatio = engine.getAspectRatio(camera);
  116908. // Camera FOV is the vertical field of view (top-bottom) in radians.
  116909. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  116910. var frustumSlopeY = Math.tan(camera.fov / 2);
  116911. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  116912. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  116913. // along the forward vector.
  116914. var frustumSlopeX = frustumSlopeY * aspectRatio;
  116915. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  116916. };
  116917. /**
  116918. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  116919. */
  116920. FramingBehavior.prototype._clearAnimationLocks = function () {
  116921. this._betaIsAnimating = false;
  116922. };
  116923. /**
  116924. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  116925. */
  116926. FramingBehavior.prototype._applyUserInteraction = function () {
  116927. if (this.isUserIsMoving) {
  116928. this._lastInteractionTime = BABYLON.Tools.Now;
  116929. this.stopAllAnimations();
  116930. this._clearAnimationLocks();
  116931. }
  116932. };
  116933. /**
  116934. * Stops and removes all animations that have been applied to the camera
  116935. */
  116936. FramingBehavior.prototype.stopAllAnimations = function () {
  116937. if (this._attachedCamera) {
  116938. this._attachedCamera.animations = [];
  116939. }
  116940. while (this._animatables.length) {
  116941. if (this._animatables[0]) {
  116942. this._animatables[0].onAnimationEnd = null;
  116943. this._animatables[0].stop();
  116944. }
  116945. this._animatables.shift();
  116946. }
  116947. };
  116948. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  116949. /**
  116950. * Gets a value indicating if the user is moving the camera
  116951. */
  116952. get: function () {
  116953. if (!this._attachedCamera) {
  116954. return false;
  116955. }
  116956. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  116957. this._attachedCamera.inertialBetaOffset !== 0 ||
  116958. this._attachedCamera.inertialRadiusOffset !== 0 ||
  116959. this._attachedCamera.inertialPanningX !== 0 ||
  116960. this._attachedCamera.inertialPanningY !== 0 ||
  116961. this._isPointerDown;
  116962. },
  116963. enumerable: true,
  116964. configurable: true
  116965. });
  116966. /**
  116967. * The easing function used by animations
  116968. */
  116969. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  116970. /**
  116971. * The easing mode used by animations
  116972. */
  116973. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  116974. // Statics
  116975. /**
  116976. * The camera can move all the way towards the mesh.
  116977. */
  116978. FramingBehavior.IgnoreBoundsSizeMode = 0;
  116979. /**
  116980. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  116981. */
  116982. FramingBehavior.FitFrustumSidesMode = 1;
  116983. return FramingBehavior;
  116984. }());
  116985. BABYLON.FramingBehavior = FramingBehavior;
  116986. })(BABYLON || (BABYLON = {}));
  116987. //# sourceMappingURL=babylon.framingBehavior.js.map
  116988. var BABYLON;
  116989. (function (BABYLON) {
  116990. /**
  116991. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  116992. * @see http://doc.babylonjs.com/how_to/camera_behaviors#bouncing-behavior
  116993. */
  116994. var BouncingBehavior = /** @class */ (function () {
  116995. function BouncingBehavior() {
  116996. /**
  116997. * The duration of the animation, in milliseconds
  116998. */
  116999. this.transitionDuration = 450;
  117000. /**
  117001. * Length of the distance animated by the transition when lower radius is reached
  117002. */
  117003. this.lowerRadiusTransitionRange = 2;
  117004. /**
  117005. * Length of the distance animated by the transition when upper radius is reached
  117006. */
  117007. this.upperRadiusTransitionRange = -2;
  117008. this._autoTransitionRange = false;
  117009. // Animations
  117010. this._radiusIsAnimating = false;
  117011. this._radiusBounceTransition = null;
  117012. this._animatables = new Array();
  117013. }
  117014. Object.defineProperty(BouncingBehavior.prototype, "name", {
  117015. /**
  117016. * Gets the name of the behavior.
  117017. */
  117018. get: function () {
  117019. return "Bouncing";
  117020. },
  117021. enumerable: true,
  117022. configurable: true
  117023. });
  117024. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  117025. /**
  117026. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  117027. */
  117028. get: function () {
  117029. return this._autoTransitionRange;
  117030. },
  117031. /**
  117032. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  117033. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  117034. */
  117035. set: function (value) {
  117036. var _this = this;
  117037. if (this._autoTransitionRange === value) {
  117038. return;
  117039. }
  117040. this._autoTransitionRange = value;
  117041. var camera = this._attachedCamera;
  117042. if (!camera) {
  117043. return;
  117044. }
  117045. if (value) {
  117046. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  117047. if (!mesh) {
  117048. return;
  117049. }
  117050. mesh.computeWorldMatrix(true);
  117051. var diagonal = mesh.getBoundingInfo().diagonalLength;
  117052. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  117053. _this.upperRadiusTransitionRange = diagonal * 0.05;
  117054. });
  117055. }
  117056. else if (this._onMeshTargetChangedObserver) {
  117057. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  117058. }
  117059. },
  117060. enumerable: true,
  117061. configurable: true
  117062. });
  117063. /**
  117064. * Initializes the behavior.
  117065. */
  117066. BouncingBehavior.prototype.init = function () {
  117067. // Do notihng
  117068. };
  117069. /**
  117070. * Attaches the behavior to its arc rotate camera.
  117071. * @param camera Defines the camera to attach the behavior to
  117072. */
  117073. BouncingBehavior.prototype.attach = function (camera) {
  117074. var _this = this;
  117075. this._attachedCamera = camera;
  117076. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  117077. if (!_this._attachedCamera) {
  117078. return;
  117079. }
  117080. // Add the bounce animation to the lower radius limit
  117081. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  117082. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  117083. }
  117084. // Add the bounce animation to the upper radius limit
  117085. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  117086. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  117087. }
  117088. });
  117089. };
  117090. /**
  117091. * Detaches the behavior from its current arc rotate camera.
  117092. */
  117093. BouncingBehavior.prototype.detach = function () {
  117094. if (!this._attachedCamera) {
  117095. return;
  117096. }
  117097. if (this._onAfterCheckInputsObserver) {
  117098. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  117099. }
  117100. if (this._onMeshTargetChangedObserver) {
  117101. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  117102. }
  117103. this._attachedCamera = null;
  117104. };
  117105. /**
  117106. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  117107. * @param radiusLimit The limit to check against.
  117108. * @return Bool to indicate if at limit.
  117109. */
  117110. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  117111. if (!this._attachedCamera) {
  117112. return false;
  117113. }
  117114. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  117115. return true;
  117116. }
  117117. return false;
  117118. };
  117119. /**
  117120. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  117121. * @param radiusDelta The delta by which to animate to. Can be negative.
  117122. */
  117123. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  117124. var _this = this;
  117125. if (!this._attachedCamera) {
  117126. return;
  117127. }
  117128. if (!this._radiusBounceTransition) {
  117129. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  117130. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  117131. }
  117132. // Prevent zoom until bounce has completed
  117133. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  117134. this._attachedCamera.wheelPrecision = Infinity;
  117135. this._attachedCamera.inertialRadiusOffset = 0;
  117136. // Animate to the radius limit
  117137. this.stopAllAnimations();
  117138. this._radiusIsAnimating = true;
  117139. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  117140. if (animatable) {
  117141. this._animatables.push(animatable);
  117142. }
  117143. };
  117144. /**
  117145. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  117146. */
  117147. BouncingBehavior.prototype._clearAnimationLocks = function () {
  117148. this._radiusIsAnimating = false;
  117149. if (this._attachedCamera) {
  117150. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  117151. }
  117152. };
  117153. /**
  117154. * Stops and removes all animations that have been applied to the camera
  117155. */
  117156. BouncingBehavior.prototype.stopAllAnimations = function () {
  117157. if (this._attachedCamera) {
  117158. this._attachedCamera.animations = [];
  117159. }
  117160. while (this._animatables.length) {
  117161. this._animatables[0].onAnimationEnd = null;
  117162. this._animatables[0].stop();
  117163. this._animatables.shift();
  117164. }
  117165. };
  117166. /**
  117167. * The easing function used by animations
  117168. */
  117169. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  117170. /**
  117171. * The easing mode used by animations
  117172. */
  117173. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  117174. return BouncingBehavior;
  117175. }());
  117176. BABYLON.BouncingBehavior = BouncingBehavior;
  117177. })(BABYLON || (BABYLON = {}));
  117178. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  117179. var BABYLON;
  117180. (function (BABYLON) {
  117181. /**
  117182. * The autoRotation behavior (BABYLON.AutoRotationBehavior) is designed to create a smooth rotation of an ArcRotateCamera when there is no user interaction.
  117183. * @see http://doc.babylonjs.com/how_to/camera_behaviors#autorotation-behavior
  117184. */
  117185. var AutoRotationBehavior = /** @class */ (function () {
  117186. function AutoRotationBehavior() {
  117187. this._zoomStopsAnimation = false;
  117188. this._idleRotationSpeed = 0.05;
  117189. this._idleRotationWaitTime = 2000;
  117190. this._idleRotationSpinupTime = 2000;
  117191. this._isPointerDown = false;
  117192. this._lastFrameTime = null;
  117193. this._lastInteractionTime = -Infinity;
  117194. this._cameraRotationSpeed = 0;
  117195. this._lastFrameRadius = 0;
  117196. }
  117197. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  117198. /**
  117199. * Gets the name of the behavior.
  117200. */
  117201. get: function () {
  117202. return "AutoRotation";
  117203. },
  117204. enumerable: true,
  117205. configurable: true
  117206. });
  117207. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  117208. /**
  117209. * Gets the flag that indicates if user zooming should stop animation.
  117210. */
  117211. get: function () {
  117212. return this._zoomStopsAnimation;
  117213. },
  117214. /**
  117215. * Sets the flag that indicates if user zooming should stop animation.
  117216. */
  117217. set: function (flag) {
  117218. this._zoomStopsAnimation = flag;
  117219. },
  117220. enumerable: true,
  117221. configurable: true
  117222. });
  117223. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  117224. /**
  117225. * Gets the default speed at which the camera rotates around the model.
  117226. */
  117227. get: function () {
  117228. return this._idleRotationSpeed;
  117229. },
  117230. /**
  117231. * Sets the default speed at which the camera rotates around the model.
  117232. */
  117233. set: function (speed) {
  117234. this._idleRotationSpeed = speed;
  117235. },
  117236. enumerable: true,
  117237. configurable: true
  117238. });
  117239. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  117240. /**
  117241. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  117242. */
  117243. get: function () {
  117244. return this._idleRotationWaitTime;
  117245. },
  117246. /**
  117247. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  117248. */
  117249. set: function (time) {
  117250. this._idleRotationWaitTime = time;
  117251. },
  117252. enumerable: true,
  117253. configurable: true
  117254. });
  117255. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  117256. /**
  117257. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  117258. */
  117259. get: function () {
  117260. return this._idleRotationSpinupTime;
  117261. },
  117262. /**
  117263. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  117264. */
  117265. set: function (time) {
  117266. this._idleRotationSpinupTime = time;
  117267. },
  117268. enumerable: true,
  117269. configurable: true
  117270. });
  117271. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  117272. /**
  117273. * Gets a value indicating if the camera is currently rotating because of this behavior
  117274. */
  117275. get: function () {
  117276. return Math.abs(this._cameraRotationSpeed) > 0;
  117277. },
  117278. enumerable: true,
  117279. configurable: true
  117280. });
  117281. /**
  117282. * Initializes the behavior.
  117283. */
  117284. AutoRotationBehavior.prototype.init = function () {
  117285. // Do notihng
  117286. };
  117287. /**
  117288. * Attaches the behavior to its arc rotate camera.
  117289. * @param camera Defines the camera to attach the behavior to
  117290. */
  117291. AutoRotationBehavior.prototype.attach = function (camera) {
  117292. var _this = this;
  117293. this._attachedCamera = camera;
  117294. var scene = this._attachedCamera.getScene();
  117295. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  117296. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  117297. _this._isPointerDown = true;
  117298. return;
  117299. }
  117300. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  117301. _this._isPointerDown = false;
  117302. }
  117303. });
  117304. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  117305. var now = BABYLON.Tools.Now;
  117306. var dt = 0;
  117307. if (_this._lastFrameTime != null) {
  117308. dt = now - _this._lastFrameTime;
  117309. }
  117310. _this._lastFrameTime = now;
  117311. // Stop the animation if there is user interaction and the animation should stop for this interaction
  117312. _this._applyUserInteraction();
  117313. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  117314. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  117315. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  117316. // Step camera rotation by rotation speed
  117317. if (_this._attachedCamera) {
  117318. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  117319. }
  117320. });
  117321. };
  117322. /**
  117323. * Detaches the behavior from its current arc rotate camera.
  117324. */
  117325. AutoRotationBehavior.prototype.detach = function () {
  117326. if (!this._attachedCamera) {
  117327. return;
  117328. }
  117329. var scene = this._attachedCamera.getScene();
  117330. if (this._onPrePointerObservableObserver) {
  117331. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  117332. }
  117333. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  117334. this._attachedCamera = null;
  117335. };
  117336. /**
  117337. * Returns true if user is scrolling.
  117338. * @return true if user is scrolling.
  117339. */
  117340. AutoRotationBehavior.prototype._userIsZooming = function () {
  117341. if (!this._attachedCamera) {
  117342. return false;
  117343. }
  117344. return this._attachedCamera.inertialRadiusOffset !== 0;
  117345. };
  117346. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  117347. if (!this._attachedCamera) {
  117348. return false;
  117349. }
  117350. var zoomHasHitLimit = false;
  117351. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  117352. zoomHasHitLimit = true;
  117353. }
  117354. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  117355. this._lastFrameRadius = this._attachedCamera.radius;
  117356. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  117357. };
  117358. /**
  117359. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  117360. */
  117361. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  117362. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  117363. this._lastInteractionTime = BABYLON.Tools.Now;
  117364. }
  117365. };
  117366. // Tools
  117367. AutoRotationBehavior.prototype._userIsMoving = function () {
  117368. if (!this._attachedCamera) {
  117369. return false;
  117370. }
  117371. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  117372. this._attachedCamera.inertialBetaOffset !== 0 ||
  117373. this._attachedCamera.inertialRadiusOffset !== 0 ||
  117374. this._attachedCamera.inertialPanningX !== 0 ||
  117375. this._attachedCamera.inertialPanningY !== 0 ||
  117376. this._isPointerDown;
  117377. };
  117378. return AutoRotationBehavior;
  117379. }());
  117380. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  117381. })(BABYLON || (BABYLON = {}));
  117382. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  117383. var BABYLON;
  117384. (function (BABYLON) {
  117385. /**
  117386. * Options to create the null engine
  117387. */
  117388. var NullEngineOptions = /** @class */ (function () {
  117389. function NullEngineOptions() {
  117390. /**
  117391. * Render width (Default: 512)
  117392. */
  117393. this.renderWidth = 512;
  117394. /**
  117395. * Render height (Default: 256)
  117396. */
  117397. this.renderHeight = 256;
  117398. /**
  117399. * Texture size (Default: 512)
  117400. */
  117401. this.textureSize = 512;
  117402. /**
  117403. * If delta time between frames should be constant
  117404. * @see https://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  117405. */
  117406. this.deterministicLockstep = false;
  117407. /**
  117408. * Maximum about of steps between frames (Default: 4)
  117409. * @see https://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  117410. */
  117411. this.lockstepMaxSteps = 4;
  117412. }
  117413. return NullEngineOptions;
  117414. }());
  117415. BABYLON.NullEngineOptions = NullEngineOptions;
  117416. /**
  117417. * The null engine class provides support for headless version of babylon.js.
  117418. * This can be used in server side scenario or for testing purposes
  117419. */
  117420. var NullEngine = /** @class */ (function (_super) {
  117421. __extends(NullEngine, _super);
  117422. function NullEngine(options) {
  117423. if (options === void 0) { options = new NullEngineOptions(); }
  117424. var _this = _super.call(this, null) || this;
  117425. if (options.deterministicLockstep === undefined) {
  117426. options.deterministicLockstep = false;
  117427. }
  117428. if (options.lockstepMaxSteps === undefined) {
  117429. options.lockstepMaxSteps = 4;
  117430. }
  117431. _this._options = options;
  117432. // Init caps
  117433. // We consider we are on a webgl1 capable device
  117434. _this._caps = new BABYLON.EngineCapabilities();
  117435. _this._caps.maxTexturesImageUnits = 16;
  117436. _this._caps.maxVertexTextureImageUnits = 16;
  117437. _this._caps.maxTextureSize = 512;
  117438. _this._caps.maxCubemapTextureSize = 512;
  117439. _this._caps.maxRenderTextureSize = 512;
  117440. _this._caps.maxVertexAttribs = 16;
  117441. _this._caps.maxVaryingVectors = 16;
  117442. _this._caps.maxFragmentUniformVectors = 16;
  117443. _this._caps.maxVertexUniformVectors = 16;
  117444. // Extensions
  117445. _this._caps.standardDerivatives = false;
  117446. _this._caps.astc = null;
  117447. _this._caps.s3tc = null;
  117448. _this._caps.pvrtc = null;
  117449. _this._caps.etc1 = null;
  117450. _this._caps.etc2 = null;
  117451. _this._caps.textureAnisotropicFilterExtension = null;
  117452. _this._caps.maxAnisotropy = 0;
  117453. _this._caps.uintIndices = false;
  117454. _this._caps.fragmentDepthSupported = false;
  117455. _this._caps.highPrecisionShaderSupported = true;
  117456. _this._caps.colorBufferFloat = false;
  117457. _this._caps.textureFloat = false;
  117458. _this._caps.textureFloatLinearFiltering = false;
  117459. _this._caps.textureFloatRender = false;
  117460. _this._caps.textureHalfFloat = false;
  117461. _this._caps.textureHalfFloatLinearFiltering = false;
  117462. _this._caps.textureHalfFloatRender = false;
  117463. _this._caps.textureLOD = false;
  117464. _this._caps.drawBuffersExtension = false;
  117465. _this._caps.depthTextureExtension = false;
  117466. _this._caps.vertexArrayObject = false;
  117467. _this._caps.instancedArrays = false;
  117468. BABYLON.Tools.Log("Babylon.js v" + BABYLON.Engine.Version + " - Null engine");
  117469. // Wrappers
  117470. if (typeof URL === "undefined") {
  117471. URL = {
  117472. createObjectURL: function () { },
  117473. revokeObjectURL: function () { }
  117474. };
  117475. }
  117476. if (typeof Blob === "undefined") {
  117477. Blob = function () { };
  117478. }
  117479. return _this;
  117480. }
  117481. /**
  117482. * @see https://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  117483. */
  117484. NullEngine.prototype.isDeterministicLockStep = function () {
  117485. return this._options.deterministicLockstep;
  117486. };
  117487. /** @see https://doc.babylonjs.com/babylon101/animations#deterministic-lockstep */
  117488. NullEngine.prototype.getLockstepMaxSteps = function () {
  117489. return this._options.lockstepMaxSteps;
  117490. };
  117491. /**
  117492. * Sets hardware scaling, used to save performance if needed
  117493. * @see https://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  117494. */
  117495. NullEngine.prototype.getHardwareScalingLevel = function () {
  117496. return 1.0;
  117497. };
  117498. NullEngine.prototype.createVertexBuffer = function (vertices) {
  117499. return {
  117500. capacity: 0,
  117501. references: 1,
  117502. is32Bits: false
  117503. };
  117504. };
  117505. NullEngine.prototype.createIndexBuffer = function (indices) {
  117506. return {
  117507. capacity: 0,
  117508. references: 1,
  117509. is32Bits: false
  117510. };
  117511. };
  117512. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  117513. if (stencil === void 0) { stencil = false; }
  117514. };
  117515. NullEngine.prototype.getRenderWidth = function (useScreen) {
  117516. if (useScreen === void 0) { useScreen = false; }
  117517. if (!useScreen && this._currentRenderTarget) {
  117518. return this._currentRenderTarget.width;
  117519. }
  117520. return this._options.renderWidth;
  117521. };
  117522. NullEngine.prototype.getRenderHeight = function (useScreen) {
  117523. if (useScreen === void 0) { useScreen = false; }
  117524. if (!useScreen && this._currentRenderTarget) {
  117525. return this._currentRenderTarget.height;
  117526. }
  117527. return this._options.renderHeight;
  117528. };
  117529. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  117530. this._cachedViewport = viewport;
  117531. };
  117532. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  117533. return {
  117534. transformFeedback: null,
  117535. __SPECTOR_rebuildProgram: null,
  117536. isParallelCompiled: false
  117537. };
  117538. };
  117539. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  117540. return [];
  117541. };
  117542. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  117543. return [];
  117544. };
  117545. NullEngine.prototype.bindSamplers = function (effect) {
  117546. this._currentEffect = null;
  117547. };
  117548. NullEngine.prototype.enableEffect = function (effect) {
  117549. this._currentEffect = effect;
  117550. if (effect.onBind) {
  117551. effect.onBind(effect);
  117552. }
  117553. if (effect._onBindObservable) {
  117554. effect._onBindObservable.notifyObservers(effect);
  117555. }
  117556. };
  117557. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  117558. if (zOffset === void 0) { zOffset = 0; }
  117559. if (reverseSide === void 0) { reverseSide = false; }
  117560. };
  117561. NullEngine.prototype.setIntArray = function (uniform, array) {
  117562. };
  117563. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  117564. };
  117565. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  117566. };
  117567. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  117568. };
  117569. NullEngine.prototype.setFloatArray = function (uniform, array) {
  117570. };
  117571. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  117572. };
  117573. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  117574. };
  117575. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  117576. };
  117577. NullEngine.prototype.setArray = function (uniform, array) {
  117578. };
  117579. NullEngine.prototype.setArray2 = function (uniform, array) {
  117580. };
  117581. NullEngine.prototype.setArray3 = function (uniform, array) {
  117582. };
  117583. NullEngine.prototype.setArray4 = function (uniform, array) {
  117584. };
  117585. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  117586. };
  117587. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  117588. };
  117589. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  117590. };
  117591. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  117592. };
  117593. NullEngine.prototype.setFloat = function (uniform, value) {
  117594. };
  117595. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  117596. };
  117597. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  117598. };
  117599. NullEngine.prototype.setBool = function (uniform, bool) {
  117600. };
  117601. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  117602. };
  117603. NullEngine.prototype.setColor3 = function (uniform, color3) {
  117604. };
  117605. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  117606. };
  117607. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  117608. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  117609. if (this._alphaMode === mode) {
  117610. return;
  117611. }
  117612. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  117613. if (!noDepthWriteChange) {
  117614. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  117615. }
  117616. this._alphaMode = mode;
  117617. };
  117618. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  117619. };
  117620. NullEngine.prototype.wipeCaches = function (bruteForce) {
  117621. if (this.preventCacheWipeBetweenFrames) {
  117622. return;
  117623. }
  117624. this.resetTextureCache();
  117625. this._currentEffect = null;
  117626. if (bruteForce) {
  117627. this._currentProgram = null;
  117628. this._stencilState.reset();
  117629. this._depthCullingState.reset();
  117630. this._alphaState.reset();
  117631. }
  117632. this._cachedVertexBuffers = null;
  117633. this._cachedIndexBuffer = null;
  117634. this._cachedEffectForVertexBuffers = null;
  117635. };
  117636. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  117637. };
  117638. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  117639. };
  117640. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  117641. };
  117642. /** @hidden */
  117643. NullEngine.prototype._createTexture = function () {
  117644. return {};
  117645. };
  117646. /** @hidden */
  117647. NullEngine.prototype._releaseTexture = function (texture) {
  117648. };
  117649. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  117650. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  117651. if (onLoad === void 0) { onLoad = null; }
  117652. if (onError === void 0) { onError = null; }
  117653. if (buffer === void 0) { buffer = null; }
  117654. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  117655. var url = String(urlArg);
  117656. texture.url = url;
  117657. texture.generateMipMaps = !noMipmap;
  117658. texture.samplingMode = samplingMode;
  117659. texture.invertY = invertY;
  117660. texture.baseWidth = this._options.textureSize;
  117661. texture.baseHeight = this._options.textureSize;
  117662. texture.width = this._options.textureSize;
  117663. texture.height = this._options.textureSize;
  117664. if (format) {
  117665. texture.format = format;
  117666. }
  117667. texture.isReady = true;
  117668. if (onLoad) {
  117669. onLoad();
  117670. }
  117671. this._internalTexturesCache.push(texture);
  117672. return texture;
  117673. };
  117674. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  117675. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  117676. if (options !== undefined && typeof options === "object") {
  117677. fullOptions.generateMipMaps = options.generateMipMaps;
  117678. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  117679. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  117680. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  117681. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  117682. }
  117683. else {
  117684. fullOptions.generateMipMaps = options;
  117685. fullOptions.generateDepthBuffer = true;
  117686. fullOptions.generateStencilBuffer = false;
  117687. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  117688. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  117689. }
  117690. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  117691. var width = size.width || size;
  117692. var height = size.height || size;
  117693. texture._depthStencilBuffer = {};
  117694. texture._framebuffer = {};
  117695. texture.baseWidth = width;
  117696. texture.baseHeight = height;
  117697. texture.width = width;
  117698. texture.height = height;
  117699. texture.isReady = true;
  117700. texture.samples = 1;
  117701. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  117702. texture.samplingMode = fullOptions.samplingMode;
  117703. texture.type = fullOptions.type;
  117704. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  117705. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  117706. this._internalTexturesCache.push(texture);
  117707. return texture;
  117708. };
  117709. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  117710. texture.samplingMode = samplingMode;
  117711. };
  117712. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  117713. if (this._currentRenderTarget) {
  117714. this.unBindFramebuffer(this._currentRenderTarget);
  117715. }
  117716. this._currentRenderTarget = texture;
  117717. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  117718. if (this._cachedViewport && !forceFullscreenViewport) {
  117719. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  117720. }
  117721. };
  117722. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  117723. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  117724. this._currentRenderTarget = null;
  117725. if (onBeforeUnbind) {
  117726. if (texture._MSAAFramebuffer) {
  117727. this._currentFramebuffer = texture._framebuffer;
  117728. }
  117729. onBeforeUnbind();
  117730. }
  117731. this._currentFramebuffer = null;
  117732. };
  117733. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  117734. var vbo = {
  117735. capacity: 1,
  117736. references: 1,
  117737. is32Bits: false
  117738. };
  117739. return vbo;
  117740. };
  117741. NullEngine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  117742. if (premulAlpha === void 0) { premulAlpha = false; }
  117743. };
  117744. NullEngine.prototype.areAllEffectsReady = function () {
  117745. return true;
  117746. };
  117747. /**
  117748. * @hidden
  117749. * Get the current error code of the webGL context
  117750. * @returns the error code
  117751. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  117752. */
  117753. NullEngine.prototype.getError = function () {
  117754. return 0;
  117755. };
  117756. /** @hidden */
  117757. NullEngine.prototype._getUnpackAlignement = function () {
  117758. return 1;
  117759. };
  117760. /** @hidden */
  117761. NullEngine.prototype._unpackFlipY = function (value) {
  117762. };
  117763. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  117764. if (offset === void 0) { offset = 0; }
  117765. };
  117766. /**
  117767. * Updates a dynamic vertex buffer.
  117768. * @param vertexBuffer the vertex buffer to update
  117769. * @param data the data used to update the vertex buffer
  117770. * @param byteOffset the byte offset of the data (optional)
  117771. * @param byteLength the byte length of the data (optional)
  117772. */
  117773. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  117774. };
  117775. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  117776. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  117777. this._boundTexturesCache[this._activeChannel] = texture;
  117778. return true;
  117779. }
  117780. return false;
  117781. };
  117782. /** @hidden */
  117783. NullEngine.prototype._bindTexture = function (channel, texture) {
  117784. if (channel < 0) {
  117785. return;
  117786. }
  117787. this._bindTextureDirectly(0, texture);
  117788. };
  117789. /** @hidden */
  117790. NullEngine.prototype._releaseBuffer = function (buffer) {
  117791. buffer.references--;
  117792. if (buffer.references === 0) {
  117793. return true;
  117794. }
  117795. return false;
  117796. };
  117797. NullEngine.prototype.releaseEffects = function () {
  117798. };
  117799. NullEngine.prototype.displayLoadingUI = function () {
  117800. };
  117801. NullEngine.prototype.hideLoadingUI = function () {
  117802. };
  117803. /** @hidden */
  117804. NullEngine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
  117805. if (faceIndex === void 0) { faceIndex = 0; }
  117806. if (lod === void 0) { lod = 0; }
  117807. };
  117808. /** @hidden */
  117809. NullEngine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {
  117810. if (faceIndex === void 0) { faceIndex = 0; }
  117811. if (lod === void 0) { lod = 0; }
  117812. };
  117813. /** @hidden */
  117814. NullEngine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
  117815. if (faceIndex === void 0) { faceIndex = 0; }
  117816. if (lod === void 0) { lod = 0; }
  117817. };
  117818. /** @hidden */
  117819. NullEngine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {
  117820. if (faceIndex === void 0) { faceIndex = 0; }
  117821. if (lod === void 0) { lod = 0; }
  117822. };
  117823. return NullEngine;
  117824. }(BABYLON.Engine));
  117825. BABYLON.NullEngine = NullEngine;
  117826. })(BABYLON || (BABYLON = {}));
  117827. //# sourceMappingURL=babylon.nullEngine.js.map
  117828. var BABYLON;
  117829. (function (BABYLON) {
  117830. /**
  117831. * This class can be used to get instrumentation data from a Babylon engine
  117832. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  117833. */
  117834. var EngineInstrumentation = /** @class */ (function () {
  117835. /**
  117836. * Instantiates a new engine instrumentation.
  117837. * This class can be used to get instrumentation data from a Babylon engine
  117838. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  117839. * @param engine Defines the engine to instrument
  117840. */
  117841. function EngineInstrumentation(
  117842. /**
  117843. * Define the instrumented engine.
  117844. */
  117845. engine) {
  117846. this.engine = engine;
  117847. this._captureGPUFrameTime = false;
  117848. this._gpuFrameTime = new BABYLON.PerfCounter();
  117849. this._captureShaderCompilationTime = false;
  117850. this._shaderCompilationTime = new BABYLON.PerfCounter();
  117851. // Observers
  117852. this._onBeginFrameObserver = null;
  117853. this._onEndFrameObserver = null;
  117854. this._onBeforeShaderCompilationObserver = null;
  117855. this._onAfterShaderCompilationObserver = null;
  117856. }
  117857. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  117858. // Properties
  117859. /**
  117860. * Gets the perf counter used for GPU frame time
  117861. */
  117862. get: function () {
  117863. return this._gpuFrameTime;
  117864. },
  117865. enumerable: true,
  117866. configurable: true
  117867. });
  117868. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  117869. /**
  117870. * Gets the GPU frame time capture status
  117871. */
  117872. get: function () {
  117873. return this._captureGPUFrameTime;
  117874. },
  117875. /**
  117876. * Enable or disable the GPU frame time capture
  117877. */
  117878. set: function (value) {
  117879. var _this = this;
  117880. if (value === this._captureGPUFrameTime) {
  117881. return;
  117882. }
  117883. this._captureGPUFrameTime = value;
  117884. if (value) {
  117885. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  117886. if (!_this._gpuFrameTimeToken) {
  117887. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  117888. }
  117889. });
  117890. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  117891. if (!_this._gpuFrameTimeToken) {
  117892. return;
  117893. }
  117894. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  117895. if (time > -1) {
  117896. _this._gpuFrameTimeToken = null;
  117897. _this._gpuFrameTime.fetchNewFrame();
  117898. _this._gpuFrameTime.addCount(time, true);
  117899. }
  117900. });
  117901. }
  117902. else {
  117903. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  117904. this._onBeginFrameObserver = null;
  117905. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  117906. this._onEndFrameObserver = null;
  117907. }
  117908. },
  117909. enumerable: true,
  117910. configurable: true
  117911. });
  117912. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  117913. /**
  117914. * Gets the perf counter used for shader compilation time
  117915. */
  117916. get: function () {
  117917. return this._shaderCompilationTime;
  117918. },
  117919. enumerable: true,
  117920. configurable: true
  117921. });
  117922. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  117923. /**
  117924. * Gets the shader compilation time capture status
  117925. */
  117926. get: function () {
  117927. return this._captureShaderCompilationTime;
  117928. },
  117929. /**
  117930. * Enable or disable the shader compilation time capture
  117931. */
  117932. set: function (value) {
  117933. var _this = this;
  117934. if (value === this._captureShaderCompilationTime) {
  117935. return;
  117936. }
  117937. this._captureShaderCompilationTime = value;
  117938. if (value) {
  117939. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  117940. _this._shaderCompilationTime.fetchNewFrame();
  117941. _this._shaderCompilationTime.beginMonitoring();
  117942. });
  117943. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  117944. _this._shaderCompilationTime.endMonitoring();
  117945. });
  117946. }
  117947. else {
  117948. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  117949. this._onBeforeShaderCompilationObserver = null;
  117950. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  117951. this._onAfterShaderCompilationObserver = null;
  117952. }
  117953. },
  117954. enumerable: true,
  117955. configurable: true
  117956. });
  117957. /**
  117958. * Dispose and release associated resources.
  117959. */
  117960. EngineInstrumentation.prototype.dispose = function () {
  117961. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  117962. this._onBeginFrameObserver = null;
  117963. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  117964. this._onEndFrameObserver = null;
  117965. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  117966. this._onBeforeShaderCompilationObserver = null;
  117967. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  117968. this._onAfterShaderCompilationObserver = null;
  117969. this.engine = null;
  117970. };
  117971. return EngineInstrumentation;
  117972. }());
  117973. BABYLON.EngineInstrumentation = EngineInstrumentation;
  117974. })(BABYLON || (BABYLON = {}));
  117975. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  117976. var BABYLON;
  117977. (function (BABYLON) {
  117978. /**
  117979. * This class can be used to get instrumentation data from a Babylon engine
  117980. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#sceneinstrumentation
  117981. */
  117982. var SceneInstrumentation = /** @class */ (function () {
  117983. /**
  117984. * Instantiates a new scene instrumentation.
  117985. * This class can be used to get instrumentation data from a Babylon engine
  117986. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#sceneinstrumentation
  117987. * @param scene Defines the scene to instrument
  117988. */
  117989. function SceneInstrumentation(
  117990. /**
  117991. * Defines the scene to instrument
  117992. */
  117993. scene) {
  117994. var _this = this;
  117995. this.scene = scene;
  117996. this._captureActiveMeshesEvaluationTime = false;
  117997. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  117998. this._captureRenderTargetsRenderTime = false;
  117999. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  118000. this._captureFrameTime = false;
  118001. this._frameTime = new BABYLON.PerfCounter();
  118002. this._captureRenderTime = false;
  118003. this._renderTime = new BABYLON.PerfCounter();
  118004. this._captureInterFrameTime = false;
  118005. this._interFrameTime = new BABYLON.PerfCounter();
  118006. this._captureParticlesRenderTime = false;
  118007. this._particlesRenderTime = new BABYLON.PerfCounter();
  118008. this._captureSpritesRenderTime = false;
  118009. this._spritesRenderTime = new BABYLON.PerfCounter();
  118010. this._capturePhysicsTime = false;
  118011. this._physicsTime = new BABYLON.PerfCounter();
  118012. this._captureAnimationsTime = false;
  118013. this._animationsTime = new BABYLON.PerfCounter();
  118014. this._captureCameraRenderTime = false;
  118015. this._cameraRenderTime = new BABYLON.PerfCounter();
  118016. // Observers
  118017. this._onBeforeActiveMeshesEvaluationObserver = null;
  118018. this._onAfterActiveMeshesEvaluationObserver = null;
  118019. this._onBeforeRenderTargetsRenderObserver = null;
  118020. this._onAfterRenderTargetsRenderObserver = null;
  118021. this._onAfterRenderObserver = null;
  118022. this._onBeforeDrawPhaseObserver = null;
  118023. this._onAfterDrawPhaseObserver = null;
  118024. this._onBeforeAnimationsObserver = null;
  118025. this._onBeforeParticlesRenderingObserver = null;
  118026. this._onAfterParticlesRenderingObserver = null;
  118027. this._onBeforeSpritesRenderingObserver = null;
  118028. this._onAfterSpritesRenderingObserver = null;
  118029. this._onBeforePhysicsObserver = null;
  118030. this._onAfterPhysicsObserver = null;
  118031. this._onAfterAnimationsObserver = null;
  118032. this._onBeforeCameraRenderObserver = null;
  118033. this._onAfterCameraRenderObserver = null;
  118034. // Before render
  118035. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  118036. if (_this._captureActiveMeshesEvaluationTime) {
  118037. _this._activeMeshesEvaluationTime.fetchNewFrame();
  118038. }
  118039. if (_this._captureRenderTargetsRenderTime) {
  118040. _this._renderTargetsRenderTime.fetchNewFrame();
  118041. }
  118042. if (_this._captureFrameTime) {
  118043. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  118044. _this._frameTime.beginMonitoring();
  118045. }
  118046. if (_this._captureInterFrameTime) {
  118047. _this._interFrameTime.endMonitoring();
  118048. }
  118049. if (_this._captureParticlesRenderTime) {
  118050. _this._particlesRenderTime.fetchNewFrame();
  118051. }
  118052. if (_this._captureSpritesRenderTime) {
  118053. _this._spritesRenderTime.fetchNewFrame();
  118054. }
  118055. if (_this._captureAnimationsTime) {
  118056. _this._animationsTime.beginMonitoring();
  118057. }
  118058. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  118059. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  118060. });
  118061. // After render
  118062. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  118063. if (_this._captureFrameTime) {
  118064. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  118065. _this._frameTime.endMonitoring();
  118066. }
  118067. if (_this._captureRenderTime) {
  118068. _this._renderTime.endMonitoring(false);
  118069. }
  118070. if (_this._captureInterFrameTime) {
  118071. _this._interFrameTime.beginMonitoring();
  118072. }
  118073. });
  118074. }
  118075. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  118076. // Properties
  118077. /**
  118078. * Gets the perf counter used for active meshes evaluation time
  118079. */
  118080. get: function () {
  118081. return this._activeMeshesEvaluationTime;
  118082. },
  118083. enumerable: true,
  118084. configurable: true
  118085. });
  118086. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  118087. /**
  118088. * Gets the active meshes evaluation time capture status
  118089. */
  118090. get: function () {
  118091. return this._captureActiveMeshesEvaluationTime;
  118092. },
  118093. /**
  118094. * Enable or disable the active meshes evaluation time capture
  118095. */
  118096. set: function (value) {
  118097. var _this = this;
  118098. if (value === this._captureActiveMeshesEvaluationTime) {
  118099. return;
  118100. }
  118101. this._captureActiveMeshesEvaluationTime = value;
  118102. if (value) {
  118103. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  118104. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  118105. _this._activeMeshesEvaluationTime.beginMonitoring();
  118106. });
  118107. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  118108. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  118109. _this._activeMeshesEvaluationTime.endMonitoring();
  118110. });
  118111. }
  118112. else {
  118113. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  118114. this._onBeforeActiveMeshesEvaluationObserver = null;
  118115. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  118116. this._onAfterActiveMeshesEvaluationObserver = null;
  118117. }
  118118. },
  118119. enumerable: true,
  118120. configurable: true
  118121. });
  118122. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  118123. /**
  118124. * Gets the perf counter used for render targets render time
  118125. */
  118126. get: function () {
  118127. return this._renderTargetsRenderTime;
  118128. },
  118129. enumerable: true,
  118130. configurable: true
  118131. });
  118132. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  118133. /**
  118134. * Gets the render targets render time capture status
  118135. */
  118136. get: function () {
  118137. return this._captureRenderTargetsRenderTime;
  118138. },
  118139. /**
  118140. * Enable or disable the render targets render time capture
  118141. */
  118142. set: function (value) {
  118143. var _this = this;
  118144. if (value === this._captureRenderTargetsRenderTime) {
  118145. return;
  118146. }
  118147. this._captureRenderTargetsRenderTime = value;
  118148. if (value) {
  118149. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  118150. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  118151. _this._renderTargetsRenderTime.beginMonitoring();
  118152. });
  118153. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  118154. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  118155. _this._renderTargetsRenderTime.endMonitoring(false);
  118156. });
  118157. }
  118158. else {
  118159. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  118160. this._onBeforeRenderTargetsRenderObserver = null;
  118161. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  118162. this._onAfterRenderTargetsRenderObserver = null;
  118163. }
  118164. },
  118165. enumerable: true,
  118166. configurable: true
  118167. });
  118168. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  118169. /**
  118170. * Gets the perf counter used for particles render time
  118171. */
  118172. get: function () {
  118173. return this._particlesRenderTime;
  118174. },
  118175. enumerable: true,
  118176. configurable: true
  118177. });
  118178. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  118179. /**
  118180. * Gets the particles render time capture status
  118181. */
  118182. get: function () {
  118183. return this._captureParticlesRenderTime;
  118184. },
  118185. /**
  118186. * Enable or disable the particles render time capture
  118187. */
  118188. set: function (value) {
  118189. var _this = this;
  118190. if (value === this._captureParticlesRenderTime) {
  118191. return;
  118192. }
  118193. this._captureParticlesRenderTime = value;
  118194. if (value) {
  118195. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  118196. BABYLON.Tools.StartPerformanceCounter("Particles");
  118197. _this._particlesRenderTime.beginMonitoring();
  118198. });
  118199. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  118200. BABYLON.Tools.EndPerformanceCounter("Particles");
  118201. _this._particlesRenderTime.endMonitoring(false);
  118202. });
  118203. }
  118204. else {
  118205. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  118206. this._onBeforeParticlesRenderingObserver = null;
  118207. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  118208. this._onAfterParticlesRenderingObserver = null;
  118209. }
  118210. },
  118211. enumerable: true,
  118212. configurable: true
  118213. });
  118214. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  118215. /**
  118216. * Gets the perf counter used for sprites render time
  118217. */
  118218. get: function () {
  118219. return this._spritesRenderTime;
  118220. },
  118221. enumerable: true,
  118222. configurable: true
  118223. });
  118224. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  118225. /**
  118226. * Gets the sprites render time capture status
  118227. */
  118228. get: function () {
  118229. return this._captureSpritesRenderTime;
  118230. },
  118231. /**
  118232. * Enable or disable the sprites render time capture
  118233. */
  118234. set: function (value) {
  118235. var _this = this;
  118236. if (value === this._captureSpritesRenderTime) {
  118237. return;
  118238. }
  118239. this._captureSpritesRenderTime = value;
  118240. if (!this.scene.spriteManagers) {
  118241. return;
  118242. }
  118243. if (value) {
  118244. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  118245. BABYLON.Tools.StartPerformanceCounter("Sprites");
  118246. _this._spritesRenderTime.beginMonitoring();
  118247. });
  118248. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  118249. BABYLON.Tools.EndPerformanceCounter("Sprites");
  118250. _this._spritesRenderTime.endMonitoring(false);
  118251. });
  118252. }
  118253. else {
  118254. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  118255. this._onBeforeSpritesRenderingObserver = null;
  118256. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  118257. this._onAfterSpritesRenderingObserver = null;
  118258. }
  118259. },
  118260. enumerable: true,
  118261. configurable: true
  118262. });
  118263. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  118264. /**
  118265. * Gets the perf counter used for physics time
  118266. */
  118267. get: function () {
  118268. return this._physicsTime;
  118269. },
  118270. enumerable: true,
  118271. configurable: true
  118272. });
  118273. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  118274. /**
  118275. * Gets the physics time capture status
  118276. */
  118277. get: function () {
  118278. return this._capturePhysicsTime;
  118279. },
  118280. /**
  118281. * Enable or disable the physics time capture
  118282. */
  118283. set: function (value) {
  118284. var _this = this;
  118285. if (value === this._capturePhysicsTime) {
  118286. return;
  118287. }
  118288. if (!this.scene.onBeforePhysicsObservable) {
  118289. return;
  118290. }
  118291. this._capturePhysicsTime = value;
  118292. if (value) {
  118293. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  118294. BABYLON.Tools.StartPerformanceCounter("Physics");
  118295. _this._physicsTime.beginMonitoring();
  118296. });
  118297. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  118298. BABYLON.Tools.EndPerformanceCounter("Physics");
  118299. _this._physicsTime.endMonitoring();
  118300. });
  118301. }
  118302. else {
  118303. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  118304. this._onBeforePhysicsObserver = null;
  118305. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  118306. this._onAfterPhysicsObserver = null;
  118307. }
  118308. },
  118309. enumerable: true,
  118310. configurable: true
  118311. });
  118312. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  118313. /**
  118314. * Gets the perf counter used for animations time
  118315. */
  118316. get: function () {
  118317. return this._animationsTime;
  118318. },
  118319. enumerable: true,
  118320. configurable: true
  118321. });
  118322. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  118323. /**
  118324. * Gets the animations time capture status
  118325. */
  118326. get: function () {
  118327. return this._captureAnimationsTime;
  118328. },
  118329. /**
  118330. * Enable or disable the animations time capture
  118331. */
  118332. set: function (value) {
  118333. var _this = this;
  118334. if (value === this._captureAnimationsTime) {
  118335. return;
  118336. }
  118337. this._captureAnimationsTime = value;
  118338. if (value) {
  118339. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  118340. _this._animationsTime.endMonitoring();
  118341. });
  118342. }
  118343. else {
  118344. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  118345. this._onAfterAnimationsObserver = null;
  118346. }
  118347. },
  118348. enumerable: true,
  118349. configurable: true
  118350. });
  118351. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  118352. /**
  118353. * Gets the perf counter used for frame time capture
  118354. */
  118355. get: function () {
  118356. return this._frameTime;
  118357. },
  118358. enumerable: true,
  118359. configurable: true
  118360. });
  118361. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  118362. /**
  118363. * Gets the frame time capture status
  118364. */
  118365. get: function () {
  118366. return this._captureFrameTime;
  118367. },
  118368. /**
  118369. * Enable or disable the frame time capture
  118370. */
  118371. set: function (value) {
  118372. this._captureFrameTime = value;
  118373. },
  118374. enumerable: true,
  118375. configurable: true
  118376. });
  118377. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  118378. /**
  118379. * Gets the perf counter used for inter-frames time capture
  118380. */
  118381. get: function () {
  118382. return this._interFrameTime;
  118383. },
  118384. enumerable: true,
  118385. configurable: true
  118386. });
  118387. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  118388. /**
  118389. * Gets the inter-frames time capture status
  118390. */
  118391. get: function () {
  118392. return this._captureInterFrameTime;
  118393. },
  118394. /**
  118395. * Enable or disable the inter-frames time capture
  118396. */
  118397. set: function (value) {
  118398. this._captureInterFrameTime = value;
  118399. },
  118400. enumerable: true,
  118401. configurable: true
  118402. });
  118403. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  118404. /**
  118405. * Gets the perf counter used for render time capture
  118406. */
  118407. get: function () {
  118408. return this._renderTime;
  118409. },
  118410. enumerable: true,
  118411. configurable: true
  118412. });
  118413. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  118414. /**
  118415. * Gets the render time capture status
  118416. */
  118417. get: function () {
  118418. return this._captureRenderTime;
  118419. },
  118420. /**
  118421. * Enable or disable the render time capture
  118422. */
  118423. set: function (value) {
  118424. var _this = this;
  118425. if (value === this._captureRenderTime) {
  118426. return;
  118427. }
  118428. this._captureRenderTime = value;
  118429. if (value) {
  118430. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  118431. _this._renderTime.beginMonitoring();
  118432. BABYLON.Tools.StartPerformanceCounter("Main render");
  118433. });
  118434. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  118435. _this._renderTime.endMonitoring(false);
  118436. BABYLON.Tools.EndPerformanceCounter("Main render");
  118437. });
  118438. }
  118439. else {
  118440. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  118441. this._onBeforeDrawPhaseObserver = null;
  118442. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  118443. this._onAfterDrawPhaseObserver = null;
  118444. }
  118445. },
  118446. enumerable: true,
  118447. configurable: true
  118448. });
  118449. Object.defineProperty(SceneInstrumentation.prototype, "cameraRenderTimeCounter", {
  118450. /**
  118451. * Gets the perf counter used for camera render time capture
  118452. */
  118453. get: function () {
  118454. return this._cameraRenderTime;
  118455. },
  118456. enumerable: true,
  118457. configurable: true
  118458. });
  118459. Object.defineProperty(SceneInstrumentation.prototype, "captureCameraRenderTime", {
  118460. /**
  118461. * Gets the camera render time capture status
  118462. */
  118463. get: function () {
  118464. return this._captureCameraRenderTime;
  118465. },
  118466. /**
  118467. * Enable or disable the camera render time capture
  118468. */
  118469. set: function (value) {
  118470. var _this = this;
  118471. if (value === this._captureCameraRenderTime) {
  118472. return;
  118473. }
  118474. this._captureCameraRenderTime = value;
  118475. if (value) {
  118476. this._onBeforeCameraRenderObserver = this.scene.onBeforeCameraRenderObservable.add(function (camera) {
  118477. _this._cameraRenderTime.beginMonitoring();
  118478. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + camera.name);
  118479. });
  118480. this._onAfterCameraRenderObserver = this.scene.onAfterCameraRenderObservable.add(function (camera) {
  118481. _this._cameraRenderTime.endMonitoring(false);
  118482. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + camera.name);
  118483. });
  118484. }
  118485. else {
  118486. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  118487. this._onBeforeCameraRenderObserver = null;
  118488. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  118489. this._onAfterCameraRenderObserver = null;
  118490. }
  118491. },
  118492. enumerable: true,
  118493. configurable: true
  118494. });
  118495. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  118496. /**
  118497. * Gets the perf counter used for draw calls
  118498. */
  118499. get: function () {
  118500. return this.scene.getEngine()._drawCalls;
  118501. },
  118502. enumerable: true,
  118503. configurable: true
  118504. });
  118505. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  118506. /**
  118507. * Gets the perf counter used for texture collisions
  118508. */
  118509. get: function () {
  118510. return this.scene.getEngine()._textureCollisions;
  118511. },
  118512. enumerable: true,
  118513. configurable: true
  118514. });
  118515. /**
  118516. * Dispose and release associated resources.
  118517. */
  118518. SceneInstrumentation.prototype.dispose = function () {
  118519. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  118520. this._onAfterRenderObserver = null;
  118521. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  118522. this._onBeforeActiveMeshesEvaluationObserver = null;
  118523. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  118524. this._onAfterActiveMeshesEvaluationObserver = null;
  118525. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  118526. this._onBeforeRenderTargetsRenderObserver = null;
  118527. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  118528. this._onAfterRenderTargetsRenderObserver = null;
  118529. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  118530. this._onBeforeAnimationsObserver = null;
  118531. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  118532. this._onBeforeParticlesRenderingObserver = null;
  118533. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  118534. this._onAfterParticlesRenderingObserver = null;
  118535. if (this._onBeforeSpritesRenderingObserver) {
  118536. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  118537. this._onBeforeSpritesRenderingObserver = null;
  118538. }
  118539. if (this._onAfterSpritesRenderingObserver) {
  118540. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  118541. this._onAfterSpritesRenderingObserver = null;
  118542. }
  118543. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  118544. this._onBeforeDrawPhaseObserver = null;
  118545. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  118546. this._onAfterDrawPhaseObserver = null;
  118547. if (this._onBeforePhysicsObserver) {
  118548. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  118549. this._onBeforePhysicsObserver = null;
  118550. }
  118551. if (this._onAfterPhysicsObserver) {
  118552. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  118553. this._onAfterPhysicsObserver = null;
  118554. }
  118555. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  118556. this._onAfterAnimationsObserver = null;
  118557. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  118558. this._onBeforeCameraRenderObserver = null;
  118559. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  118560. this._onAfterCameraRenderObserver = null;
  118561. this.scene = null;
  118562. };
  118563. return SceneInstrumentation;
  118564. }());
  118565. BABYLON.SceneInstrumentation = SceneInstrumentation;
  118566. })(BABYLON || (BABYLON = {}));
  118567. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  118568. var BABYLON;
  118569. (function (BABYLON) {
  118570. /**
  118571. * @hidden
  118572. **/
  118573. var _TimeToken = /** @class */ (function () {
  118574. function _TimeToken() {
  118575. this._timeElapsedQueryEnded = false;
  118576. }
  118577. return _TimeToken;
  118578. }());
  118579. BABYLON._TimeToken = _TimeToken;
  118580. })(BABYLON || (BABYLON = {}));
  118581. //# sourceMappingURL=babylon.timeToken.js.map
  118582. var BABYLON;
  118583. (function (BABYLON) {
  118584. /**
  118585. * Background material defines definition.
  118586. * @hidden Mainly internal Use
  118587. */
  118588. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  118589. __extends(BackgroundMaterialDefines, _super);
  118590. /**
  118591. * Constructor of the defines.
  118592. */
  118593. function BackgroundMaterialDefines() {
  118594. var _this = _super.call(this) || this;
  118595. /**
  118596. * True if the diffuse texture is in use.
  118597. */
  118598. _this.DIFFUSE = false;
  118599. /**
  118600. * The direct UV channel to use.
  118601. */
  118602. _this.DIFFUSEDIRECTUV = 0;
  118603. /**
  118604. * True if the diffuse texture is in gamma space.
  118605. */
  118606. _this.GAMMADIFFUSE = false;
  118607. /**
  118608. * True if the diffuse texture has opacity in the alpha channel.
  118609. */
  118610. _this.DIFFUSEHASALPHA = false;
  118611. /**
  118612. * True if you want the material to fade to transparent at grazing angle.
  118613. */
  118614. _this.OPACITYFRESNEL = false;
  118615. /**
  118616. * True if an extra blur needs to be added in the reflection.
  118617. */
  118618. _this.REFLECTIONBLUR = false;
  118619. /**
  118620. * True if you want the material to fade to reflection at grazing angle.
  118621. */
  118622. _this.REFLECTIONFRESNEL = false;
  118623. /**
  118624. * True if you want the material to falloff as far as you move away from the scene center.
  118625. */
  118626. _this.REFLECTIONFALLOFF = false;
  118627. /**
  118628. * False if the current Webgl implementation does not support the texture lod extension.
  118629. */
  118630. _this.TEXTURELODSUPPORT = false;
  118631. /**
  118632. * True to ensure the data are premultiplied.
  118633. */
  118634. _this.PREMULTIPLYALPHA = false;
  118635. /**
  118636. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  118637. */
  118638. _this.USERGBCOLOR = false;
  118639. /**
  118640. * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color
  118641. * stays aligned with the desired configuration.
  118642. */
  118643. _this.USEHIGHLIGHTANDSHADOWCOLORS = false;
  118644. /**
  118645. * True to add noise in order to reduce the banding effect.
  118646. */
  118647. _this.NOISE = false;
  118648. /**
  118649. * is the reflection texture in BGR color scheme?
  118650. * Mainly used to solve a bug in ios10 video tag
  118651. */
  118652. _this.REFLECTIONBGR = false;
  118653. _this.IMAGEPROCESSING = false;
  118654. _this.VIGNETTE = false;
  118655. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  118656. _this.VIGNETTEBLENDMODEOPAQUE = false;
  118657. _this.TONEMAPPING = false;
  118658. _this.TONEMAPPING_ACES = false;
  118659. _this.CONTRAST = false;
  118660. _this.COLORCURVES = false;
  118661. _this.COLORGRADING = false;
  118662. _this.COLORGRADING3D = false;
  118663. _this.SAMPLER3DGREENDEPTH = false;
  118664. _this.SAMPLER3DBGRMAP = false;
  118665. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  118666. _this.EXPOSURE = false;
  118667. // Reflection.
  118668. _this.REFLECTION = false;
  118669. _this.REFLECTIONMAP_3D = false;
  118670. _this.REFLECTIONMAP_SPHERICAL = false;
  118671. _this.REFLECTIONMAP_PLANAR = false;
  118672. _this.REFLECTIONMAP_CUBIC = false;
  118673. _this.REFLECTIONMAP_PROJECTION = false;
  118674. _this.REFLECTIONMAP_SKYBOX = false;
  118675. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  118676. _this.REFLECTIONMAP_EXPLICIT = false;
  118677. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  118678. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  118679. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  118680. _this.INVERTCUBICMAP = false;
  118681. _this.REFLECTIONMAP_OPPOSITEZ = false;
  118682. _this.LODINREFLECTIONALPHA = false;
  118683. _this.GAMMAREFLECTION = false;
  118684. _this.RGBDREFLECTION = false;
  118685. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  118686. // Default BJS.
  118687. _this.MAINUV1 = false;
  118688. _this.MAINUV2 = false;
  118689. _this.UV1 = false;
  118690. _this.UV2 = false;
  118691. _this.CLIPPLANE = false;
  118692. _this.CLIPPLANE2 = false;
  118693. _this.CLIPPLANE3 = false;
  118694. _this.CLIPPLANE4 = false;
  118695. _this.POINTSIZE = false;
  118696. _this.FOG = false;
  118697. _this.NORMAL = false;
  118698. _this.NUM_BONE_INFLUENCERS = 0;
  118699. _this.BonesPerMesh = 0;
  118700. _this.INSTANCES = false;
  118701. _this.SHADOWFLOAT = false;
  118702. _this.rebuild();
  118703. return _this;
  118704. }
  118705. return BackgroundMaterialDefines;
  118706. }(BABYLON.MaterialDefines));
  118707. /**
  118708. * Background material used to create an efficient environement around your scene.
  118709. */
  118710. var BackgroundMaterial = /** @class */ (function (_super) {
  118711. __extends(BackgroundMaterial, _super);
  118712. /**
  118713. * Instantiates a Background Material in the given scene
  118714. * @param name The friendly name of the material
  118715. * @param scene The scene to add the material to
  118716. */
  118717. function BackgroundMaterial(name, scene) {
  118718. var _this = _super.call(this, name, scene) || this;
  118719. /**
  118720. * Key light Color (multiply against the environement texture)
  118721. */
  118722. _this.primaryColor = BABYLON.Color3.White();
  118723. _this._primaryColorShadowLevel = 0;
  118724. _this._primaryColorHighlightLevel = 0;
  118725. /**
  118726. * Reflection Texture used in the material.
  118727. * Should be author in a specific way for the best result (refer to the documentation).
  118728. */
  118729. _this.reflectionTexture = null;
  118730. /**
  118731. * Reflection Texture level of blur.
  118732. *
  118733. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  118734. * texture twice.
  118735. */
  118736. _this.reflectionBlur = 0;
  118737. /**
  118738. * Diffuse Texture used in the material.
  118739. * Should be author in a specific way for the best result (refer to the documentation).
  118740. */
  118741. _this.diffuseTexture = null;
  118742. _this._shadowLights = null;
  118743. /**
  118744. * Specify the list of lights casting shadow on the material.
  118745. * All scene shadow lights will be included if null.
  118746. */
  118747. _this.shadowLights = null;
  118748. /**
  118749. * Helps adjusting the shadow to a softer level if required.
  118750. * 0 means black shadows and 1 means no shadows.
  118751. */
  118752. _this.shadowLevel = 0;
  118753. /**
  118754. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  118755. * It is usually zero but might be interesting to modify according to your setup.
  118756. */
  118757. _this.sceneCenter = BABYLON.Vector3.Zero();
  118758. /**
  118759. * This helps specifying that the material is falling off to the sky box at grazing angle.
  118760. * This helps ensuring a nice transition when the camera goes under the ground.
  118761. */
  118762. _this.opacityFresnel = true;
  118763. /**
  118764. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  118765. * This helps adding a mirror texture on the ground.
  118766. */
  118767. _this.reflectionFresnel = false;
  118768. /**
  118769. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  118770. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  118771. */
  118772. _this.reflectionFalloffDistance = 0.0;
  118773. /**
  118774. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  118775. */
  118776. _this.reflectionAmount = 1.0;
  118777. /**
  118778. * This specifies the weight of the reflection at grazing angle.
  118779. */
  118780. _this.reflectionReflectance0 = 0.05;
  118781. /**
  118782. * This specifies the weight of the reflection at a perpendicular point of view.
  118783. */
  118784. _this.reflectionReflectance90 = 0.5;
  118785. /**
  118786. * Helps to directly use the maps channels instead of their level.
  118787. */
  118788. _this.useRGBColor = true;
  118789. /**
  118790. * This helps reducing the banding effect that could occur on the background.
  118791. */
  118792. _this.enableNoise = false;
  118793. _this._fovMultiplier = 1.0;
  118794. /**
  118795. * Enable the FOV adjustment feature controlled by fovMultiplier.
  118796. */
  118797. _this.useEquirectangularFOV = false;
  118798. _this._maxSimultaneousLights = 4;
  118799. /**
  118800. * Number of Simultaneous lights allowed on the material.
  118801. */
  118802. _this.maxSimultaneousLights = 4;
  118803. /**
  118804. * Keep track of the image processing observer to allow dispose and replace.
  118805. */
  118806. _this._imageProcessingObserver = null;
  118807. /**
  118808. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  118809. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  118810. */
  118811. _this.switchToBGR = false;
  118812. // Temp values kept as cache in the material.
  118813. _this._renderTargets = new BABYLON.SmartArray(16);
  118814. _this._reflectionControls = BABYLON.Vector4.Zero();
  118815. _this._white = BABYLON.Color3.White();
  118816. _this._primaryShadowColor = BABYLON.Color3.Black();
  118817. _this._primaryHighlightColor = BABYLON.Color3.Black();
  118818. // Setup the default processing configuration to the scene.
  118819. _this._attachImageProcessingConfiguration(null);
  118820. _this.getRenderTargetTextures = function () {
  118821. _this._renderTargets.reset();
  118822. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  118823. _this._renderTargets.push(_this._diffuseTexture);
  118824. }
  118825. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  118826. _this._renderTargets.push(_this._reflectionTexture);
  118827. }
  118828. return _this._renderTargets;
  118829. };
  118830. return _this;
  118831. }
  118832. Object.defineProperty(BackgroundMaterial.prototype, "_perceptualColor", {
  118833. /**
  118834. * Experimental Internal Use Only.
  118835. *
  118836. * Key light Color in "perceptual value" meaning the color you would like to see on screen.
  118837. * This acts as a helper to set the primary color to a more "human friendly" value.
  118838. * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the
  118839. * output color as close as possible from the chosen value.
  118840. * (This does not account for contrast color grading and color curves as they are considered post effect and not directly
  118841. * part of lighting setup.)
  118842. */
  118843. get: function () {
  118844. return this.__perceptualColor;
  118845. },
  118846. set: function (value) {
  118847. this.__perceptualColor = value;
  118848. this._computePrimaryColorFromPerceptualColor();
  118849. this._markAllSubMeshesAsLightsDirty();
  118850. },
  118851. enumerable: true,
  118852. configurable: true
  118853. });
  118854. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorShadowLevel", {
  118855. /**
  118856. * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.
  118857. * The color opposite to the primary color is used at the level chosen to define what the black area would look.
  118858. */
  118859. get: function () {
  118860. return this._primaryColorShadowLevel;
  118861. },
  118862. set: function (value) {
  118863. this._primaryColorShadowLevel = value;
  118864. this._computePrimaryColors();
  118865. this._markAllSubMeshesAsLightsDirty();
  118866. },
  118867. enumerable: true,
  118868. configurable: true
  118869. });
  118870. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorHighlightLevel", {
  118871. /**
  118872. * Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors.
  118873. * The primary color is used at the level chosen to define what the white area would look.
  118874. */
  118875. get: function () {
  118876. return this._primaryColorHighlightLevel;
  118877. },
  118878. set: function (value) {
  118879. this._primaryColorHighlightLevel = value;
  118880. this._computePrimaryColors();
  118881. this._markAllSubMeshesAsLightsDirty();
  118882. },
  118883. enumerable: true,
  118884. configurable: true
  118885. });
  118886. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  118887. /**
  118888. * Sets the reflection reflectance fresnel values according to the default standard
  118889. * empirically know to work well :-)
  118890. */
  118891. set: function (value) {
  118892. var reflectionWeight = value;
  118893. if (reflectionWeight < 0.5) {
  118894. reflectionWeight = reflectionWeight * 2.0;
  118895. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  118896. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  118897. }
  118898. else {
  118899. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  118900. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  118901. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  118902. }
  118903. },
  118904. enumerable: true,
  118905. configurable: true
  118906. });
  118907. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  118908. /**
  118909. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  118910. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  118911. * Recommended to be keep at 1.0 except for special cases.
  118912. */
  118913. get: function () {
  118914. return this._fovMultiplier;
  118915. },
  118916. set: function (value) {
  118917. if (isNaN(value)) {
  118918. value = 1.0;
  118919. }
  118920. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  118921. },
  118922. enumerable: true,
  118923. configurable: true
  118924. });
  118925. /**
  118926. * Attaches a new image processing configuration to the PBR Material.
  118927. * @param configuration (if null the scene configuration will be use)
  118928. */
  118929. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  118930. var _this = this;
  118931. if (configuration === this._imageProcessingConfiguration) {
  118932. return;
  118933. }
  118934. // Detaches observer.
  118935. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  118936. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  118937. }
  118938. // Pick the scene configuration if needed.
  118939. if (!configuration) {
  118940. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  118941. }
  118942. else {
  118943. this._imageProcessingConfiguration = configuration;
  118944. }
  118945. // Attaches observer.
  118946. if (this._imageProcessingConfiguration) {
  118947. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  118948. _this._computePrimaryColorFromPerceptualColor();
  118949. _this._markAllSubMeshesAsImageProcessingDirty();
  118950. });
  118951. }
  118952. };
  118953. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  118954. /**
  118955. * Gets the image processing configuration used either in this material.
  118956. */
  118957. get: function () {
  118958. return this._imageProcessingConfiguration;
  118959. },
  118960. /**
  118961. * Sets the Default image processing configuration used either in the this material.
  118962. *
  118963. * If sets to null, the scene one is in use.
  118964. */
  118965. set: function (value) {
  118966. this._attachImageProcessingConfiguration(value);
  118967. // Ensure the effect will be rebuilt.
  118968. this._markAllSubMeshesAsTexturesDirty();
  118969. },
  118970. enumerable: true,
  118971. configurable: true
  118972. });
  118973. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  118974. /**
  118975. * Gets wether the color curves effect is enabled.
  118976. */
  118977. get: function () {
  118978. return this.imageProcessingConfiguration.colorCurvesEnabled;
  118979. },
  118980. /**
  118981. * Sets wether the color curves effect is enabled.
  118982. */
  118983. set: function (value) {
  118984. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  118985. },
  118986. enumerable: true,
  118987. configurable: true
  118988. });
  118989. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  118990. /**
  118991. * Gets wether the color grading effect is enabled.
  118992. */
  118993. get: function () {
  118994. return this.imageProcessingConfiguration.colorGradingEnabled;
  118995. },
  118996. /**
  118997. * Gets wether the color grading effect is enabled.
  118998. */
  118999. set: function (value) {
  119000. this.imageProcessingConfiguration.colorGradingEnabled = value;
  119001. },
  119002. enumerable: true,
  119003. configurable: true
  119004. });
  119005. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  119006. /**
  119007. * Gets wether tonemapping is enabled or not.
  119008. */
  119009. get: function () {
  119010. return this._imageProcessingConfiguration.toneMappingEnabled;
  119011. },
  119012. /**
  119013. * Sets wether tonemapping is enabled or not
  119014. */
  119015. set: function (value) {
  119016. this._imageProcessingConfiguration.toneMappingEnabled = value;
  119017. },
  119018. enumerable: true,
  119019. configurable: true
  119020. });
  119021. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  119022. /**
  119023. * The camera exposure used on this material.
  119024. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  119025. * This corresponds to a photographic exposure.
  119026. */
  119027. get: function () {
  119028. return this._imageProcessingConfiguration.exposure;
  119029. },
  119030. /**
  119031. * The camera exposure used on this material.
  119032. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  119033. * This corresponds to a photographic exposure.
  119034. */
  119035. set: function (value) {
  119036. this._imageProcessingConfiguration.exposure = value;
  119037. },
  119038. enumerable: true,
  119039. configurable: true
  119040. });
  119041. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  119042. /**
  119043. * Gets The camera contrast used on this material.
  119044. */
  119045. get: function () {
  119046. return this._imageProcessingConfiguration.contrast;
  119047. },
  119048. /**
  119049. * Sets The camera contrast used on this material.
  119050. */
  119051. set: function (value) {
  119052. this._imageProcessingConfiguration.contrast = value;
  119053. },
  119054. enumerable: true,
  119055. configurable: true
  119056. });
  119057. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  119058. /**
  119059. * Gets the Color Grading 2D Lookup Texture.
  119060. */
  119061. get: function () {
  119062. return this._imageProcessingConfiguration.colorGradingTexture;
  119063. },
  119064. /**
  119065. * Sets the Color Grading 2D Lookup Texture.
  119066. */
  119067. set: function (value) {
  119068. this.imageProcessingConfiguration.colorGradingTexture = value;
  119069. },
  119070. enumerable: true,
  119071. configurable: true
  119072. });
  119073. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  119074. /**
  119075. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  119076. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  119077. * 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;
  119078. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  119079. */
  119080. get: function () {
  119081. return this.imageProcessingConfiguration.colorCurves;
  119082. },
  119083. /**
  119084. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  119085. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  119086. * 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;
  119087. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  119088. */
  119089. set: function (value) {
  119090. this.imageProcessingConfiguration.colorCurves = value;
  119091. },
  119092. enumerable: true,
  119093. configurable: true
  119094. });
  119095. Object.defineProperty(BackgroundMaterial.prototype, "hasRenderTargetTextures", {
  119096. /**
  119097. * Gets a boolean indicating that current material needs to register RTT
  119098. */
  119099. get: function () {
  119100. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  119101. return true;
  119102. }
  119103. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  119104. return true;
  119105. }
  119106. return false;
  119107. },
  119108. enumerable: true,
  119109. configurable: true
  119110. });
  119111. /**
  119112. * The entire material has been created in order to prevent overdraw.
  119113. * @returns false
  119114. */
  119115. BackgroundMaterial.prototype.needAlphaTesting = function () {
  119116. return true;
  119117. };
  119118. /**
  119119. * The entire material has been created in order to prevent overdraw.
  119120. * @returns true if blending is enable
  119121. */
  119122. BackgroundMaterial.prototype.needAlphaBlending = function () {
  119123. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  119124. };
  119125. /**
  119126. * Checks wether the material is ready to be rendered for a given mesh.
  119127. * @param mesh The mesh to render
  119128. * @param subMesh The submesh to check against
  119129. * @param useInstances Specify wether or not the material is used with instances
  119130. * @returns true if all the dependencies are ready (Textures, Effects...)
  119131. */
  119132. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  119133. var _this = this;
  119134. if (useInstances === void 0) { useInstances = false; }
  119135. if (subMesh.effect && this.isFrozen) {
  119136. if (this._wasPreviouslyReady) {
  119137. return true;
  119138. }
  119139. }
  119140. if (!subMesh._materialDefines) {
  119141. subMesh._materialDefines = new BackgroundMaterialDefines();
  119142. }
  119143. var scene = this.getScene();
  119144. var defines = subMesh._materialDefines;
  119145. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  119146. if (defines._renderId === scene.getRenderId()) {
  119147. return true;
  119148. }
  119149. }
  119150. var engine = scene.getEngine();
  119151. // Lights
  119152. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  119153. defines._needNormals = true;
  119154. // Textures
  119155. if (defines._areTexturesDirty) {
  119156. defines._needUVs = false;
  119157. if (scene.texturesEnabled) {
  119158. if (scene.getEngine().getCaps().textureLOD) {
  119159. defines.TEXTURELODSUPPORT = true;
  119160. }
  119161. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  119162. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  119163. return false;
  119164. }
  119165. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  119166. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  119167. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  119168. defines.OPACITYFRESNEL = this._opacityFresnel;
  119169. }
  119170. else {
  119171. defines.DIFFUSE = false;
  119172. defines.DIFFUSEHASALPHA = false;
  119173. defines.GAMMADIFFUSE = false;
  119174. defines.OPACITYFRESNEL = false;
  119175. }
  119176. var reflectionTexture = this._reflectionTexture;
  119177. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  119178. if (!reflectionTexture.isReadyOrNotBlocking()) {
  119179. return false;
  119180. }
  119181. defines.REFLECTION = true;
  119182. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  119183. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  119184. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  119185. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  119186. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  119187. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  119188. defines.REFLECTIONBGR = this.switchToBGR;
  119189. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  119190. defines.INVERTCUBICMAP = true;
  119191. }
  119192. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  119193. switch (reflectionTexture.coordinatesMode) {
  119194. case BABYLON.Texture.EXPLICIT_MODE:
  119195. defines.REFLECTIONMAP_EXPLICIT = true;
  119196. break;
  119197. case BABYLON.Texture.PLANAR_MODE:
  119198. defines.REFLECTIONMAP_PLANAR = true;
  119199. break;
  119200. case BABYLON.Texture.PROJECTION_MODE:
  119201. defines.REFLECTIONMAP_PROJECTION = true;
  119202. break;
  119203. case BABYLON.Texture.SKYBOX_MODE:
  119204. defines.REFLECTIONMAP_SKYBOX = true;
  119205. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !reflectionTexture.getReflectionTextureMatrix().isIdentity();
  119206. break;
  119207. case BABYLON.Texture.SPHERICAL_MODE:
  119208. defines.REFLECTIONMAP_SPHERICAL = true;
  119209. break;
  119210. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  119211. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  119212. break;
  119213. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  119214. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  119215. break;
  119216. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  119217. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  119218. break;
  119219. case BABYLON.Texture.CUBIC_MODE:
  119220. case BABYLON.Texture.INVCUBIC_MODE:
  119221. default:
  119222. defines.REFLECTIONMAP_CUBIC = true;
  119223. break;
  119224. }
  119225. if (this.reflectionFresnel) {
  119226. defines.REFLECTIONFRESNEL = true;
  119227. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  119228. this._reflectionControls.x = this.reflectionAmount;
  119229. this._reflectionControls.y = this.reflectionReflectance0;
  119230. this._reflectionControls.z = this.reflectionReflectance90;
  119231. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  119232. }
  119233. else {
  119234. defines.REFLECTIONFRESNEL = false;
  119235. defines.REFLECTIONFALLOFF = false;
  119236. }
  119237. }
  119238. else {
  119239. defines.REFLECTION = false;
  119240. defines.REFLECTIONFRESNEL = false;
  119241. defines.REFLECTIONFALLOFF = false;
  119242. defines.REFLECTIONBLUR = false;
  119243. defines.REFLECTIONMAP_3D = false;
  119244. defines.REFLECTIONMAP_SPHERICAL = false;
  119245. defines.REFLECTIONMAP_PLANAR = false;
  119246. defines.REFLECTIONMAP_CUBIC = false;
  119247. defines.REFLECTIONMAP_PROJECTION = false;
  119248. defines.REFLECTIONMAP_SKYBOX = false;
  119249. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  119250. defines.REFLECTIONMAP_EXPLICIT = false;
  119251. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  119252. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  119253. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  119254. defines.INVERTCUBICMAP = false;
  119255. defines.REFLECTIONMAP_OPPOSITEZ = false;
  119256. defines.LODINREFLECTIONALPHA = false;
  119257. defines.GAMMAREFLECTION = false;
  119258. defines.RGBDREFLECTION = false;
  119259. }
  119260. }
  119261. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  119262. defines.USERGBCOLOR = this._useRGBColor;
  119263. defines.NOISE = this._enableNoise;
  119264. }
  119265. if (defines._areLightsDirty) {
  119266. defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);
  119267. }
  119268. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  119269. if (!this._imageProcessingConfiguration.isReady()) {
  119270. return false;
  119271. }
  119272. this._imageProcessingConfiguration.prepareDefines(defines);
  119273. }
  119274. // Misc.
  119275. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  119276. // Values that need to be evaluated on every frame
  119277. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  119278. // Attribs
  119279. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  119280. if (mesh) {
  119281. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  119282. mesh.createNormals(true);
  119283. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  119284. }
  119285. }
  119286. }
  119287. // Get correct effect
  119288. if (defines.isDirty) {
  119289. defines.markAsProcessed();
  119290. scene.resetCachedMaterial();
  119291. // Fallbacks
  119292. var fallbacks = new BABYLON.EffectFallbacks();
  119293. if (defines.FOG) {
  119294. fallbacks.addFallback(0, "FOG");
  119295. }
  119296. if (defines.POINTSIZE) {
  119297. fallbacks.addFallback(1, "POINTSIZE");
  119298. }
  119299. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  119300. if (defines.NUM_BONE_INFLUENCERS > 0) {
  119301. fallbacks.addCPUSkinningFallback(0, mesh);
  119302. }
  119303. //Attributes
  119304. var attribs = [BABYLON.VertexBuffer.PositionKind];
  119305. if (defines.NORMAL) {
  119306. attribs.push(BABYLON.VertexBuffer.NormalKind);
  119307. }
  119308. if (defines.UV1) {
  119309. attribs.push(BABYLON.VertexBuffer.UVKind);
  119310. }
  119311. if (defines.UV2) {
  119312. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  119313. }
  119314. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  119315. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  119316. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  119317. "vFogInfos", "vFogColor", "pointSize",
  119318. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "mBones",
  119319. "vPrimaryColor", "vPrimaryColorShadow",
  119320. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  119321. "shadowLevel", "alpha",
  119322. "vBackgroundCenter", "vReflectionControl",
  119323. "vDiffuseInfos", "diffuseMatrix",
  119324. ];
  119325. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  119326. var uniformBuffers = ["Material", "Scene"];
  119327. if (BABYLON.ImageProcessingConfiguration) {
  119328. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  119329. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  119330. }
  119331. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  119332. uniformsNames: uniforms,
  119333. uniformBuffersNames: uniformBuffers,
  119334. samplers: samplers,
  119335. defines: defines,
  119336. maxSimultaneousLights: this._maxSimultaneousLights
  119337. });
  119338. var onCompiled = function (effect) {
  119339. if (_this.onCompiled) {
  119340. _this.onCompiled(effect);
  119341. }
  119342. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  119343. };
  119344. var join = defines.toString();
  119345. subMesh.setEffect(scene.getEngine().createEffect("background", {
  119346. attributes: attribs,
  119347. uniformsNames: uniforms,
  119348. uniformBuffersNames: uniformBuffers,
  119349. samplers: samplers,
  119350. defines: join,
  119351. fallbacks: fallbacks,
  119352. onCompiled: onCompiled,
  119353. onError: this.onError,
  119354. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  119355. }, engine), defines);
  119356. this.buildUniformLayout();
  119357. }
  119358. if (!subMesh.effect || !subMesh.effect.isReady()) {
  119359. return false;
  119360. }
  119361. defines._renderId = scene.getRenderId();
  119362. this._wasPreviouslyReady = true;
  119363. return true;
  119364. };
  119365. /**
  119366. * Compute the primary color according to the chosen perceptual color.
  119367. */
  119368. BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () {
  119369. if (!this.__perceptualColor) {
  119370. return;
  119371. }
  119372. this._primaryColor.copyFrom(this.__perceptualColor);
  119373. // Revert gamma space.
  119374. this._primaryColor.toLinearSpaceToRef(this._primaryColor);
  119375. // Revert image processing configuration.
  119376. if (this._imageProcessingConfiguration) {
  119377. // Revert Exposure.
  119378. this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);
  119379. }
  119380. this._computePrimaryColors();
  119381. };
  119382. /**
  119383. * Compute the highlights and shadow colors according to their chosen levels.
  119384. */
  119385. BackgroundMaterial.prototype._computePrimaryColors = function () {
  119386. if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {
  119387. return;
  119388. }
  119389. // Find the highlight color based on the configuration.
  119390. this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);
  119391. this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);
  119392. // Find the shadow color based on the configuration.
  119393. this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);
  119394. this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);
  119395. this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);
  119396. };
  119397. /**
  119398. * Build the uniform buffer used in the material.
  119399. */
  119400. BackgroundMaterial.prototype.buildUniformLayout = function () {
  119401. // Order is important !
  119402. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  119403. this._uniformBuffer.addUniform("vPrimaryColorShadow", 4);
  119404. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  119405. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  119406. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  119407. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  119408. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  119409. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  119410. this._uniformBuffer.addUniform("pointSize", 1);
  119411. this._uniformBuffer.addUniform("shadowLevel", 1);
  119412. this._uniformBuffer.addUniform("alpha", 1);
  119413. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  119414. this._uniformBuffer.addUniform("vReflectionControl", 4);
  119415. this._uniformBuffer.create();
  119416. };
  119417. /**
  119418. * Unbind the material.
  119419. */
  119420. BackgroundMaterial.prototype.unbind = function () {
  119421. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  119422. this._uniformBuffer.setTexture("diffuseSampler", null);
  119423. }
  119424. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  119425. this._uniformBuffer.setTexture("reflectionSampler", null);
  119426. }
  119427. _super.prototype.unbind.call(this);
  119428. };
  119429. /**
  119430. * Bind only the world matrix to the material.
  119431. * @param world The world matrix to bind.
  119432. */
  119433. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  119434. this._activeEffect.setMatrix("world", world);
  119435. };
  119436. /**
  119437. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  119438. * @param world The world matrix to bind.
  119439. * @param subMesh The submesh to bind for.
  119440. */
  119441. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  119442. var scene = this.getScene();
  119443. var defines = subMesh._materialDefines;
  119444. if (!defines) {
  119445. return;
  119446. }
  119447. var effect = subMesh.effect;
  119448. if (!effect) {
  119449. return;
  119450. }
  119451. this._activeEffect = effect;
  119452. // Matrices
  119453. this.bindOnlyWorldMatrix(world);
  119454. // Bones
  119455. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  119456. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  119457. if (mustRebind) {
  119458. this._uniformBuffer.bindToEffect(effect, "Material");
  119459. this.bindViewProjection(effect);
  119460. var reflectionTexture = this._reflectionTexture;
  119461. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  119462. // Texture uniforms
  119463. if (scene.texturesEnabled) {
  119464. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  119465. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  119466. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  119467. }
  119468. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  119469. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  119470. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  119471. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  119472. }
  119473. }
  119474. if (this.shadowLevel > 0) {
  119475. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  119476. }
  119477. this._uniformBuffer.updateFloat("alpha", this.alpha);
  119478. // Point size
  119479. if (this.pointsCloud) {
  119480. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  119481. }
  119482. if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {
  119483. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0);
  119484. this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0);
  119485. }
  119486. else {
  119487. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0);
  119488. }
  119489. }
  119490. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  119491. // Textures
  119492. if (scene.texturesEnabled) {
  119493. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  119494. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  119495. }
  119496. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  119497. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  119498. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  119499. }
  119500. else if (!defines.REFLECTIONBLUR) {
  119501. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  119502. }
  119503. else {
  119504. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  119505. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  119506. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  119507. }
  119508. if (defines.REFLECTIONFRESNEL) {
  119509. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  119510. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  119511. }
  119512. }
  119513. }
  119514. // Clip plane
  119515. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  119516. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  119517. }
  119518. if (mustRebind || !this.isFrozen) {
  119519. if (scene.lightsEnabled) {
  119520. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  119521. }
  119522. // View
  119523. this.bindView(effect);
  119524. // Fog
  119525. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect, true);
  119526. // image processing
  119527. if (this._imageProcessingConfiguration) {
  119528. this._imageProcessingConfiguration.bind(this._activeEffect);
  119529. }
  119530. }
  119531. this._uniformBuffer.update();
  119532. this._afterBind(mesh, this._activeEffect);
  119533. };
  119534. /**
  119535. * Dispose the material.
  119536. * @param forceDisposeEffect Force disposal of the associated effect.
  119537. * @param forceDisposeTextures Force disposal of the associated textures.
  119538. */
  119539. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  119540. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  119541. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  119542. if (forceDisposeTextures) {
  119543. if (this.diffuseTexture) {
  119544. this.diffuseTexture.dispose();
  119545. }
  119546. if (this.reflectionTexture) {
  119547. this.reflectionTexture.dispose();
  119548. }
  119549. }
  119550. this._renderTargets.dispose();
  119551. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  119552. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  119553. }
  119554. _super.prototype.dispose.call(this, forceDisposeEffect);
  119555. };
  119556. /**
  119557. * Clones the material.
  119558. * @param name The cloned name.
  119559. * @returns The cloned material.
  119560. */
  119561. BackgroundMaterial.prototype.clone = function (name) {
  119562. var _this = this;
  119563. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  119564. };
  119565. /**
  119566. * Serializes the current material to its JSON representation.
  119567. * @returns The JSON representation.
  119568. */
  119569. BackgroundMaterial.prototype.serialize = function () {
  119570. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  119571. serializationObject.customType = "BABYLON.BackgroundMaterial";
  119572. return serializationObject;
  119573. };
  119574. /**
  119575. * Gets the class name of the material
  119576. * @returns "BackgroundMaterial"
  119577. */
  119578. BackgroundMaterial.prototype.getClassName = function () {
  119579. return "BackgroundMaterial";
  119580. };
  119581. /**
  119582. * Parse a JSON input to create back a background material.
  119583. * @param source The JSON data to parse
  119584. * @param scene The scene to create the parsed material in
  119585. * @param rootUrl The root url of the assets the material depends upon
  119586. * @returns the instantiated BackgroundMaterial.
  119587. */
  119588. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  119589. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  119590. };
  119591. /**
  119592. * Standard reflectance value at parallel view angle.
  119593. */
  119594. BackgroundMaterial.StandardReflectance0 = 0.05;
  119595. /**
  119596. * Standard reflectance value at grazing angle.
  119597. */
  119598. BackgroundMaterial.StandardReflectance90 = 0.5;
  119599. __decorate([
  119600. BABYLON.serializeAsColor3()
  119601. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  119602. __decorate([
  119603. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  119604. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  119605. __decorate([
  119606. BABYLON.serializeAsColor3()
  119607. ], BackgroundMaterial.prototype, "__perceptualColor", void 0);
  119608. __decorate([
  119609. BABYLON.serialize()
  119610. ], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0);
  119611. __decorate([
  119612. BABYLON.serialize()
  119613. ], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0);
  119614. __decorate([
  119615. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  119616. ], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null);
  119617. __decorate([
  119618. BABYLON.serializeAsTexture()
  119619. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  119620. __decorate([
  119621. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  119622. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  119623. __decorate([
  119624. BABYLON.serialize()
  119625. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  119626. __decorate([
  119627. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  119628. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  119629. __decorate([
  119630. BABYLON.serializeAsTexture()
  119631. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  119632. __decorate([
  119633. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  119634. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  119635. __decorate([
  119636. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  119637. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  119638. __decorate([
  119639. BABYLON.serialize()
  119640. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  119641. __decorate([
  119642. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  119643. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  119644. __decorate([
  119645. BABYLON.serializeAsVector3()
  119646. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  119647. __decorate([
  119648. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  119649. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  119650. __decorate([
  119651. BABYLON.serialize()
  119652. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  119653. __decorate([
  119654. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  119655. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  119656. __decorate([
  119657. BABYLON.serialize()
  119658. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  119659. __decorate([
  119660. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  119661. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  119662. __decorate([
  119663. BABYLON.serialize()
  119664. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  119665. __decorate([
  119666. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  119667. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  119668. __decorate([
  119669. BABYLON.serialize()
  119670. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  119671. __decorate([
  119672. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  119673. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  119674. __decorate([
  119675. BABYLON.serialize()
  119676. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  119677. __decorate([
  119678. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  119679. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  119680. __decorate([
  119681. BABYLON.serialize()
  119682. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  119683. __decorate([
  119684. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  119685. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  119686. __decorate([
  119687. BABYLON.serialize()
  119688. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  119689. __decorate([
  119690. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  119691. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  119692. __decorate([
  119693. BABYLON.serialize()
  119694. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  119695. __decorate([
  119696. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  119697. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  119698. __decorate([
  119699. BABYLON.serialize()
  119700. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  119701. __decorate([
  119702. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  119703. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  119704. __decorate([
  119705. BABYLON.serializeAsImageProcessingConfiguration()
  119706. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  119707. return BackgroundMaterial;
  119708. }(BABYLON.PushMaterial));
  119709. BABYLON.BackgroundMaterial = BackgroundMaterial;
  119710. })(BABYLON || (BABYLON = {}));
  119711. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  119712. var __assign = (this && this.__assign) || function () {
  119713. __assign = Object.assign || function(t) {
  119714. for (var s, i = 1, n = arguments.length; i < n; i++) {
  119715. s = arguments[i];
  119716. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  119717. t[p] = s[p];
  119718. }
  119719. return t;
  119720. };
  119721. return __assign.apply(this, arguments);
  119722. };
  119723. var BABYLON;
  119724. (function (BABYLON) {
  119725. /**
  119726. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  119727. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  119728. * It also helps with the default setup of your imageProcessing configuration.
  119729. */
  119730. var EnvironmentHelper = /** @class */ (function () {
  119731. /**
  119732. * constructor
  119733. * @param options
  119734. * @param scene The scene to add the material to
  119735. */
  119736. function EnvironmentHelper(options, scene) {
  119737. var _this = this;
  119738. this._errorHandler = function (message, exception) {
  119739. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  119740. };
  119741. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  119742. this._scene = scene;
  119743. this.onErrorObservable = new BABYLON.Observable();
  119744. this._setupBackground();
  119745. this._setupImageProcessing();
  119746. }
  119747. /**
  119748. * Creates the default options for the helper.
  119749. */
  119750. EnvironmentHelper._getDefaultOptions = function () {
  119751. return {
  119752. createGround: true,
  119753. groundSize: 15,
  119754. groundTexture: this._groundTextureCDNUrl,
  119755. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  119756. groundOpacity: 0.9,
  119757. enableGroundShadow: true,
  119758. groundShadowLevel: 0.5,
  119759. enableGroundMirror: false,
  119760. groundMirrorSizeRatio: 0.3,
  119761. groundMirrorBlurKernel: 64,
  119762. groundMirrorAmount: 1,
  119763. groundMirrorFresnelWeight: 1,
  119764. groundMirrorFallOffDistance: 0,
  119765. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  119766. groundYBias: 0.00001,
  119767. createSkybox: true,
  119768. skyboxSize: 20,
  119769. skyboxTexture: this._skyboxTextureCDNUrl,
  119770. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  119771. backgroundYRotation: 0,
  119772. sizeAuto: true,
  119773. rootPosition: BABYLON.Vector3.Zero(),
  119774. setupImageProcessing: true,
  119775. environmentTexture: this._environmentTextureCDNUrl,
  119776. cameraExposure: 0.8,
  119777. cameraContrast: 1.2,
  119778. toneMappingEnabled: true,
  119779. };
  119780. };
  119781. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  119782. /**
  119783. * Gets the root mesh created by the helper.
  119784. */
  119785. get: function () {
  119786. return this._rootMesh;
  119787. },
  119788. enumerable: true,
  119789. configurable: true
  119790. });
  119791. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  119792. /**
  119793. * Gets the skybox created by the helper.
  119794. */
  119795. get: function () {
  119796. return this._skybox;
  119797. },
  119798. enumerable: true,
  119799. configurable: true
  119800. });
  119801. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  119802. /**
  119803. * Gets the skybox texture created by the helper.
  119804. */
  119805. get: function () {
  119806. return this._skyboxTexture;
  119807. },
  119808. enumerable: true,
  119809. configurable: true
  119810. });
  119811. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  119812. /**
  119813. * Gets the skybox material created by the helper.
  119814. */
  119815. get: function () {
  119816. return this._skyboxMaterial;
  119817. },
  119818. enumerable: true,
  119819. configurable: true
  119820. });
  119821. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  119822. /**
  119823. * Gets the ground mesh created by the helper.
  119824. */
  119825. get: function () {
  119826. return this._ground;
  119827. },
  119828. enumerable: true,
  119829. configurable: true
  119830. });
  119831. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  119832. /**
  119833. * Gets the ground texture created by the helper.
  119834. */
  119835. get: function () {
  119836. return this._groundTexture;
  119837. },
  119838. enumerable: true,
  119839. configurable: true
  119840. });
  119841. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  119842. /**
  119843. * Gets the ground mirror created by the helper.
  119844. */
  119845. get: function () {
  119846. return this._groundMirror;
  119847. },
  119848. enumerable: true,
  119849. configurable: true
  119850. });
  119851. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  119852. /**
  119853. * Gets the ground mirror render list to helps pushing the meshes
  119854. * you wish in the ground reflection.
  119855. */
  119856. get: function () {
  119857. if (this._groundMirror) {
  119858. return this._groundMirror.renderList;
  119859. }
  119860. return null;
  119861. },
  119862. enumerable: true,
  119863. configurable: true
  119864. });
  119865. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  119866. /**
  119867. * Gets the ground material created by the helper.
  119868. */
  119869. get: function () {
  119870. return this._groundMaterial;
  119871. },
  119872. enumerable: true,
  119873. configurable: true
  119874. });
  119875. /**
  119876. * Updates the background according to the new options
  119877. * @param options
  119878. */
  119879. EnvironmentHelper.prototype.updateOptions = function (options) {
  119880. var newOptions = __assign({}, this._options, options);
  119881. if (this._ground && !newOptions.createGround) {
  119882. this._ground.dispose();
  119883. this._ground = null;
  119884. }
  119885. if (this._groundMaterial && !newOptions.createGround) {
  119886. this._groundMaterial.dispose();
  119887. this._groundMaterial = null;
  119888. }
  119889. if (this._groundTexture) {
  119890. if (this._options.groundTexture != newOptions.groundTexture) {
  119891. this._groundTexture.dispose();
  119892. this._groundTexture = null;
  119893. }
  119894. }
  119895. if (this._skybox && !newOptions.createSkybox) {
  119896. this._skybox.dispose();
  119897. this._skybox = null;
  119898. }
  119899. if (this._skyboxMaterial && !newOptions.createSkybox) {
  119900. this._skyboxMaterial.dispose();
  119901. this._skyboxMaterial = null;
  119902. }
  119903. if (this._skyboxTexture) {
  119904. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  119905. this._skyboxTexture.dispose();
  119906. this._skyboxTexture = null;
  119907. }
  119908. }
  119909. if (this._groundMirror && !newOptions.enableGroundMirror) {
  119910. this._groundMirror.dispose();
  119911. this._groundMirror = null;
  119912. }
  119913. if (this._scene.environmentTexture) {
  119914. if (this._options.environmentTexture != newOptions.environmentTexture) {
  119915. this._scene.environmentTexture.dispose();
  119916. }
  119917. }
  119918. this._options = newOptions;
  119919. this._setupBackground();
  119920. this._setupImageProcessing();
  119921. };
  119922. /**
  119923. * Sets the primary color of all the available elements.
  119924. * @param color the main color to affect to the ground and the background
  119925. */
  119926. EnvironmentHelper.prototype.setMainColor = function (color) {
  119927. if (this.groundMaterial) {
  119928. this.groundMaterial.primaryColor = color;
  119929. }
  119930. if (this.skyboxMaterial) {
  119931. this.skyboxMaterial.primaryColor = color;
  119932. }
  119933. if (this.groundMirror) {
  119934. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  119935. }
  119936. };
  119937. /**
  119938. * Setup the image processing according to the specified options.
  119939. */
  119940. EnvironmentHelper.prototype._setupImageProcessing = function () {
  119941. if (this._options.setupImageProcessing) {
  119942. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  119943. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  119944. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  119945. this._setupEnvironmentTexture();
  119946. }
  119947. };
  119948. /**
  119949. * Setup the environment texture according to the specified options.
  119950. */
  119951. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  119952. if (this._scene.environmentTexture) {
  119953. return;
  119954. }
  119955. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  119956. this._scene.environmentTexture = this._options.environmentTexture;
  119957. return;
  119958. }
  119959. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  119960. this._scene.environmentTexture = environmentTexture;
  119961. };
  119962. /**
  119963. * Setup the background according to the specified options.
  119964. */
  119965. EnvironmentHelper.prototype._setupBackground = function () {
  119966. if (!this._rootMesh) {
  119967. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  119968. }
  119969. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  119970. var sceneSize = this._getSceneSize();
  119971. if (this._options.createGround) {
  119972. this._setupGround(sceneSize);
  119973. this._setupGroundMaterial();
  119974. this._setupGroundDiffuseTexture();
  119975. if (this._options.enableGroundMirror) {
  119976. this._setupGroundMirrorTexture(sceneSize);
  119977. }
  119978. this._setupMirrorInGroundMaterial();
  119979. }
  119980. if (this._options.createSkybox) {
  119981. this._setupSkybox(sceneSize);
  119982. this._setupSkyboxMaterial();
  119983. this._setupSkyboxReflectionTexture();
  119984. }
  119985. this._rootMesh.position.x = sceneSize.rootPosition.x;
  119986. this._rootMesh.position.z = sceneSize.rootPosition.z;
  119987. this._rootMesh.position.y = sceneSize.rootPosition.y;
  119988. };
  119989. /**
  119990. * Get the scene sizes according to the setup.
  119991. */
  119992. EnvironmentHelper.prototype._getSceneSize = function () {
  119993. var _this = this;
  119994. var groundSize = this._options.groundSize;
  119995. var skyboxSize = this._options.skyboxSize;
  119996. var rootPosition = this._options.rootPosition;
  119997. if (!this._scene.meshes || this._scene.meshes.length === 1) { // 1 only means the root of the helper.
  119998. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  119999. }
  120000. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  120001. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  120002. });
  120003. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  120004. if (this._options.sizeAuto) {
  120005. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  120006. this._scene.activeCamera.upperRadiusLimit) {
  120007. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  120008. skyboxSize = groundSize;
  120009. }
  120010. var sceneDiagonalLenght = sceneDiagonal.length();
  120011. if (sceneDiagonalLenght > groundSize) {
  120012. groundSize = sceneDiagonalLenght * 2;
  120013. skyboxSize = groundSize;
  120014. }
  120015. // 10 % bigger.
  120016. groundSize *= 1.1;
  120017. skyboxSize *= 1.5;
  120018. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  120019. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  120020. }
  120021. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  120022. };
  120023. /**
  120024. * Setup the ground according to the specified options.
  120025. */
  120026. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  120027. var _this = this;
  120028. if (!this._ground || this._ground.isDisposed()) {
  120029. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  120030. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  120031. this._ground.parent = this._rootMesh;
  120032. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  120033. }
  120034. this._ground.receiveShadows = this._options.enableGroundShadow;
  120035. };
  120036. /**
  120037. * Setup the ground material according to the specified options.
  120038. */
  120039. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  120040. if (!this._groundMaterial) {
  120041. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  120042. }
  120043. this._groundMaterial.alpha = this._options.groundOpacity;
  120044. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  120045. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  120046. this._groundMaterial.primaryColor = this._options.groundColor;
  120047. this._groundMaterial.useRGBColor = false;
  120048. this._groundMaterial.enableNoise = true;
  120049. if (this._ground) {
  120050. this._ground.material = this._groundMaterial;
  120051. }
  120052. };
  120053. /**
  120054. * Setup the ground diffuse texture according to the specified options.
  120055. */
  120056. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  120057. if (!this._groundMaterial) {
  120058. return;
  120059. }
  120060. if (this._groundTexture) {
  120061. return;
  120062. }
  120063. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  120064. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  120065. return;
  120066. }
  120067. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  120068. diffuseTexture.gammaSpace = false;
  120069. diffuseTexture.hasAlpha = true;
  120070. this._groundMaterial.diffuseTexture = diffuseTexture;
  120071. };
  120072. /**
  120073. * Setup the ground mirror texture according to the specified options.
  120074. */
  120075. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  120076. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  120077. if (!this._groundMirror) {
  120078. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  120079. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  120080. this._groundMirror.anisotropicFilteringLevel = 1;
  120081. this._groundMirror.wrapU = wrapping;
  120082. this._groundMirror.wrapV = wrapping;
  120083. this._groundMirror.gammaSpace = false;
  120084. if (this._groundMirror.renderList) {
  120085. for (var i = 0; i < this._scene.meshes.length; i++) {
  120086. var mesh = this._scene.meshes[i];
  120087. if (mesh !== this._ground &&
  120088. mesh !== this._skybox &&
  120089. mesh !== this._rootMesh) {
  120090. this._groundMirror.renderList.push(mesh);
  120091. }
  120092. }
  120093. }
  120094. }
  120095. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  120096. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  120097. };
  120098. /**
  120099. * Setup the ground to receive the mirror texture.
  120100. */
  120101. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  120102. if (this._groundMaterial) {
  120103. this._groundMaterial.reflectionTexture = this._groundMirror;
  120104. this._groundMaterial.reflectionFresnel = true;
  120105. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  120106. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  120107. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  120108. }
  120109. };
  120110. /**
  120111. * Setup the skybox according to the specified options.
  120112. */
  120113. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  120114. var _this = this;
  120115. if (!this._skybox || this._skybox.isDisposed()) {
  120116. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  120117. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  120118. }
  120119. this._skybox.parent = this._rootMesh;
  120120. };
  120121. /**
  120122. * Setup the skybox material according to the specified options.
  120123. */
  120124. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  120125. if (!this._skybox) {
  120126. return;
  120127. }
  120128. if (!this._skyboxMaterial) {
  120129. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  120130. }
  120131. this._skyboxMaterial.useRGBColor = false;
  120132. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  120133. this._skyboxMaterial.enableNoise = true;
  120134. this._skybox.material = this._skyboxMaterial;
  120135. };
  120136. /**
  120137. * Setup the skybox reflection texture according to the specified options.
  120138. */
  120139. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  120140. if (!this._skyboxMaterial) {
  120141. return;
  120142. }
  120143. if (this._skyboxTexture) {
  120144. return;
  120145. }
  120146. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  120147. this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;
  120148. return;
  120149. }
  120150. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  120151. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  120152. this._skyboxTexture.gammaSpace = false;
  120153. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  120154. };
  120155. /**
  120156. * Dispose all the elements created by the Helper.
  120157. */
  120158. EnvironmentHelper.prototype.dispose = function () {
  120159. if (this._groundMaterial) {
  120160. this._groundMaterial.dispose(true, true);
  120161. }
  120162. if (this._skyboxMaterial) {
  120163. this._skyboxMaterial.dispose(true, true);
  120164. }
  120165. this._rootMesh.dispose(false);
  120166. };
  120167. /**
  120168. * Default ground texture URL.
  120169. */
  120170. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  120171. /**
  120172. * Default skybox texture URL.
  120173. */
  120174. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  120175. /**
  120176. * Default environment texture URL.
  120177. */
  120178. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.env";
  120179. return EnvironmentHelper;
  120180. }());
  120181. BABYLON.EnvironmentHelper = EnvironmentHelper;
  120182. })(BABYLON || (BABYLON = {}));
  120183. //# sourceMappingURL=babylon.environmentHelper.js.map
  120184. var BABYLON;
  120185. (function (BABYLON) {
  120186. /** Internal class used to store shapes for emitters */
  120187. var ParticleSystemSetEmitterCreationOptions = /** @class */ (function () {
  120188. function ParticleSystemSetEmitterCreationOptions() {
  120189. }
  120190. return ParticleSystemSetEmitterCreationOptions;
  120191. }());
  120192. /**
  120193. * Represents a set of particle systems working together to create a specific effect
  120194. */
  120195. var ParticleSystemSet = /** @class */ (function () {
  120196. function ParticleSystemSet() {
  120197. /**
  120198. * Gets the particle system list
  120199. */
  120200. this.systems = new Array();
  120201. }
  120202. Object.defineProperty(ParticleSystemSet.prototype, "emitterNode", {
  120203. /**
  120204. * Gets the emitter node used with this set
  120205. */
  120206. get: function () {
  120207. return this._emitterNode;
  120208. },
  120209. enumerable: true,
  120210. configurable: true
  120211. });
  120212. /**
  120213. * Creates a new emitter mesh as a sphere
  120214. * @param options defines the options used to create the sphere
  120215. * @param renderingGroupId defines the renderingGroupId to use for the sphere
  120216. * @param scene defines the hosting scene
  120217. */
  120218. ParticleSystemSet.prototype.setEmitterAsSphere = function (options, renderingGroupId, scene) {
  120219. if (this._emitterNode) {
  120220. this._emitterNode.dispose();
  120221. }
  120222. this._emitterCreationOptions = {
  120223. kind: "Sphere",
  120224. options: options,
  120225. renderingGroupId: renderingGroupId
  120226. };
  120227. var emitterMesh = BABYLON.MeshBuilder.CreateSphere("emitterSphere", { diameter: options.diameter, segments: options.segments }, scene);
  120228. emitterMesh.renderingGroupId = renderingGroupId;
  120229. var material = new BABYLON.StandardMaterial("emitterSphereMaterial", scene);
  120230. material.emissiveColor = options.color;
  120231. emitterMesh.material = material;
  120232. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  120233. var system = _a[_i];
  120234. system.emitter = emitterMesh;
  120235. }
  120236. this._emitterNode = emitterMesh;
  120237. };
  120238. /**
  120239. * Starts all particle systems of the set
  120240. * @param emitter defines an optional mesh to use as emitter for the particle systems
  120241. */
  120242. ParticleSystemSet.prototype.start = function (emitter) {
  120243. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  120244. var system = _a[_i];
  120245. if (emitter) {
  120246. system.emitter = emitter;
  120247. }
  120248. system.start();
  120249. }
  120250. };
  120251. /**
  120252. * Release all associated resources
  120253. */
  120254. ParticleSystemSet.prototype.dispose = function () {
  120255. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  120256. var system = _a[_i];
  120257. system.dispose();
  120258. }
  120259. this.systems = [];
  120260. if (this._emitterNode) {
  120261. this._emitterNode.dispose();
  120262. this._emitterNode = null;
  120263. }
  120264. };
  120265. /**
  120266. * Serialize the set into a JSON compatible object
  120267. * @returns a JSON compatible representation of the set
  120268. */
  120269. ParticleSystemSet.prototype.serialize = function () {
  120270. var result = {};
  120271. result.systems = [];
  120272. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  120273. var system = _a[_i];
  120274. result.systems.push(system.serialize());
  120275. }
  120276. if (this._emitterNode) {
  120277. result.emitter = this._emitterCreationOptions;
  120278. }
  120279. return result;
  120280. };
  120281. /**
  120282. * Parse a new ParticleSystemSet from a serialized source
  120283. * @param data defines a JSON compatible representation of the set
  120284. * @param scene defines the hosting scene
  120285. * @param gpu defines if we want GPU particles or CPU particles
  120286. * @returns a new ParticleSystemSet
  120287. */
  120288. ParticleSystemSet.Parse = function (data, scene, gpu) {
  120289. if (gpu === void 0) { gpu = false; }
  120290. var result = new ParticleSystemSet();
  120291. var rootUrl = BABYLON.ParticleHelper.BaseAssetsUrl + "/textures/";
  120292. scene = scene || BABYLON.Engine.LastCreatedScene;
  120293. for (var _i = 0, _a = data.systems; _i < _a.length; _i++) {
  120294. var system = _a[_i];
  120295. result.systems.push(gpu ? BABYLON.GPUParticleSystem.Parse(system, scene, rootUrl, true) : BABYLON.ParticleSystem.Parse(system, scene, rootUrl, true));
  120296. }
  120297. if (data.emitter) {
  120298. var options = data.emitter.options;
  120299. switch (data.emitter.kind) {
  120300. case "Sphere":
  120301. result.setEmitterAsSphere({
  120302. diameter: options.diameter,
  120303. segments: options.segments,
  120304. color: BABYLON.Color3.FromArray(options.color)
  120305. }, data.emitter.renderingGroupId, scene);
  120306. break;
  120307. }
  120308. }
  120309. return result;
  120310. };
  120311. return ParticleSystemSet;
  120312. }());
  120313. BABYLON.ParticleSystemSet = ParticleSystemSet;
  120314. })(BABYLON || (BABYLON = {}));
  120315. //# sourceMappingURL=babylon.particleSystemSet.js.map
  120316. var BABYLON;
  120317. (function (BABYLON) {
  120318. /**
  120319. * This class is made for on one-liner static method to help creating particle system set.
  120320. */
  120321. var ParticleHelper = /** @class */ (function () {
  120322. function ParticleHelper() {
  120323. }
  120324. /**
  120325. * Create a default particle system that you can tweak
  120326. * @param emitter defines the emitter to use
  120327. * @param capacity defines the system capacity (default is 500 particles)
  120328. * @param scene defines the hosting scene
  120329. * @param useGPU defines if a GPUParticleSystem must be created (default is false)
  120330. * @returns the new Particle system
  120331. */
  120332. ParticleHelper.CreateDefault = function (emitter, capacity, scene, useGPU) {
  120333. if (capacity === void 0) { capacity = 500; }
  120334. if (useGPU === void 0) { useGPU = false; }
  120335. var system;
  120336. if (useGPU) {
  120337. system = new BABYLON.GPUParticleSystem("default system", { capacity: capacity }, scene);
  120338. }
  120339. else {
  120340. system = new BABYLON.ParticleSystem("default system", capacity, scene);
  120341. }
  120342. system.emitter = emitter;
  120343. system.particleTexture = new BABYLON.Texture("https://www.babylonjs.com/assets/Flare.png", system.getScene());
  120344. system.createConeEmitter(0.1, Math.PI / 4);
  120345. // Particle color
  120346. system.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  120347. system.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  120348. system.colorDead = new BABYLON.Color4(1.0, 1.0, 1.0, 0.0);
  120349. // Particle Size
  120350. system.minSize = 0.1;
  120351. system.maxSize = 0.1;
  120352. // Emission speed
  120353. system.minEmitPower = 2;
  120354. system.maxEmitPower = 2;
  120355. // Update speed
  120356. system.updateSpeed = 1 / 60;
  120357. system.emitRate = 30;
  120358. return system;
  120359. };
  120360. /**
  120361. * This is the main static method (one-liner) of this helper to create different particle systems
  120362. * @param type This string represents the type to the particle system to create
  120363. * @param scene The scene where the particle system should live
  120364. * @param gpu If the system will use gpu
  120365. * @returns the ParticleSystemSet created
  120366. */
  120367. ParticleHelper.CreateAsync = function (type, scene, gpu) {
  120368. if (gpu === void 0) { gpu = false; }
  120369. if (!scene) {
  120370. scene = BABYLON.Engine.LastCreatedScene;
  120371. }
  120372. var token = {};
  120373. scene._addPendingData(token);
  120374. return new Promise(function (resolve, reject) {
  120375. if (gpu && !BABYLON.GPUParticleSystem.IsSupported) {
  120376. scene._removePendingData(token);
  120377. return reject("Particle system with GPU is not supported.");
  120378. }
  120379. BABYLON.Tools.LoadFile(ParticleHelper.BaseAssetsUrl + "/systems/" + type + ".json", function (data, response) {
  120380. scene._removePendingData(token);
  120381. var newData = JSON.parse(data.toString());
  120382. return resolve(BABYLON.ParticleSystemSet.Parse(newData, scene, gpu));
  120383. }, undefined, undefined, undefined, function (req, exception) {
  120384. scene._removePendingData(token);
  120385. return reject("An error occured while the creation of your particle system. Check if your type '" + type + "' exists.");
  120386. });
  120387. });
  120388. };
  120389. /**
  120390. * Static function used to export a particle system to a ParticleSystemSet variable.
  120391. * Please note that the emitter shape is not exported
  120392. * @param systems defines the particle systems to export
  120393. * @returns the created particle system set
  120394. */
  120395. ParticleHelper.ExportSet = function (systems) {
  120396. var set = new BABYLON.ParticleSystemSet();
  120397. for (var _i = 0, systems_1 = systems; _i < systems_1.length; _i++) {
  120398. var system = systems_1[_i];
  120399. set.systems.push(system);
  120400. }
  120401. return set;
  120402. };
  120403. /**
  120404. * Gets or sets base Assets URL
  120405. */
  120406. ParticleHelper.BaseAssetsUrl = "https://assets.babylonjs.com/particles";
  120407. return ParticleHelper;
  120408. }());
  120409. BABYLON.ParticleHelper = ParticleHelper;
  120410. })(BABYLON || (BABYLON = {}));
  120411. //# sourceMappingURL=babylon.particleHelper.js.map
  120412. var BABYLON;
  120413. (function (BABYLON) {
  120414. /**
  120415. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  120416. * As a subclass of TransformNode, this allow parenting to the camera or multiple videos with different locations in the scene.
  120417. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  120418. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  120419. */
  120420. var VideoDome = /** @class */ (function (_super) {
  120421. __extends(VideoDome, _super);
  120422. /**
  120423. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  120424. * @param name Element's name, child elements will append suffixes for their own names.
  120425. * @param urlsOrVideo defines the url(s) or the video element to use
  120426. * @param options An object containing optional or exposed sub element properties
  120427. */
  120428. function VideoDome(name, urlsOrVideo, options, scene) {
  120429. var _this = _super.call(this, name, scene) || this;
  120430. _this._useDirectMapping = false;
  120431. // set defaults and manage values
  120432. name = name || "videoDome";
  120433. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  120434. options.clickToPlay = Boolean(options.clickToPlay);
  120435. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  120436. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  120437. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  120438. if (options.useDirectMapping === undefined) {
  120439. _this._useDirectMapping = true;
  120440. }
  120441. else {
  120442. _this._useDirectMapping = options.useDirectMapping;
  120443. }
  120444. _this._setReady(false);
  120445. // create
  120446. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true, poster: options.poster };
  120447. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  120448. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, _this._useDirectMapping, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  120449. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  120450. texture.onLoadObservable.addOnce(function () {
  120451. _this._setReady(true);
  120452. });
  120453. // configure material
  120454. material.useEquirectangularFOV = true;
  120455. material.fovMultiplier = 1.0;
  120456. material.opacityFresnel = false;
  120457. if (_this._useDirectMapping) {
  120458. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  120459. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  120460. material.diffuseTexture = texture;
  120461. }
  120462. else {
  120463. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  120464. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  120465. material.reflectionTexture = texture;
  120466. }
  120467. // configure mesh
  120468. _this._mesh.material = material;
  120469. _this._mesh.parent = _this;
  120470. // optional configuration
  120471. if (options.clickToPlay) {
  120472. scene.onPointerUp = function () {
  120473. _this._videoTexture.video.play();
  120474. };
  120475. }
  120476. return _this;
  120477. }
  120478. Object.defineProperty(VideoDome.prototype, "videoTexture", {
  120479. /**
  120480. * Gets the video texture being displayed on the sphere
  120481. */
  120482. get: function () {
  120483. return this._videoTexture;
  120484. },
  120485. enumerable: true,
  120486. configurable: true
  120487. });
  120488. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  120489. /**
  120490. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  120491. * Also see the options.resolution property.
  120492. */
  120493. get: function () {
  120494. return this._material.fovMultiplier;
  120495. },
  120496. set: function (value) {
  120497. this._material.fovMultiplier = value;
  120498. },
  120499. enumerable: true,
  120500. configurable: true
  120501. });
  120502. /**
  120503. * Releases resources associated with this node.
  120504. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  120505. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  120506. */
  120507. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  120508. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  120509. this._videoTexture.dispose();
  120510. this._mesh.dispose();
  120511. this._material.dispose();
  120512. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  120513. };
  120514. return VideoDome;
  120515. }(BABYLON.TransformNode));
  120516. BABYLON.VideoDome = VideoDome;
  120517. })(BABYLON || (BABYLON = {}));
  120518. //# sourceMappingURL=babylon.videoDome.js.map
  120519. var BABYLON;
  120520. (function (BABYLON) {
  120521. /**
  120522. * Display a 360 degree photo on an approximately spherical surface, useful for VR applications or skyboxes.
  120523. * As a subclass of TransformNode, this allow parenting to the camera with different locations in the scene.
  120524. * This class achieves its effect with a Texture and a correctly configured BackgroundMaterial on an inverted sphere.
  120525. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  120526. */
  120527. var PhotoDome = /** @class */ (function (_super) {
  120528. __extends(PhotoDome, _super);
  120529. /**
  120530. * Create an instance of this class and pass through the parameters to the relevant classes, Texture, StandardMaterial, and Mesh.
  120531. * @param name Element's name, child elements will append suffixes for their own names.
  120532. * @param urlsOfPhoto defines the url of the photo to display
  120533. * @param options defines an object containing optional or exposed sub element properties
  120534. * @param onError defines a callback called when an error occured while loading the texture
  120535. */
  120536. function PhotoDome(name, urlOfPhoto, options, scene, onError) {
  120537. if (onError === void 0) { onError = null; }
  120538. var _this = _super.call(this, name, scene) || this;
  120539. _this._useDirectMapping = false;
  120540. /**
  120541. * Observable raised when an error occured while loading the 360 image
  120542. */
  120543. _this.onLoadErrorObservable = new BABYLON.Observable();
  120544. // set defaults and manage values
  120545. name = name || "photoDome";
  120546. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  120547. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  120548. if (options.useDirectMapping === undefined) {
  120549. _this._useDirectMapping = true;
  120550. }
  120551. else {
  120552. _this._useDirectMapping = options.useDirectMapping;
  120553. }
  120554. _this._setReady(false);
  120555. // create
  120556. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  120557. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  120558. // configure material
  120559. material.opacityFresnel = false;
  120560. material.useEquirectangularFOV = true;
  120561. material.fovMultiplier = 1.0;
  120562. _this.photoTexture = new BABYLON.Texture(urlOfPhoto, scene, true, !_this._useDirectMapping, undefined, undefined, function (message, exception) {
  120563. _this.onLoadErrorObservable.notifyObservers(message || "Unknown error occured");
  120564. if (onError) {
  120565. onError(message, exception);
  120566. }
  120567. });
  120568. _this.photoTexture.onLoadObservable.addOnce(function () {
  120569. _this._setReady(true);
  120570. });
  120571. // configure mesh
  120572. _this._mesh.material = material;
  120573. _this._mesh.parent = _this;
  120574. return _this;
  120575. }
  120576. Object.defineProperty(PhotoDome.prototype, "photoTexture", {
  120577. /**
  120578. * Gets or sets the texture being displayed on the sphere
  120579. */
  120580. get: function () {
  120581. return this._photoTexture;
  120582. },
  120583. set: function (value) {
  120584. if (this._photoTexture === value) {
  120585. return;
  120586. }
  120587. this._photoTexture = value;
  120588. if (this._useDirectMapping) {
  120589. this._photoTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  120590. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  120591. this._material.diffuseTexture = this._photoTexture;
  120592. }
  120593. else {
  120594. this._photoTexture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  120595. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  120596. this._material.reflectionTexture = this._photoTexture;
  120597. }
  120598. },
  120599. enumerable: true,
  120600. configurable: true
  120601. });
  120602. Object.defineProperty(PhotoDome.prototype, "fovMultiplier", {
  120603. /**
  120604. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  120605. * Also see the options.resolution property.
  120606. */
  120607. get: function () {
  120608. return this._material.fovMultiplier;
  120609. },
  120610. set: function (value) {
  120611. this._material.fovMultiplier = value;
  120612. },
  120613. enumerable: true,
  120614. configurable: true
  120615. });
  120616. /**
  120617. * Releases resources associated with this node.
  120618. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  120619. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  120620. */
  120621. PhotoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  120622. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  120623. this._photoTexture.dispose();
  120624. this._mesh.dispose();
  120625. this._material.dispose();
  120626. this.onLoadErrorObservable.clear();
  120627. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  120628. };
  120629. return PhotoDome;
  120630. }(BABYLON.TransformNode));
  120631. BABYLON.PhotoDome = PhotoDome;
  120632. })(BABYLON || (BABYLON = {}));
  120633. //# sourceMappingURL=babylon.photoDome.js.map
  120634. var BABYLON;
  120635. (function (BABYLON) {
  120636. /** @hidden */
  120637. var _OcclusionDataStorage = /** @class */ (function () {
  120638. function _OcclusionDataStorage() {
  120639. /** @hidden */
  120640. this.occlusionInternalRetryCounter = 0;
  120641. /** @hidden */
  120642. this.isOcclusionQueryInProgress = false;
  120643. /** @hidden */
  120644. this.isOccluded = false;
  120645. /** @hidden */
  120646. this.occlusionRetryCount = -1;
  120647. /** @hidden */
  120648. this.occlusionType = BABYLON.AbstractMesh.OCCLUSION_TYPE_NONE;
  120649. /** @hidden */
  120650. this.occlusionQueryAlgorithmType = BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  120651. }
  120652. return _OcclusionDataStorage;
  120653. }());
  120654. BABYLON.Engine.prototype.createQuery = function () {
  120655. return this._gl.createQuery();
  120656. };
  120657. BABYLON.Engine.prototype.deleteQuery = function (query) {
  120658. this._gl.deleteQuery(query);
  120659. return this;
  120660. };
  120661. BABYLON.Engine.prototype.isQueryResultAvailable = function (query) {
  120662. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  120663. };
  120664. BABYLON.Engine.prototype.getQueryResult = function (query) {
  120665. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  120666. };
  120667. BABYLON.Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  120668. var glAlgorithm = this._getGlAlgorithmType(algorithmType);
  120669. this._gl.beginQuery(glAlgorithm, query);
  120670. return this;
  120671. };
  120672. BABYLON.Engine.prototype.endOcclusionQuery = function (algorithmType) {
  120673. var glAlgorithm = this._getGlAlgorithmType(algorithmType);
  120674. this._gl.endQuery(glAlgorithm);
  120675. return this;
  120676. };
  120677. BABYLON.Engine.prototype._createTimeQuery = function () {
  120678. var timerQuery = this.getCaps().timerQuery;
  120679. if (timerQuery.createQueryEXT) {
  120680. return timerQuery.createQueryEXT();
  120681. }
  120682. return this.createQuery();
  120683. };
  120684. BABYLON.Engine.prototype._deleteTimeQuery = function (query) {
  120685. var timerQuery = this.getCaps().timerQuery;
  120686. if (timerQuery.deleteQueryEXT) {
  120687. timerQuery.deleteQueryEXT(query);
  120688. return;
  120689. }
  120690. this.deleteQuery(query);
  120691. };
  120692. BABYLON.Engine.prototype._getTimeQueryResult = function (query) {
  120693. var timerQuery = this.getCaps().timerQuery;
  120694. if (timerQuery.getQueryObjectEXT) {
  120695. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  120696. }
  120697. return this.getQueryResult(query);
  120698. };
  120699. BABYLON.Engine.prototype._getTimeQueryAvailability = function (query) {
  120700. var timerQuery = this.getCaps().timerQuery;
  120701. if (timerQuery.getQueryObjectEXT) {
  120702. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  120703. }
  120704. return this.isQueryResultAvailable(query);
  120705. };
  120706. BABYLON.Engine.prototype.startTimeQuery = function () {
  120707. var caps = this.getCaps();
  120708. var timerQuery = caps.timerQuery;
  120709. if (!timerQuery) {
  120710. return null;
  120711. }
  120712. var token = new BABYLON._TimeToken();
  120713. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  120714. if (caps.canUseTimestampForTimerQuery) {
  120715. token._startTimeQuery = this._createTimeQuery();
  120716. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  120717. }
  120718. else {
  120719. if (this._currentNonTimestampToken) {
  120720. return this._currentNonTimestampToken;
  120721. }
  120722. token._timeElapsedQuery = this._createTimeQuery();
  120723. if (timerQuery.beginQueryEXT) {
  120724. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  120725. }
  120726. else {
  120727. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  120728. }
  120729. this._currentNonTimestampToken = token;
  120730. }
  120731. return token;
  120732. };
  120733. BABYLON.Engine.prototype.endTimeQuery = function (token) {
  120734. var caps = this.getCaps();
  120735. var timerQuery = caps.timerQuery;
  120736. if (!timerQuery || !token) {
  120737. return -1;
  120738. }
  120739. if (caps.canUseTimestampForTimerQuery) {
  120740. if (!token._startTimeQuery) {
  120741. return -1;
  120742. }
  120743. if (!token._endTimeQuery) {
  120744. token._endTimeQuery = this._createTimeQuery();
  120745. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  120746. }
  120747. }
  120748. else if (!token._timeElapsedQueryEnded) {
  120749. if (!token._timeElapsedQuery) {
  120750. return -1;
  120751. }
  120752. if (timerQuery.endQueryEXT) {
  120753. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  120754. }
  120755. else {
  120756. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  120757. }
  120758. token._timeElapsedQueryEnded = true;
  120759. }
  120760. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  120761. var available = false;
  120762. if (token._endTimeQuery) {
  120763. available = this._getTimeQueryAvailability(token._endTimeQuery);
  120764. }
  120765. else if (token._timeElapsedQuery) {
  120766. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  120767. }
  120768. if (available && !disjoint) {
  120769. var result = 0;
  120770. if (caps.canUseTimestampForTimerQuery) {
  120771. if (!token._startTimeQuery || !token._endTimeQuery) {
  120772. return -1;
  120773. }
  120774. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  120775. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  120776. result = timeEnd - timeStart;
  120777. this._deleteTimeQuery(token._startTimeQuery);
  120778. this._deleteTimeQuery(token._endTimeQuery);
  120779. token._startTimeQuery = null;
  120780. token._endTimeQuery = null;
  120781. }
  120782. else {
  120783. if (!token._timeElapsedQuery) {
  120784. return -1;
  120785. }
  120786. result = this._getTimeQueryResult(token._timeElapsedQuery);
  120787. this._deleteTimeQuery(token._timeElapsedQuery);
  120788. token._timeElapsedQuery = null;
  120789. token._timeElapsedQueryEnded = false;
  120790. this._currentNonTimestampToken = null;
  120791. }
  120792. return result;
  120793. }
  120794. return -1;
  120795. };
  120796. BABYLON.Engine.prototype._getGlAlgorithmType = function (algorithmType) {
  120797. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  120798. };
  120799. Object.defineProperty(BABYLON.AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  120800. get: function () {
  120801. return this._occlusionDataStorage.isOcclusionQueryInProgress;
  120802. },
  120803. enumerable: false,
  120804. configurable: true
  120805. });
  120806. Object.defineProperty(BABYLON.AbstractMesh.prototype, "_occlusionDataStorage", {
  120807. get: function () {
  120808. if (!this.__occlusionDataStorage) {
  120809. this.__occlusionDataStorage = new _OcclusionDataStorage();
  120810. }
  120811. return this.__occlusionDataStorage;
  120812. },
  120813. enumerable: false,
  120814. configurable: true
  120815. });
  120816. Object.defineProperty(BABYLON.AbstractMesh.prototype, "isOccluded", {
  120817. get: function () {
  120818. return this._occlusionDataStorage.isOccluded;
  120819. },
  120820. set: function (value) {
  120821. this._occlusionDataStorage.isOccluded = value;
  120822. },
  120823. enumerable: true,
  120824. configurable: true
  120825. });
  120826. Object.defineProperty(BABYLON.AbstractMesh.prototype, "occlusionQueryAlgorithmType", {
  120827. get: function () {
  120828. return this._occlusionDataStorage.occlusionQueryAlgorithmType;
  120829. },
  120830. set: function (value) {
  120831. this._occlusionDataStorage.occlusionQueryAlgorithmType = value;
  120832. },
  120833. enumerable: true,
  120834. configurable: true
  120835. });
  120836. Object.defineProperty(BABYLON.AbstractMesh.prototype, "occlusionType", {
  120837. get: function () {
  120838. return this._occlusionDataStorage.occlusionType;
  120839. },
  120840. set: function (value) {
  120841. this._occlusionDataStorage.occlusionType = value;
  120842. },
  120843. enumerable: true,
  120844. configurable: true
  120845. });
  120846. Object.defineProperty(BABYLON.AbstractMesh.prototype, "occlusionRetryCount", {
  120847. get: function () {
  120848. return this._occlusionDataStorage.occlusionRetryCount;
  120849. },
  120850. set: function (value) {
  120851. this._occlusionDataStorage.occlusionRetryCount = value;
  120852. },
  120853. enumerable: true,
  120854. configurable: true
  120855. });
  120856. // We also need to update AbstractMesh as there is a portion of the code there
  120857. BABYLON.AbstractMesh.prototype._checkOcclusionQuery = function () {
  120858. var dataStorage = this._occlusionDataStorage;
  120859. if (dataStorage.occlusionType === BABYLON.AbstractMesh.OCCLUSION_TYPE_NONE) {
  120860. dataStorage.isOccluded = false;
  120861. return false;
  120862. }
  120863. var engine = this.getEngine();
  120864. if (engine.webGLVersion < 2) {
  120865. dataStorage.isOccluded = false;
  120866. return false;
  120867. }
  120868. if (!engine.isQueryResultAvailable) { // Occlusion query where not referenced
  120869. dataStorage.isOccluded = false;
  120870. return false;
  120871. }
  120872. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  120873. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  120874. if (isOcclusionQueryAvailable) {
  120875. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  120876. dataStorage.isOcclusionQueryInProgress = false;
  120877. dataStorage.occlusionInternalRetryCounter = 0;
  120878. dataStorage.isOccluded = occlusionQueryResult === 1 ? false : true;
  120879. }
  120880. else {
  120881. dataStorage.occlusionInternalRetryCounter++;
  120882. if (dataStorage.occlusionRetryCount !== -1 && dataStorage.occlusionInternalRetryCounter > dataStorage.occlusionRetryCount) {
  120883. dataStorage.isOcclusionQueryInProgress = false;
  120884. dataStorage.occlusionInternalRetryCounter = 0;
  120885. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  120886. // if strict continue the last state of the object.
  120887. dataStorage.isOccluded = dataStorage.occlusionType === BABYLON.AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : dataStorage.isOccluded;
  120888. }
  120889. else {
  120890. return false;
  120891. }
  120892. }
  120893. }
  120894. var scene = this.getScene();
  120895. if (scene.getBoundingBoxRenderer) {
  120896. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  120897. if (!this._occlusionQuery) {
  120898. this._occlusionQuery = engine.createQuery();
  120899. }
  120900. engine.beginOcclusionQuery(dataStorage.occlusionQueryAlgorithmType, this._occlusionQuery);
  120901. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  120902. engine.endOcclusionQuery(dataStorage.occlusionQueryAlgorithmType);
  120903. this._occlusionDataStorage.isOcclusionQueryInProgress = true;
  120904. }
  120905. return dataStorage.isOccluded;
  120906. };
  120907. })(BABYLON || (BABYLON = {}));
  120908. //# sourceMappingURL=babylon.engine.occlusionQuery.js.map
  120909. var BABYLON;
  120910. (function (BABYLON) {
  120911. /**
  120912. * Class used to generate noise procedural textures
  120913. */
  120914. var NoiseProceduralTexture = /** @class */ (function (_super) {
  120915. __extends(NoiseProceduralTexture, _super);
  120916. /**
  120917. * Creates a new NoiseProceduralTexture
  120918. * @param name defines the name fo the texture
  120919. * @param size defines the size of the texture (default is 256)
  120920. * @param scene defines the hosting scene
  120921. * @param fallbackTexture defines the texture to use if the NoiseProceduralTexture can't be created
  120922. * @param generateMipMaps defines if mipmaps must be generated (true by default)
  120923. */
  120924. function NoiseProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  120925. if (size === void 0) { size = 256; }
  120926. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  120927. var _this = _super.call(this, name, size, "noise", scene, fallbackTexture, generateMipMaps) || this;
  120928. _this._time = 0;
  120929. /** Gets or sets a value between 0 and 1 indicating the overall brightness of the texture (default is 0.2) */
  120930. _this.brightness = 0.2;
  120931. /** Defines the number of octaves to process */
  120932. _this.octaves = 3;
  120933. /** Defines the level of persistence (0.8 by default) */
  120934. _this.persistence = 0.8;
  120935. /** Gets or sets animation speed factor (default is 1) */
  120936. _this.animationSpeedFactor = 1;
  120937. _this.autoClear = false;
  120938. _this._updateShaderUniforms();
  120939. return _this;
  120940. }
  120941. NoiseProceduralTexture.prototype._updateShaderUniforms = function () {
  120942. var scene = this.getScene();
  120943. if (!scene) {
  120944. return;
  120945. }
  120946. this._time += scene.getAnimationRatio() * this.animationSpeedFactor * 0.01;
  120947. this.setFloat("brightness", this.brightness);
  120948. this.setFloat("persistence", this.persistence);
  120949. this.setFloat("timeScale", this._time);
  120950. };
  120951. NoiseProceduralTexture.prototype._getDefines = function () {
  120952. return "#define OCTAVES " + (this.octaves | 0);
  120953. };
  120954. /** Generate the current state of the procedural texture */
  120955. NoiseProceduralTexture.prototype.render = function (useCameraPostProcess) {
  120956. this._updateShaderUniforms();
  120957. _super.prototype.render.call(this, useCameraPostProcess);
  120958. };
  120959. /**
  120960. * Serializes this noise procedural texture
  120961. * @returns a serialized noise procedural texture object
  120962. */
  120963. NoiseProceduralTexture.prototype.serialize = function () {
  120964. var serializationObject = {};
  120965. serializationObject.customType = "BABYLON.NoiseProceduralTexture";
  120966. serializationObject.brightness = this.brightness;
  120967. serializationObject.octaves = this.octaves;
  120968. serializationObject.persistence = this.persistence;
  120969. serializationObject.animationSpeedFactor = this.animationSpeedFactor;
  120970. serializationObject.size = this.getSize().width;
  120971. serializationObject.generateMipMaps = this._generateMipMaps;
  120972. return serializationObject;
  120973. };
  120974. /**
  120975. * Creates a NoiseProceduralTexture from parsed noise procedural texture data
  120976. * @param parsedTexture defines parsed texture data
  120977. * @param scene defines the current scene
  120978. * @param rootUrl defines the root URL containing noise procedural texture information
  120979. * @returns a parsed NoiseProceduralTexture
  120980. */
  120981. NoiseProceduralTexture.Parse = function (parsedTexture, scene, rootUrl) {
  120982. var texture = new NoiseProceduralTexture(parsedTexture.name, parsedTexture.size, scene, undefined, parsedTexture.generateMipMaps);
  120983. texture.brightness = parsedTexture.brightness;
  120984. texture.octaves = parsedTexture.octaves;
  120985. texture.persistence = parsedTexture.persistence;
  120986. texture.animationSpeedFactor = parsedTexture.animationSpeedFactor;
  120987. return texture;
  120988. };
  120989. return NoiseProceduralTexture;
  120990. }(BABYLON.ProceduralTexture));
  120991. BABYLON.NoiseProceduralTexture = NoiseProceduralTexture;
  120992. })(BABYLON || (BABYLON = {}));
  120993. //# sourceMappingURL=babylon.noiseProceduralTexture.js.map
  120994. var __assign = (this && this.__assign) || function () {
  120995. __assign = Object.assign || function(t) {
  120996. for (var s, i = 1, n = arguments.length; i < n; i++) {
  120997. s = arguments[i];
  120998. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  120999. t[p] = s[p];
  121000. }
  121001. return t;
  121002. };
  121003. return __assign.apply(this, arguments);
  121004. };
  121005. var BABYLON;
  121006. (function (BABYLON) {
  121007. /**
  121008. * This can helps recording videos from BabylonJS.
  121009. * This is based on the available WebRTC functionalities of the browser.
  121010. *
  121011. * @see http://doc.babylonjs.com/how_to/render_scene_on_a_video
  121012. */
  121013. var VideoRecorder = /** @class */ (function () {
  121014. /**
  121015. * Create a new VideoCapture object which can help converting what you see in Babylon to
  121016. * a video file.
  121017. * @param engine Defines the BabylonJS Engine you wish to record
  121018. * @param options Defines options that can be used to customized the capture
  121019. */
  121020. function VideoRecorder(engine, options) {
  121021. if (options === void 0) { options = null; }
  121022. if (!VideoRecorder.IsSupported(engine)) {
  121023. throw "Your browser does not support recording so far.";
  121024. }
  121025. var canvas = engine.getRenderingCanvas();
  121026. if (!canvas) {
  121027. throw "The babylon engine must have a canvas to be recorded";
  121028. }
  121029. this._canvas = canvas;
  121030. this._canvas.isRecording = false;
  121031. this._options = __assign({}, VideoRecorder._defaultOptions, options);
  121032. var stream = this._canvas.captureStream(this._options.fps);
  121033. this._mediaRecorder = new MediaRecorder(stream, { mimeType: this._options.mimeType });
  121034. this._mediaRecorder.ondataavailable = this._handleDataAvailable.bind(this);
  121035. this._mediaRecorder.onerror = this._handleError.bind(this);
  121036. this._mediaRecorder.onstop = this._handleStop.bind(this);
  121037. }
  121038. /**
  121039. * Returns wehther or not the VideoRecorder is available in your browser.
  121040. * @param engine Defines the Babylon Engine to check the support for
  121041. * @returns true if supported otherwise false
  121042. */
  121043. VideoRecorder.IsSupported = function (engine) {
  121044. var canvas = engine.getRenderingCanvas();
  121045. return (!!canvas && typeof canvas.captureStream === "function");
  121046. };
  121047. Object.defineProperty(VideoRecorder.prototype, "isRecording", {
  121048. /**
  121049. * True wether a recording is already in progress.
  121050. */
  121051. get: function () {
  121052. return !!this._canvas && this._canvas.isRecording;
  121053. },
  121054. enumerable: true,
  121055. configurable: true
  121056. });
  121057. /**
  121058. * Stops the current recording before the default capture timeout passed in the startRecording
  121059. * functions.
  121060. */
  121061. VideoRecorder.prototype.stopRecording = function () {
  121062. if (!this._canvas || !this._mediaRecorder) {
  121063. return;
  121064. }
  121065. if (!this.isRecording) {
  121066. return;
  121067. }
  121068. this._canvas.isRecording = false;
  121069. this._mediaRecorder.stop();
  121070. };
  121071. /**
  121072. * Starts recording the canvas for a max duration specified in parameters.
  121073. * @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.
  121074. * @param maxDuration Defines the maximum recording time in seconds.
  121075. * It default to 7 seconds. A value of zero will not stop automatically, you would need to call stopRecording manually.
  121076. * @return a promise callback at the end of the recording with the video data in Blob.
  121077. */
  121078. VideoRecorder.prototype.startRecording = function (fileName, maxDuration) {
  121079. var _this = this;
  121080. if (fileName === void 0) { fileName = "babylonjs.webm"; }
  121081. if (maxDuration === void 0) { maxDuration = 7; }
  121082. if (!this._canvas || !this._mediaRecorder) {
  121083. throw "Recorder has already been disposed";
  121084. }
  121085. if (this.isRecording) {
  121086. throw "Recording already in progress";
  121087. }
  121088. if (maxDuration > 0) {
  121089. setTimeout(function () {
  121090. _this.stopRecording();
  121091. }, maxDuration * 1000);
  121092. }
  121093. this._fileName = fileName;
  121094. this._recordedChunks = [];
  121095. this._resolve = null;
  121096. this._reject = null;
  121097. this._canvas.isRecording = true;
  121098. this._mediaRecorder.start(this._options.recordChunckSize);
  121099. return new Promise(function (resolve, reject) {
  121100. _this._resolve = resolve;
  121101. _this._reject = reject;
  121102. });
  121103. };
  121104. /**
  121105. * Releases internal resources used during the recording.
  121106. */
  121107. VideoRecorder.prototype.dispose = function () {
  121108. this._canvas = null;
  121109. this._mediaRecorder = null;
  121110. this._recordedChunks = [];
  121111. this._fileName = null;
  121112. this._resolve = null;
  121113. this._reject = null;
  121114. };
  121115. VideoRecorder.prototype._handleDataAvailable = function (event) {
  121116. if (event.data.size > 0) {
  121117. this._recordedChunks.push(event.data);
  121118. }
  121119. };
  121120. VideoRecorder.prototype._handleError = function (event) {
  121121. this.stopRecording();
  121122. if (this._reject) {
  121123. this._reject(event.error);
  121124. }
  121125. else {
  121126. throw new event.error();
  121127. }
  121128. };
  121129. VideoRecorder.prototype._handleStop = function () {
  121130. this.stopRecording();
  121131. var superBuffer = new Blob(this._recordedChunks);
  121132. if (this._resolve) {
  121133. this._resolve(superBuffer);
  121134. }
  121135. window.URL.createObjectURL(superBuffer);
  121136. if (this._fileName) {
  121137. BABYLON.Tools.Download(superBuffer, this._fileName);
  121138. }
  121139. };
  121140. VideoRecorder._defaultOptions = {
  121141. mimeType: "video/webm",
  121142. fps: 25,
  121143. recordChunckSize: 3000
  121144. };
  121145. return VideoRecorder;
  121146. }());
  121147. BABYLON.VideoRecorder = VideoRecorder;
  121148. })(BABYLON || (BABYLON = {}));
  121149. //# sourceMappingURL=babylon.videoRecorder.js.map
  121150. var BABYLON;
  121151. (function (BABYLON) {
  121152. BABYLON.Scene.prototype.createDefaultLight = function (replace) {
  121153. if (replace === void 0) { replace = false; }
  121154. // Dispose existing light in replace mode.
  121155. if (replace) {
  121156. if (this.lights) {
  121157. for (var i = 0; i < this.lights.length; i++) {
  121158. this.lights[i].dispose();
  121159. }
  121160. }
  121161. }
  121162. // Light
  121163. if (this.lights.length === 0) {
  121164. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  121165. }
  121166. };
  121167. BABYLON.Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  121168. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  121169. if (replace === void 0) { replace = false; }
  121170. if (attachCameraControls === void 0) { attachCameraControls = false; }
  121171. // Dispose existing camera in replace mode.
  121172. if (replace) {
  121173. if (this.activeCamera) {
  121174. this.activeCamera.dispose();
  121175. this.activeCamera = null;
  121176. }
  121177. }
  121178. // Camera
  121179. if (!this.activeCamera) {
  121180. var worldExtends = this.getWorldExtends();
  121181. var worldSize = worldExtends.max.subtract(worldExtends.min);
  121182. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  121183. var camera;
  121184. var radius = worldSize.length() * 1.5;
  121185. // empty scene scenario!
  121186. if (!isFinite(radius)) {
  121187. radius = 1;
  121188. worldCenter.copyFromFloats(0, 0, 0);
  121189. }
  121190. if (createArcRotateCamera) {
  121191. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  121192. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  121193. arcRotateCamera.wheelPrecision = 100 / radius;
  121194. camera = arcRotateCamera;
  121195. }
  121196. else {
  121197. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  121198. freeCamera.setTarget(worldCenter);
  121199. camera = freeCamera;
  121200. }
  121201. camera.minZ = radius * 0.01;
  121202. camera.maxZ = radius * 1000;
  121203. camera.speed = radius * 0.2;
  121204. this.activeCamera = camera;
  121205. var canvas = this.getEngine().getRenderingCanvas();
  121206. if (attachCameraControls && canvas) {
  121207. camera.attachControl(canvas);
  121208. }
  121209. }
  121210. };
  121211. BABYLON.Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  121212. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  121213. if (replace === void 0) { replace = false; }
  121214. if (attachCameraControls === void 0) { attachCameraControls = false; }
  121215. this.createDefaultLight(replace);
  121216. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  121217. };
  121218. BABYLON.Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur, setGlobalEnvTexture) {
  121219. if (pbr === void 0) { pbr = false; }
  121220. if (scale === void 0) { scale = 1000; }
  121221. if (blur === void 0) { blur = 0; }
  121222. if (setGlobalEnvTexture === void 0) { setGlobalEnvTexture = true; }
  121223. if (!environmentTexture) {
  121224. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  121225. return null;
  121226. }
  121227. if (setGlobalEnvTexture) {
  121228. if (environmentTexture) {
  121229. this.environmentTexture = environmentTexture;
  121230. }
  121231. }
  121232. // Skybox
  121233. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  121234. if (pbr) {
  121235. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  121236. hdrSkyboxMaterial.backFaceCulling = false;
  121237. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  121238. if (hdrSkyboxMaterial.reflectionTexture) {
  121239. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  121240. }
  121241. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  121242. hdrSkyboxMaterial.disableLighting = true;
  121243. hdrSkyboxMaterial.twoSidedLighting = true;
  121244. hdrSkybox.infiniteDistance = true;
  121245. hdrSkybox.material = hdrSkyboxMaterial;
  121246. }
  121247. else {
  121248. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  121249. skyboxMaterial.backFaceCulling = false;
  121250. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  121251. if (skyboxMaterial.reflectionTexture) {
  121252. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  121253. }
  121254. skyboxMaterial.disableLighting = true;
  121255. hdrSkybox.infiniteDistance = true;
  121256. hdrSkybox.material = skyboxMaterial;
  121257. }
  121258. hdrSkybox.isPickable = false;
  121259. return hdrSkybox;
  121260. };
  121261. BABYLON.Scene.prototype.createDefaultEnvironment = function (options) {
  121262. if (BABYLON.EnvironmentHelper) {
  121263. return new BABYLON.EnvironmentHelper(options, this);
  121264. }
  121265. return null;
  121266. };
  121267. BABYLON.Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  121268. if (webVROptions === void 0) { webVROptions = {}; }
  121269. return new BABYLON.VRExperienceHelper(this, webVROptions);
  121270. };
  121271. BABYLON.Scene.prototype.createDefaultXRExperienceAsync = function () {
  121272. var _this = this;
  121273. return BABYLON.WebXRExperienceHelper.CreateAsync(this).then(function (helper) {
  121274. var outputCanvas = new BABYLON.WebXRManagedOutputCanvas(helper);
  121275. return BABYLON.WebXREnterExitUI.CreateAsync(_this, helper, { outputCanvasContext: outputCanvas.canvasContext })
  121276. .then(function (ui) {
  121277. new BABYLON.WebXRInput(helper);
  121278. return helper;
  121279. });
  121280. });
  121281. };
  121282. })(BABYLON || (BABYLON = {}));
  121283. //# sourceMappingURL=babylon.sceneHelpers.js.map
  121284. 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 RGBDREFRACTION\nenvironmentRefraction.rgb=fromRGBD(environmentRefraction);\n#endif\n#ifdef GAMMAREFRACTION\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}\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}","passCubePixelShader":"\nvarying vec2 vUV;\nuniform samplerCube textureSampler;\nvoid main(void) \n{\nvec2 uv=vUV*2.0-1.0;\n#ifdef POSITIVEX\ngl_FragColor=textureCube(textureSampler,vec3(1.001,uv.y,uv.x));\n#endif\n#ifdef NEGATIVEX\ngl_FragColor=textureCube(textureSampler,vec3(-1.001,uv.y,uv.x));\n#endif\n#ifdef POSITIVEY\ngl_FragColor=textureCube(textureSampler,vec3(uv.y,1.001,uv.x));\n#endif\n#ifdef NEGATIVEY\ngl_FragColor=textureCube(textureSampler,vec3(uv.y,-1.001,uv.x));\n#endif\n#ifdef POSITIVEZ\ngl_FragColor=textureCube(textureSampler,vec3(uv,1.001));\n#endif\n#ifdef NEGATIVEZ\ngl_FragColor=textureCube(textureSampler,vec3(uv,-1.001));\n#endif\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\n#ifdef VELOCITY\nuniform mat4 previousWorldViewProjection;\nvarying vec4 vCurrentPosition;\nvarying vec4 vPreviousPosition;\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\n#ifdef VELOCITY\nvCurrentPosition=viewProjection*finalWorld*vec4(position,1.0);\nvPreviousPosition=previousWorldViewProjection*vec4(position,1.0);\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 VELOCITY\nvarying vec4 vCurrentPosition;\nvarying vec4 vPreviousPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<mrtFragmentDeclaration>[RENDER_TARGET_COUNT]\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[POSITION_INDEX]=vec4(vPosition,1.0);\n#endif\n#ifdef VELOCITY\nvec2 a=(vCurrentPosition.xy/vCurrentPosition.w)*0.5+0.5;\nvec2 b=(vPreviousPosition.xy/vPreviousPosition.w)*0.5+0.5;\nvec2 velocity=(a-b)*0.5+0.5;\nvelocity*=0.5+0.5;\nvelocity=vec2(pow(velocity.x,3.0),pow(velocity.y,3.0));\ngl_FragData[VELOCITY_INDEX]=vec4(velocity,0.0,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}","motionBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D velocitySampler;\nuniform float motionStrength;\nuniform float motionScale;\nuniform vec2 screenSize;\nvoid main(void)\n{\n#ifdef GEOMETRY_SUPPORTED\nvec2 texelSize=1.0/screenSize;\nvec2 velocityColor=texture2D(velocitySampler,vUV).rg;\nvec2 velocity=vec2(pow(velocityColor.r,1.0/3.0),pow(velocityColor.g,1.0/3.0))*2.0-1.0;\nvelocity*=motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint samplesCount=int(clamp(speed,1.0,SAMPLES));\nvelocity=normalize(velocity)*texelSize;\nfloat hlim=float(-samplesCount)*0.5+0.5;\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(SAMPLES); ++i)\n{\nif (i>=samplesCount)\nbreak;\nvec2 offset=vUV+velocity*(hlim+float(i));\nresult+=texture2D(textureSampler,offset);\n}\ngl_FragColor=result/float(samplesCount);\n#else\ngl_FragColor=texture2D(textureSampler,vUV);\n#endif\n}\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\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"};
  121285. BABYLON.Effect.IncludesShadersStore={"depthPrePass":"#ifdef DEPTHPREPASS\ngl_FragColor=vec4(0.,0.,0.,1.0);\nreturn;\n#endif","bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\n#ifdef BONETEXTURE\nuniform sampler2D boneSampler;\nuniform float boneTextureWidth;\n#else\nuniform mat4 mBones[BonesPerMesh];\n#endif \nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#ifdef BONETEXTURE\nmat4 readMatrixFromRawSampler(sampler2D smp,float index)\n{\nfloat offset=index*4.0; \nfloat dx=1.0/boneTextureWidth;\nvec4 m0=texture2D(smp,vec2(dx*(offset+0.5),0.));\nvec4 m1=texture2D(smp,vec2(dx*(offset+1.5),0.));\nvec4 m2=texture2D(smp,vec2(dx*(offset+2.5),0.));\nvec4 m3=texture2D(smp,vec2(dx*(offset+3.5),0.));\nreturn mat4(m0,m1,m2,m3);\n}\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;\n#ifdef BONETEXTURE\ninfluence=readMatrixFromRawSampler(boneSampler,matricesIndices[0])*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=readMatrixFromRawSampler(boneSampler,matricesIndices[1])*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=readMatrixFromRawSampler(boneSampler,matricesIndices[2])*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=readMatrixFromRawSampler(boneSampler,matricesIndices[3])*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=readMatrixFromRawSampler(boneSampler,matricesIndicesExtra[0])*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=readMatrixFromRawSampler(boneSampler,matricesIndicesExtra[1])*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=readMatrixFromRawSampler(boneSampler,matricesIndicesExtra[2])*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=readMatrixFromRawSampler(boneSampler,matricesIndicesExtra[3])*matricesWeightsExtra[3];\n#endif \n#else \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 \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\n#ifdef BONETEXTURE\nuniform sampler2D boneSampler;\n#else\nuniform mat4 mBones[BonesPerMesh];\n#endif \nin vec4 matricesIndices;\nin vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nin vec4 matricesIndicesExtra;\nin vec4 matricesWeightsExtra;\n#endif\n#ifdef BONETEXTURE\nmat4 readMatrixFromRawSampler(sampler2D smp,float index)\n{\nmat4 result;\nfloat offset=index*4.0; \nfloat dx=1.0/boneTextureWidth;\nresult[0]=texture(smp,vec2(dx*(offset+0.5),0.));\nresult[1]=texture(smp,vec2(dx*(offset+1.5),0.));\nresult[2]=texture(smp,vec2(dx*(offset+2.5),0.));\nresult[3]=texture(smp,vec2(dx*(offset+3.5),0.));\nreturn result;\n}\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};"};